april/may 1996

GAME DEVELOPER MAGAZINE GAME PLAN GGAMEAEM

Editorial Director Larry O’Brien [email protected] Senior Editor Nicole Freeman Network Games [email protected] Managing Editor Diane Anderson [email protected] Editorial Assistant Jana Outlaw [email protected] etwork gaming will recreate the growth I predict for 3D video boards, but Contributing Editors Alex Dunne [email protected] computer entertainment indus- they’ll become popular with niche, moti- Barbara Hanscome try and revitalize the cartridge vated buyers. Initially, this motivation will [email protected] market. Within a few years, come from network-based telephony and Chris Hecker online gaming will be the domi- multiplayer gaming of existing games. [email protected] nant form of computer recre- More importantly, ISDN should fill out Mike Michaels ation. Normally, I preach the the niche without jeopardizing bandwidth. [email protected] “horizon of predictability”— ISDN, however, remains a technology David Sieks [email protected] Nbeyond which nothing can be said with with a considerable barrier to entry. Most Editor-at-Large Alexander Antoniades certainty—is an astonishingly short 14 to people will wait for the big news. Which [email protected] 16 months away. Anyone who predicts will be high-bandwidth connections, cable beyond that is like a six-year-old on a modems or ATM-to-the-curb. Cover Photography Charles Ingram Photography whale-watching expedition, shouting, This is the fourth, and furthest out Publisher Veronica Costanza “There’s a whale,” and pointing randomly. element prepping us for an online gaming Group Director Regina Starr Ridley And network gaming isn’t going to be a explosion. I can’t predict whether to buy major force in the 14 to 16 months stock in cable companies or ATM manu- (although by the end of 1996, early facturers, since widespread availability of Advertising Sales Staff adopters will play exciting new games); it’s these technologies is years away. The Western Regional Sales Manager more likely to happen within 5 years. But bandwidth numbers of these technologies Steve Nikkola (415) 905-2256 [email protected] we’re on the eve of adopting several tech- are incredible—more than enough to make Promotions Manager/Eastern Regional Sales Manager nologies, which point to explosive growth believable the wildest ideas of network- Holly Meintzer (212) 615-2275 in multiplayer gaming. based applications. If these technologies [email protected] First and foremost, the world is get- are really able to deliver and transmit sever- ting wired. In other words, everyone will al megabits per second, a revolution as Marketing Manager Susan McDonald be able to at least “get to” game servers. profound as the arrival of the desktop PC Marketing Graphic Designer Azriel Hayes Second, 3D chips will take the mar- will follow. Advertising Production Coordinator Denise Temple ket by storm. In the cartridge market, one Finally, why did I say that network Director of Production Andrew A. Mickus need only look at the new generation of gaming will revitalize the cartridge market? Vice President/Circulation Jerry M. Okabe machines to be impressed, while the desk- Let’s talk about the Java terminals comput- Circulation Director Gina Oh top video card market has been fairly bland er magazines say have no market. They’re Associate Circulation Director Kathy Henry for several years as the limitations of Win- right to say people won’t download word Group Circulation Manager Mike Poplardo dows 3.1 overshadowed improvements in processors and work on their resumes with Assistant Circulation Manager Jamai Deuberry card technology, color-depth, and onboard an Internet terminal rather than their Manager Debra Caris RAM. The past 14 months have seen an $3,500 home PC; kids will download the Reprints Stella Valdez (916) 729-3633 unprecedented boom in the high-end of latest version of “Java Warriors,” to their the desktop 3D market—the technology cartridge machines. Sun’s second-tier Chairman of the Board Graham J.S. Wilson gap Silicon Graphics has enjoyed for years MicroJava chip is scheduled for the first Chairman/CEO Marshall W. Freeman has rapidly shrunk and, according to some, quarter of 1997, with a unit price of $25 to President/COO Thomas L. Kemp disappeared in the low-workstation price $50. Can an Internet terminal be built for Senior Vice President/CFO Warren “Andy” Ambrose points. Consumer 3D technology is poised $500? Let’s see—a Java game cartridge, Senior Vice Presidents David Nussbaum, Darrell to enter the market, and card manufactur- hooked up to a cable modem, on a Sony Denny, Donald A. Pazour, Wini D. Ragus ers will enjoy perfect timing as 3D graphics PlayStation or Ultra64. Do you think it Vice President/Production Andrew A. Mickus upgrades become the upgrade of the year. would sell? ■ Vice President/Circulation Jerry Okabe Vice President/ Third, network connections will add Software Development Division Regina Starr Ridley voice capabilities. I don’t think DVSD and Larry O’Brien Miller Freeman ASDL modems will enjoy the explosive Editorial Director A United News & Media publication

6 GAME DEVELOPER • APRIL/MAY 1996 http://www.mfi.com/gdmag CROSSFIRE

Applesauce

Alex Dunne f you had been at Macworld in San Book notebook computers. However, Francisco earlier this year, you prob- because Apple is cutting its hardware ably wouldn’t have seen any overt prices to compete with the free-falling Those who do not signs that Apple was auguring in. prices of Windows-based computers, More than 70,000 people attended first fiscal quarter earnings are actually the show, you had to strong-arm down compared to 1992. your way through the crowds, and March. Second quarter results are everyone seemed upbeat (even actor again flagging, again due to price cuts. learn from history are IGregory Hines of “White Nights” and In response, Apple contemplates cut- “History of the World, Part 1” fame, who ting its operating expenses through I saw on the show floor). But the bustling reorganization. crowds and high energy at Macworld hid May. CEO announces a frightening fact: Apple is in serious Apple is “shifting its focus away from doomed to repeat it. At financial trouble, and despite Hines pres- hardware and concentrating on the sys- ence, there’s no white knight coming to tem software that controls computers the company’s rescue. and communications, and even online The latest rumor before we went to information services.” David Coursey of Apple, Amelio‘s got his press was that Sun Microsystems was to PC Letter calls the company “immensely acquire Apple. Sun joins an illustrious list confused.” of would-be suitors over the past few June. Sculley steps down after a years. Unfortunately, even if this merger ten-year stint as CEO, and the board rumor had panned out, it probably would names president Michael Spindler to work cut out. Let‘s have been too little, too late. Apple’s mis- take his place. Spindler is charged with management has taken it to the brink. navigating the company out of its finan- Pursuits such as Newton, eWorld, Open- cial trouble and taking a greater hands- Doc, Kaleida Labs, and have on role in management. Sculley stays on drained the company’s coffers and divert- as chairman. jump in the time ed its attention away from its bread-and- July. Third quarter results send butter computer business, which has suf- shock waves through the industry. Apple fered as a result. reports a whopping $188 million loss, its Now it appears that the Wintel largest-ever quarterly loss, due mostly to machine and look juggernaut has more than enough a $321 million restructuring. On the momentum to carry it past any would- same day, Apple declares that 2,500 be competition. Looking back a few employees (over 15% of the company) years, it all seems so clear now how mis- will be laid off. Analyst Doug Kass, pres- guided Apple’s strategies were. Let’s set ident of the Viewpoint Group consulting back on Spindler‘s our way-back machine to the beginning firm, sums it up when he tells the San of 1993 and roll tape. Francisco Chronicle, “A well-run company shouldn’t have to reorganize every couple 1993: Spindler takes over. of years. To bring out a ground-breaking January. Apple is enjoying outstanding product like the PowerBook and then reign. sales of the immensely popular Power- stumble leaves us with little confidence

http://www.mfi.com/gdmag GAME DEVELOPER • APRIL/MAY 1996 9 CROSSFIRE

that they can navigate a new market with March. Apple launches its line of 1995: The Downward Spiral Newton. . . .” How prescient. PowerMacs, which are driven by Motoro- January. Information Week reports that August. At Macworld in Boston, la’s PowerPC chip. The launch at Lincoln Oracle, Philips Consumer Electronics, Apple unveils the Newton, its $700 Center in New York is the most antici- and Matsushita are about to undertake a dyslexic “personal digital assistant.” pated event since Apple launched the hostile takeover of Apple. Oracle is Apple insists it is not betting the compa- a decade earlier. Oracle CEO apparently interested in the MacOS and ny on Newton. Good thing. considers buying Apple Taligent software, while Philips and September. Apple announces it will with help from convicted junk-bond king Matsushita will split the hardware busi- license necessary technology to other Michael Milken. Go figure. ness. All parties deny the rumor, and companies interested in manufacturing April. Gaston Bastiaens, head of Apple reiterates it is not for sale. Macintosh clones, reversing a decade of Apple’s Personal Interactive Electronics Apple posts record revenues of closed-architecture strategy. Donald (PIE) division responsible for the New- $2.83 billion for the first fiscal quarter, Strickland, Apple’s vice president for ton, is fired because of the product’s dis- due largely to outstanding Power Macin- licensing, hints to the Chronicle that a mal sales. The Apple PIE division tosh sales and cuts in operating costs. big player in the hardware industry will employees reportedly break into cheers February. The Supreme Court be among the clone makers. upon hearing the news. Spindler blames denies Apple’s appeal in a seven-year old October. Robert Puette, president of poor Newton sales on retailers who lawsuit against Microsoft. The suit Apple USA, leaves a day before fourth weren’t doing enough to explain the accused the Redmond company of copy- quarter results are announced that show Newton to customers. ing the Macintosh graphical user inter- profits down 97%. Apple’s inventory of May. Rumors fly that Apple is try- face, dating back to Microsoft Windows unsold products stands at an unhealthy ing to persuade IBM to produce Macin- 2.03. Apple dashes off a letter to U.S. $1.5 billion. Ian Diery, executive vice tosh clones. Ten years earlier, IBM was District Judge Stanley Sporkin, warning president of Apple’s Personal Computer portrayed as Big Brother in Apple’s Sporkin that Microsoft has bullied Division, takes over for Puette. At Sey- famous television commercial launching Apple and can’t be trusted to abide by bold, Diery explains that Apple is central- the original Macintosh. How times the proposed antitrust settlement. Gates izing its forecasting procedures and moni- change! chastises Spindler for Apple’s legal tac- toring aspects of sales to prevent product July. System 7.5 is launched. Ana- tics, and denies Apple’s allegation that shortages and overproduction. Sculley lyst Bruce Lupatkin of Hambrecht & Microsoft threatened to stop producing leaves his position as chairman and is Quist says the is “a software for the Macintosh. replaced by Apple cofounder Mike nice, evolutionary extension, but there is March. Spindler acknowledges Markkula Jr. nothing dramatic about it.” Apple is having problems filling orders November. Dell Computer, AST September. Apple starts an aggres- for Power because of poor Research, and Compaq allegedly are sive campaign to license its operating planning and component shortages. approached about licensing the Mac OS system, targeting major U.S. companies. Salomon Bros. cuts its earnings esti- but all refuse Apple’s offer. October. AT&T holds talks with mates as a result, lowers its rating on Apple about a possible takeover, accord- Apple to underperform, and the compa- 1994: Trimming Down, ing to the Chronicle. is also ny’s stock drops 8% in one day. But Losing Focus. mentioned as a possible contender for April. Spindler announces another January. Apple’s online service, eWorld, Apple. None of the companies com- major shakeup at Apple. Four divisions debuts at Macworld in San Francisco. ment. Spindler reportedly talks with are merged into two, and veterans David Gary Arlen, a media researcher, quips, IBM about securing an equity invest- Nagel and Dan Eilers are given leader- “Unless Apple has something new to ment in Apple and possibly leasing the ship over the divisions. Ian Diery, offer, it’ll be tough to hold its own MacOS. Apple’s executive vice president and against the existing players.” eWorld is November. Apple, IBM, and head of the PC Hardware division, priced much higher than competing Motorola team up to design a common resigns. online services, such as America Online machine. Two weeks later at Comdex, Meanwhile, rumors swirl that and CompuServe. Earnings for the first IBM backs away from the alliance, citing Canon Inc. is in talks with Apple about quarter are down 75% by the ongoing concerns from its corporate customers acquiring the company. price war in the hardware industry, who think IBM might be wavering in its May. Apple Chief Financial Officer despite record shipments of Macs. support for OS/2 by working closely Joseph Graziano states that Apple is not February. Apple unveils its own ver- with Apple. for sale and that the impact of licensing sion of a TV set-top box for delivering December. Power Computing, a the MacOS will be “modest” during movies and services like electronic shop- company with only 20 employees, and 1995. Radius announces it has to wait ping. The box, which will sell at about Radius announce that they will be the until fall to ship its Macintosh clones in $300, gets shrugs from analysts. first companies to sell Macintosh clones. large quantities due to a shortage of parts.

10 GAME DEVELOPER • APRIL/MAY 1996 http://www.mfi.com/gdmag CROSSFIRE

June. eWorld celebrates its first birthday. With a subscriber base of only 80,000, prices slightly higher than com- peting services, and no internet connec- tions other than e-mail, the service is described by one analyst as, “America Online with nicer artwork, no content, and no users.” July. Frank Seiji Sanda, the presi- dent of Apple’s successful Japanese oper- ation, quits unexpectedly. Apple’s third quarter results fall short of expectations, as earnings are down due to supply prob- Mike Markkula, Chair Micheal Spindler, CEO lems. Markkula sells 400,000 shares of Photo courtesy of Apple Computer Inc. Photo Courtesy of Apple Computer Inc. his Apple stock. Apple declines to explain why. August. Apple tries to dismiss the and allowing eWorld subscribers access December. Apple announces it will hype surrounding the launch of Win- to the web from within the service. probably lose money in the first quarter, dows 95 with their “been there, done eWorld, still lagging far behind other citing its inability to meet production that” slogan. Senior Apple executives services with only 115,000 members, is demands and its shrinking profit margin. sell hundreds of thousands of more in trouble. Apple’s stock drops 15% in the two days shares of Apple stock. In two months, An increasingly skeptical press and following this announcement, and as a Markkula has pared his stake in Apple analyst community speculates whether result Standard & Poor’s Corp. puts the by $44.1 million. Spindler is going to get the boot from company’s debt on credit watch for pos- Apple executives have quietly Apple. Markkula remains strongly sible downgrading. drawn up “golden parachute” agreements behind Spindler, however, and there’s Apple and IBM end their partner- for themselves, entitling management to little chance that the board will act to ship in Taligent, an effort to advance large payments in the event they lose fire Spindler without the Chairman’s object-oriented software technology. their jobs or are demoted following a say-so. Taligent becomes a subsidiary of IBM. takeover. Spindler’s payout alone could October. Joseph Graziano, Apple’s be worth as much as three times his CFO for six years and a member of the 1996: Chapter 11? salary and bonus, or around $3 million. board, leads efforts within the board to Acquistion? Your Call September. In one day, the compa- remove Spindler, reports the Chronicle. January. A busy month indeed. At Mac- ny delivers a double-whammy of bad According to unnamed sources, world, Apple makes no major news news. First, it advises investors that its Graziano says, “Either Spindler goes announcements and holds no news con- earnings for the fourth quarter will be and the company is sold, or [I] will ferences for the press. Spindler doesn’t “well below” Wall Street estimates. Sec- quit.” Apple’s board meeting held there- even make an appearance at the show. ond, it announces that it has stopped after produces no changes, and Another exodus of Apple executives shipping its new PowerBook 5300 Graziano announces his resignation, cit- takes place, as a stream of vice presidents models, due to problems with their ing “differences of opinion” with depart: Barbara Krause (VP of Corporate lithium ion batteries that have a ten- Spindler as the reason. Communications), Jim Groff (VP of dency to overheat and ignite. Commenting on Graziano’s depar- Education Marketing), Peter Friedman Following this announcement, ture, Kimball Brown of Dataquest tells (VP and General Manager of Internet business columnist Herb Greenberg the San Jose Mercury News, “The most Sources), Keith Fox (VP of the Home slams Spindler. “Yesterday, Apple dangerous job in high tech today is the Division), and Don Strickland (VP of appeared to be spinning out of control, No. 2 spot at Apple, because Spindler is Business and Government Sales). The but Spindler was nowhere to be found. not comfortable sharing power.” number of high-ranking executives that On a day when he should personally Approximately a week later, Apple have left in the past year stands at 14. have been reassuring investors, the press, undergoes another reorganization. In the Apple reveals that it lost $60 mil- and customers that all is well, he was out shakeup, the media group, which used to lion during the traditionally strong of his office, and he wasn’t expected to report to senior vice president Dan Eil- Christmas quarter and that its profit return until Monday. Terrible timing.” ers, now reports directly to Spindler. margins have hit a record low of 15% — Apple lays out plans to revamp November. Dan Eilers resigns. despite further price cuts. Apple’s mis- eWorld, by offering sections of the ser- Apple and IBM’s joint venture, Kaleida, judgment of demand for the more pow- vice to users of the World Wide Web, shuts down. erful Power Macintoshes resulted in a

12 GAME DEVELOPER • APRIL/MAY 1996 http://www.mfi.com/gdmag CROSSFIRE

backlog and lost sales during the holiday “could be lessened or redefined.” Some Where to From Here? season. Apple announces it will undergo speculate this may be a way to ease the That’s the saga as we go to press. What- a huge restructuring, cutting 1,300 jobs CEO out of the company gracefully. ever its future, major changes will contin- at the company, and jettison unprofitable Others demand Markkula’s resignation, ue to rock the company. Some have sug- businesses. blaming him for the company’s travails. gested that by spinning off its hardware Radius sells its clone-making busi- At the annual shareholder’s meet- business and focusing solely on its more ness to Umax Data Systems. Linley ing, insults fly at Apple management. As profitable software business, Apple would Gwennap, editor of Microprocessor Report Spindler and Markkula sit in front of insulate itself from the cutthroat hardware opines to the Chronicle, “It sounds to me 500 investors and employees, there are price wars which have caused the compa- as if Umax and Radius decided it wasn’t calls for resignations, accusations of ny’s profit margins to dive. It’s not a bad worth having both of them [making incompetence, and demands for im- idea, but I doubt Apple will consider it, clones] and that they’d rather combine provement. Employees complain about given their strong feelings about keeping their efforts...[the demand for clones] is the loss of competent managers. One the company intact. not taking off as quickly as people employee almost breaks down crying, This past January, one Macworld thought it would.” explaining that though he loves Apple, attendee was resigned to all of the The Wall Street Journal reports that he’s considering job offers from other depressing reports about Apple: “Most Sun Microsystems is in negotiations to companies. Macintosh people are used to hearing acquire Apple, and Sun’s stock falls 9%. February. Apple’s board announces bad news all the time.” Unfortunately, Apple denies the rumor, states that it is that Gilbert Amelio, former president the worst may be yet to come. ■ not for sale, and says that Spindler has and CEO of National Semiconductor, the full support of the board. will replace Spindler and take over the While Alex Dunne is allegedly a Mac Markkula announces that Spindler Chairman position from Markkula. The fan, coworkers have never seen him use is suffering from health problems and appointment signals to the world that an one. Contact him via e-mail at says Spindler’s role at the company acquisition by Sun Microsystems is off. [email protected].

14 GAME DEVELOPER • APRIL/MAY 1996 http://www.mfi.com/gdmag SEZ U!

Games Aren’t Just for Kids Anymore!

SAY IT! The shady staff of Game Developer would love to hear your comments, questions, and suggestions! Please send them to: Game Developer magazine, Sez U!, 600 Harrison St., San Francisco, Calif., 94107. For those of you who do have access to the Inter- net, send e-mail to [email protected] or go to the Game Developer web site at http://www.mfi.com/gdmag. Thanks!

SATISFACTION GUARANTEED! position in any game company. Help me, Dear Editor: you’re my only hope. reat issue! Particularly, “The Play’s The Sean S. Whalen Thing” by Barbara Hanscome (Dec./Jan. Via e-mail G1996). I especially enjoyed reading quotes from people like Corey Cole and Jonathan Editorial Assistant Jana Outlaw responds: Knight. Please do that again and more often. I Stay tuned: upcoming issues cover game pro- much prefer to hear developer people talk gramming using the Microsoft Game SDK. than reviewers pontificate. Insights are Maybe the Multimedia Careers section of the invaluable. magazine will point you in the right direction, Courtland Shakespeare in the meantime. Via e-mail CHRIS HAS FANS! Dear Editor: EAT, SLEEP, AND DRINK GAME DEVELOPER hanks for the excellent series on “3D Texture Dear Editor: Mapping.” In the discussion of the lines-of- y copy of Game Developer and a Snapple Tconstant-z approximation to perspective tex- 6-pack were placed on my desk by a car- ture mapping, Chris Hecker writes, “walls and Ming individual. Before looking at the floors are special cases where lines-of-con- cover, I tried to picture what it would look stant-z are vertical and horizontal,” but explains like. “Windows 95 and Game SDK” page 62, why it is not satisfactory in the general case. “The Game Companies in and Around the Maybe the best answer is to use the lines-of- New York Area” page 94, and “The Best constant-z method for the special cases of walls C/C++ Compilers for Windows 95” page 105. and floors, and to use the subdividing affine I understand that the last two are recent method for polygons that require the general requests, and you could not have possibly solution. A closer examination of the lines-of- known of their existence. But the first arti- constant-z method for this very common special cle—there are 100 million Windows users in case would be valuable, although maybe it is the world, and half of them have Windows 95. too simple to fill a whole column. DOS is dead, and Windows 95 is the future. I Steve Schonberger just realized my opportunity, and I was hop- Via e-mail ing that you would help us lone programmers get a jump start with Game SDK. The last two Chris Hecker responds: requests are desperately needed by a young C Some people have vertical and horizontal ras- and assembly student hoping to get a junior terizers and they use the vertical ones for

16 GAME DEVELOPER • APRIL/MAY 1996 http://www.mfi.com/gdmag polygons that are more wall-like and the hori- games. The chapters devoted to these games Our Readers zontal ones for polygons that are more floor- go through every inch of code with a magnifying like. This lets you subdivide less if you’re doing glass. in these game examples adaptive subdivision (since your “canlines” are were evaluated by professionals at Microsoft closer to the lines-of-constant Z, so there’s and other software engineers in the game This month, our read- less warp along them), but it means you have industry for accuracy. to integrate both rasterizers in your code. The subject matter in Spells of Fury will sat- isfy a broad range of programmers, from the novice to the professional developer—no stone ANOTHER SATISFIED CUSTOMER is left unturned. Dear Editor: ers search for books, he magazine is great! I don’t read anything ERRATA but Game Developer. It’s my one-stop infor- Tmation magazine!!! uality is job one here at Game Anonymous Developer magazine. We strive to correct any mistakes we’ve made examine lines-of- Qand give any additional informa- INQUIRING MINDS WANT TO KNOW tion that may be helpful in providing Dear Editor: you with the best product we can. was reading Michael J. Norton’s article, “The Mode X-Files” in the Oct./Nov. 1995 • In “Bit Blasts” (Feb./Mar. 1996), constant-z, and Iissue of Game Developer magazine and was we told you that you could order a wondering how I would get in contact with trial demo CD of Caligari's True- him. He stated in the article that he was Space2 for $14.95. One reader, working on a book for programming the Win- David Scarbrough, informed us dows 95 SDK. I’d like to find out when he that at ftp.caligari.com, you can thinks the book will be done and who will be download it for free. The directory explain their feelings publishing it. I’ve been looking for a book like is /pub/trueSpace, and the two this for a while now. files are ts2trial.txt and ts2trial.zip. Robert Hildebrand Anonymous login is allowed; you Via e-mail can use your e-mail address for your password. about Game Developer Michael Norton responds: • In Chris Hecker’s “Let’s Get to the I'm glad to hear there is interest in a Microsoft [Floating] Point” (Feb./Mar. Windows 95 Game SDK book. This summer, 1996),there were two exponent Spells of Fury by Waite Group Press, will be typos. On page 20, it says, “so we reaching the shelves of your local computer can represent numbers as large as book store. This is a culmination of a year of 21000 and as small as 21000.” The magazine and its work on a very exciting project. As a profes- second exponent should be 2-1000. sional in the industry, I pulled together my On page 22, it also says, “What resources to form a development team includ- happens if we add in 223....” The ing programmers, artists, and musicians to number should read 223. put together ten fully functioning DirectX staff.

18 GAME DEVELOPER • APRIL/MAY 1996 http://www.mfi.com/gdmag BIT BLASTS

What’s the Buzz?

Diane Anderson t press time, we are looking forward that delivers 3D animation, 2D graphics, to the Computer Game Developer’s and digital video playback acceleration for Conference. Here are some products PCs running Windows 95. It uses S3’s Ato check out while you are there. triangle-based polygon rendering engine What‘s new in the and features perspective-corrected texture mapping, bi-linear filtering, MIP-map- Capture Polhemus ping, alpha blending, depth-cueing, and Polhemus is building on its motion cap- fogging. It comes standard with 2MB of world of developing ture system; Ultratrak Pro is its new ver- DRAM that is split between display sion. It incorporates DSP technology and memory and Z-buffer memory, but can is targeted toward game developers, be upgraded to 4MB of DRAM for bet- movie studios, and production houses ter Z buffering, texture mapping, and bet- games? Check out involved in animation and special effects. ter acceleration of 3D applications at It uses real-time, six-degree-of-freedom higher resolutions. The Diamond Stealth data from numerous sensors. Data can be 3D 2000 features full-motion digital processed in real-time for live broadcast video playback at 30 frames-per-second products that capture or virtual set applications. Using the Long by off-loading functions from the host Ranger transmitter, Ultratrak Pro pro- CPU. The Diamond Stealth 3D 2000 vides a working area of more than 700 with 2MB EDO DRAM for the PCI- square feet. Drivers are available for most bus costs $300. Upgrades, such as the motion, that model major software packages including MPEG Video Player 1100 daughtercard Alias/Wavefront, Softimage, Side Effects, or the Diamond DTV 1100 TV tuner, 4DVision, and Hash Animation. Ultra- are available from Diamond as well. trak Pro is an integrated system free of ■ For more information contact: animation, and that DIP switches, in a 19-inch rack mount- Diamond Multimedia able chassis. Data is transmitted to a 2880 Junction Ave. workstation over an Ethernet or SCSI San Jose, Calif. 95134-1922 interface or may be saved to the hard Tel: (408) 325-7000 accelerate it. And a drive. Pricing depends on receiver and Hz Fax: (408) 325-7070 configuration and ranges from $23,500 to Web: http://www.diamondmm.com $71,500. ■ For more information contact: word from the Gossip Polhemus Inc. Softimage 3.0 1 Hercules Dr. Microsoft is now shipping a Windows Colchester, Vt. 05446 NT version of its 3D modeling and ani- Tel: (802) 655-3159 mation software, which offers the same Lady mourning the Fax: (802) 655-1439 animation environment as Softimage 3D for Silicon Graphics. Softimage 3D for Windows NT requires Windows NT Stealth 3D 2000 3.51 (with Service Pak 2 installed), a min- loss of Eden at Apple. Diamond announces Diamond Stealth imum of 64MB of RAM, 1GB of hard- 3D 2000, a new multimedia accelerator disk space, and a supported OpenGL

20 GAME DEVELOPER • APRIL/MAY 1996 http://www.mfi.com/gdmag BIT BLASTS

■ ... Schmooze news graphics accelerator card. Softimage for For more information contact: Multimedia ... Schmooze news Windows NT is optimized for several Microsoft Shakeout Intensifies... turnkey hardware configurations. Softim- 1 Microsoft Wy. Digital Pictures axed 30 people a couple of weeks ago. Sanctuary age 3D for Windows NT costs $7,995 Redmond, Wash. 98052 Woods drop-kicked their CEO (Scott through the Softimage network of VARs. Tel: (800) 576-3846 Walchek) and laid off 20 of their 100 Owners of version 2.66 or earlier can Fax: (206) 936-7329 people. Guess Director games didn’t sell upgrade for approximately $1,995 (hard- Web: http://www.softimage.com too well over Xmas! After lulling Comp- ware not included). Softimage also ton’s game people with promises that it would continue producing “quality” announced support for Silicon Graphics games, SoftKey fired virtually the entire Indigo2 Impact workstations, adding to Diane Anderson is managing editor of game development crew. Reports are the list of certified configurations. Game Developer magazine. that the few who received offers to stay opted to go looking for greener pastures anyway. Death Threats from Disk Pirates in South China The organization that represents the global industry has closed its Canton, China operation after staff learned that local CD pirates had hired hit-men in an imaginative anti-anti-pira- cy move. Hopefully U.S. and Canadian pirate shareware publishers won’t get ideas! The Miles Drivers Boogie RAD Software acquired John Miles’s AIL sound library, renamed it to “Miles Sound System” and intends to extend it to the Mac and PowerMac. Speaking of Macs... Apple Computer Inc. seems to be withering on the vine. With a huge loss for the last quarter and CEO Spindler’s departure, things are looking pretty bleak for the hardware and software manufac- turer. One comment heard on the news: “Is the Macintosh going to become the next eight-track tape player?”One thing is certain: now is a REALLY lousy time to be an Apple employee. Layoffs are looking likely. Industry analysts are pre- dicting up to one quarter of the Apple employees will receive pink slips in a major reorganization. The moral of the story here is: “Evolve or die.”

The sad part is that if Apple had had smarter management, they’d be in Microsoft’s position right now. Instead, they’re in the situation that if they had sold off their manufacturing division and invested the proceeds in Microsoft stock, they would have had a much better year. The Gossip Lady predicts that Apple will be sold in the next year, and that they’ll become a superb software division for a major hardware company.

Wanna talk? E-mail The Gossip Lady at [email protected].

22 GAME DEVELOPER • APRIL/MAY 1996 http://www.mfi.com/gdmag BEHIND THE SCREEN

Perspective Texture Mapping, Part V: It’s About Time

Chris Hecker heck the date on the Game the market leader (and the CPU I know Developer in your hands. Does best). You’ll still get a lot from reading April/May 1996 mean any- this regardless of your chosen platform, Finally! The moment thing special? How about the but the code is specific to Intel. However, same issue last year: April/May I got a new Macintosh clone from Power- 1995? What, you have no idea Computing with a PowerPC 604 chip in what I’m talking about? That’s it, so don’t be surprised to see a PowerPC understandable, since it was so version of this texture mapper at some game developers have Clong ago. I’ll refresh your memory with a later date (as soon as I get used to the small quote from my column in that concept of 32 general purpose registers)! 1995 issue: “My next two articles should To quickly bring us up to date, we fix this lack of documentation, first by decided to use a subdivided affine giving an easy-to-understand mathemati- approximation to the true perspective been waiting for. At cal foundation…and sample code to curve (Behind the Screen, Dec./Jan. implement the naive algorithm. In the 1995). This approximation uses short lin- next article, we’ll speed it up to interac- ear spans with perspectively correct end- tive performance.” points to approximate the rational per- long last, Chris Hecker Yes, you guessed it, the April/May spective curve. I modified the DrawScan- 1995 issue contained the first installment Line function to do the affine subdivision of my “two-part” perspective texture in C++ and the texture mapper got three mapping series. Now, a year later, we’re times faster than the version with the finally going to finish the two part series divides. I uploaded a sample application unveils the denoue- with this issue, part five. True to my soft- that contains the texture mappers we ware engineering background, I can’t developed so far. Of course, I was late in estimate how long it will take me to do uploading it (see above comment about something to save my life. However, I saving my life), and I apologize to anyone feel the somewhat lengthy trip has been who looked and couldn’t find it. The ment of his texture worth it. sample is up now though—see the end of this column for information on where to A Long, Strange Trip find it. Unlike the first installment, this article I can provide an overall outline for mapping series. What will not be a journey through the elegant the optimizations we’ll cover before theory and math behind perspective tex- going into detail. Our main optimiza- ture mapping. Instead, this article will tions will take advantage of the dual inte- romp through the myriad optimization ger pipelines on the Pentium to imple- tricks and techniques we can use to ment a very fast fixed-point linear texture a long, strange trip it squeeze every last bit of texture mapping mapper for our affine spans, and we’ll use performance from the Intel Pentium the floating-point unit’s ability to overlap processor. While the rest of the series was execution (especially those costly perspec- platform independent, we have to turn to tive divides) with integer instructions to assembly language to get the most out of calculate the interpolation values for the has been. modern processors, and the Pentium is next span as we render the current span.

http://www.gdmag.com GAME DEVELOPER • APRIL/MAY 1996 25 BEHIND THE SCREEN

Listing 1. The C++ Inner Loop tional part of V carries into the integer part, the source pointer no longer steps by for(int Counter = 0;Counter < AffineLength;Counter++) 1, it steps by the width of the texture { int UInt = U>>16; bitmap. Not even assembly language has int VInt = V>>16; an instruction to add in an arbitrary num- ber—like the TextureDeltaScan in Listing *(pDestBits++) = *(pTextureBits + UInt + 1—on carry. (VInt * TextureDeltaScan)); Quickly adding in the vertical source step on V’s carry is where 99% of the pro- U += DeltaU; gramming brainpower is spent on linear V += DeltaV; texture mapping optimizations. I’ve seen } about five or six ways of doing it myself, but by far the coolest, fastest, and most In addition, we’ll pull a bunch of cheap need to know when this happens and add elegant way I’ve seen was invented by tricks along the way to give it that extra an extra step to our source pointer. Michael Abrash. However, before I kick. This carry problem uncovers a major describe it, I’m going to address the opti- hole in C and C++ from the standpoint of mization a lot of the experienced texture Carry Me Away integer optimizations: there’s no carry bit. mappers in the audience think I’m going Listing 1 shows the C++ linear inner In other words, in assembly language, it’s to use here. loop for our DrawScanLine function. While trivial to know when two added numbers If you go out on the Internet and this is better than our previous loops with overflow because the carry bit will be set, look for affine texture mappers, you’ll their divides, it’s still not great because but in C++ there’s no way to know with- undoubtedly run into a lot of very opti- it’s doing a multiply and a bunch of shifts out doing a bunch of cumbersome tests. mized x86 code that only works with and adds for each pixel. If we look at why So, in pseudocode, we want to do this: power-of-two source texture sizes, and it’s doing a multiply, we see it’s calculat- specifically two to the eighth power (or ing the source texture offset for each new UFrac += DeltaUFrac 256-bytes wide for 8bpp textures), coordinate, even though we’re just doing pTexture += DeltaUInt + Carry because if you keep your textures to a a normal linear interpolation through the power-of-two width, you can very easily texture for each span. By definition, a Where the variable Carry is set to 0 if handle the V carry we’re discussing using linear interpolation increments by the the fractional addition didn’t carry into some special x86 instructions that operate same amount each step, so we can take the imaginary integer part (that we’re not on 8-bit portions of the full registers. advantage of this coherency to speed up storing anymore) and is set to 1 if the Let’s run through an example, where our loop. addition did carry. This pseudocode is our source texture is 256 by 256. We’ll Let’s ignore the V coordinate for the trivial in all the assembly languages I’ve use the x86’s ebx register, and its corre- moment and see how we can take advan- ever seen, for example, in x86 assembly: sponding “byte registers,” bh and bl. The tage of the U coordinate’s coherency. As byte registers are part of the 32 bit ebx you can see from the loop, the U fixed- add ebx,ecx register, and bl (b-low) is the lowest 8 point variable is shifted down to extract adc esi,edx bits—bit 0 through 7—and bh (b-high) is its integer portion for each pixel, which is the next higher 8 bits—bit 8 through 15. then added into the texture pointer. Assuming the given registers contain the If we keep the U coordinate in bl and the However, since we’re linear, the integer right values, the adc (add with carry) will V coordinate in bh, we can use the follow- portion of DeltaU is going to stay constant add in the step and any carry from the ing code to increment both U and V for the span—always incrementing the previous addition. Implementing this (assuming ecx and edx have the current integer part of U by the same amount— code in C++ would be a mess. UFrac and VFrac, respectively, and esi con- so there’s really no need to keep the inte- That’s it for the U coordinate, but tains the texture pointer): ger portion of U around at all. If we think we conveniently ignored the V coordinate only of the U increments, we can keep the because it’s a good deal trickier. Like U, add ecx,[DeltaUFrac] source pointer at the current texture pixel, the V coordinate is linear for our span, so adc bl,[UIntStep] and we can find the next texture pixel by we can precalculate our increment and add edx,[DeltaVFrac] just adding in the integer part of DeltaU— leave the integer part of V out of our loop. adc bh,[VIntStep] calculated outside the loop—to the point- However, as you can see from Listing 1, add esi,ebx er at each step. The only problem with the integer part of the V coordinate is this plan is the fractional part of U plus scaled to step vertically in our texture Notice the second adc. It adds in the the fractional part of DeltaU will some- bitmap. This doesn’t present a problem carry from the VFrac addition, but I just times carry into the integer part of U. We for the normal V step, but when the frac- got finished saying how this wouldn’t

26 GAME DEVELOPER • APRIL/MAY 1996 http://www.mfi.com/gdmag BEHIND THE SCREEN

Listing 2. The x86 Asm Inner Loop As if the basic operation wasn’t good enough, the pipelining on this code is add edx,[DeltaVFrac] ; add in dVFrac amazing as well. The order of instructions sbb ebp,ebp ; store carry perfectly fills both pipes on the Pentium mov [edi],al ; write pixel n and manages to run the two additions from memory—both two-cycle instruc- mov al,[esi] ; fetch pixel n+1 tions—in the Pentium U and V pipes at add ecx,ebx ; add in dUFrac the same time (remember, the next pixel’s code will come right after this pixel, so adc esi,[4*ebp + UVStepVCarry] ; add in steps the add edx and the adc esi will run at the same time). The instructions are also far work because V’s carry needs to add in the first half of the solution is these two enough away from each other that there width of the texture. The trick is that bh is instructions: are no Address Generation Interlocks. actually already multiplied by the width of Overall, it’s a beautiful piece of code. our texture—256—by virtue of its bit add edx,[DeltaVFrac] position in ebx. Neat, huh? Now, given sbb ebp,ebp Walking and Chewing Gum such a cool trick, why wouldn’t we use it? Regardless of how amazing our integer There are two reasons: first, restricting The first instruction adds in the affine inner loop is, we’ll still be slower yourself to power-of-two textures isn’t fractional step as usual, but the second than we need to be if we’re waiting for the very flexible and is bad for cache coheren- instruction saves the carry flag, using a floating-point unit to calculate the per- cy (see Behind the Screen, Oct./Nov. neat trick involving the sbb (subtract spective-corrected texture coordinates 1995). More importantly, with the Pen- with borrow) instruction. The sbb before starting each span. This is where tium Pro, this code will run slowly due to instruction is like the opposite of adc, it the floating-point overlap I hinted about a new pipeline stall called the Partial Reg- subtracts its source from its destination, in the last issue enters in. Most modern ister Stall (PRS). The PRS happens when but also subtracts the carry bit, so sbb processors can execute floating-point you modify one of the byte registers and ebp,ebp will subtract the ebp register from instructions at the same time as integer then try to use the encompassing 32-bit itself, giving 0 if there was no carry, or -1 instructions, and some, like the Pentium, register, much like the above code. The if there was a carry. Thus, the carry bit can execute multiple floating-point instruction add esi,ebx will stall for a very from the VFrac addition is stored as a 0 instructions at the same time. As an long time on the Pentium Pro. Why did or a -1 in ebp. example of integer and floating-point Intel let this happen? I have no clue, The second half of the solution overlap, the following code will take 36 although they say it will let them increase comes with these instructions: cycles on a Pentium in double precision the clock speed more than if they had pre- mode: vented the stall. Regardless, it’s there, and add ecx,ebx we’ll need to live with it. adc esi,[4*ebp + UVStepVCarry] fdiv [Number1] So, given that we’re not going to use fst [Number2] the power-of-two texture trick, how do The first instruction is the UFrac we write our code so it can carry an arbi- addition, so after it completes, the carry The division takes 33 cycles, the trary value into the pointer when VFrac bit is set appropriately. The next instruc- store takes two cycles, and there’s a one- overflows? Enter Abrash’s code snippet tion is where all the action occurs. It’s an cycle stall for trying to store the result of shown in Listing 2. This is the code for a adc, so it adds in the carry from the UFrac the division right after it’s completed. pixel from the middle of an unrolled loop, addition as you’d expect. However, it’s Guess how long the following code takes: so there’s a bit of setup not shown here, an adc from memory, and it uses a two but imagine this same snippet concate- dword array to accomplish its magic. fdiv [Number1] nated with itself a bunch of times. See if UVStepVCarry is the address of the second rept 33 you can figure out how it works and then dword in the array, and the 0 or -1 in ebp add ebx,ecx read on for the description of this tour de from the VFrac carry will select either the add edx,eax force of optimization. second dword if there was no V carry, or endm the first dword if there was a V carry fst [Number2] Hit the Pipe (since 4 • -1 will subtact 4 bytes from the There are so many cool things about this array address). The only thing left is to To guess correctly, you need to code it’s hard to know where to start make sure the array has the appropriate know that the rept macro repeats the describing it, but, since we were dis- steps in it, including the U and V integer contained code 33 times, so there are cussing the V carry, we’ll start with how steps and the V carry step for the first actually 66 instructions between the fdiv the code addresses that problem. The element in the array. and the fst. This is actually a trick ques-

28 GAME DEVELOPER • APRIL/MAY 1996 http://www.mfi.com/gdmag BEHIND THE SCREEN

tion because this code takes the same 36 perspective divide for our next span and ter access easy, but Intel doesn’t usually cycles as the first snippet, but we got to have it calculate as we’re processing the ask my opinion on these things, so I’ll execute 66 integer instructions for free! current span, making it almost free. quickly describe the stack-based solution. Well, we don’t really get just any 66 Listing 3 shows the obvious way to instructions for free, but we do get 33 U Short Stack add some numbers together, along with and V pipe slots in which we can try to The second floating-point technique I the cycle counts for each instruction. It’s get some work done before using the mentioned, executing multiple floating- implementing this C++ code: result of the division. Some instructions, point operations simultaneously, is slight- like integer multiplies, won’t overlap with ly more convoluted. The Intel floating- a1 += b1; c1 += d1; e1 += f1; the floating-point unit, and you can’t point architecture is stack based, which really do many other floating-point means almost all the floating-point The code executes in 21 cycles, instructions at the same time as floating- instructions will only operate on the top including the three stalls (the 2+1 fstp point division, but we can start up the of the stack. This made it hard for Intel to pipeline the floating-point unit for the Listing 4. Quick Adding Listing 3. Naive Adding Pentium since all the instructions were vying for the same register—the floating- fld [a1] ; 1 fld [a1] ; 1 point top-of-stack register. So, instead of fadd [b1] ; 1 fadd [b1] ; 3 breaking all the existing floating-point fld [c1] ; 1 fstp [a1] ; 2+1 code by making a bunch of new instruc- fadd [d1] ; 1 fld [c1] ; 1 tions to randomly access the floating- fld [e1] ; 1 fadd [d1] ; 3 fadd [f1] ; 1 point registers, Intel decided to make it fstp [c1] ; 2+1 fxch st(2) ; 0 fld [e1] ; 1 possible to move operands around on the fstp [a1] ; 2 fadd [f1] ; 3 stack very quickly. I actually wish they’d fstp [c1] ; 2 fstp [e1] ; 2+1 broken the code and made random regis- fstp [e1] ; 2

30 GAME DEVELOPER • APRIL/MAY 1996 http://www.mfi.com/gdmag BEHIND THE SCREEN

timings) for storing the results of an write this (again, see the comment about ond at 320 by 200 if you’re not doing operation immediately following its estimating how long it takes me to do anything else except texture mapping. completion. Listing 4 shows an alternate something at the beginning of this arti- That’s definitely fast enough for a high- implementation of the same code, which cle), but it’s already two times as fast as end 3D game, and I think we can safely executes in 12 cycles, or almost twice as the C++ subdividing affine texture map- say we’ve met the goals we set for our- fast. The instructions can pipeline if you per, and I hope to make it another two selves at the beginning of this series, don’t access their results before the times faster by the time you read this even if we did meet them a bit late. ■ instruction is finished (the fld instruc- and are able to pick up the code. It’s cur- tion pushes its operand onto the stack, rently drawing 4.5 million pixels per sec- You can e-mail Chris Hecker at check- and the previous fadd continues on its ond on a Pentium 133, which is 5 times [email protected]. Don’t be surprised if it takes operand even as it’s moved down one faster than our original texture mapper, him a while to respond, although he’ll assure stack position). In our example, the fadds and fast enough to do 70 frames per sec- you it will only take a second.... take 3 cycles each in Listing 3, but only a single cycle each in Listing 4. The second thing to notice is that the fxch instruction is free in Listing 4. This is Intel’s offering to the angry God of Processor Architecture, who threat- ened to smite Intel dead if it didn’t pipeline the floating-point unit. The almost-free fxch instruction makes it possible—not easy, just possible—to pipeline your floating-point code even though most of the instructions only operate on the top-of-stack register. Using fxch, you can move things around while they’re still calculating, like the e1+f1 addition in Listing 4. I called it “almost-free” because there are some restrictions you have to obey to keep it free; for example, the following instruc- tion must be a floating-point operation, as it will stall a cycle if the following instruction is an integer operation. Intel’s AP500 Application Note, available on their www.intel.com site and the Intel Architecture Labs CD, describes this technique in detail.

Finally There are more tricks in the assembly texture mapper that deserve a mention, but they’re all minor and I’m out of space. You can find them in the code itself. As with most assembly code, the texture mapper is way too long to include here in the magazine. You can, however, get it in the texture mapping archive on the Game Developer web site, on its ftp site (ftp.mfi.com/pub/ gamedev/src), or on my homepage at http://ourworld.compuserve.com/ homepages/checker. How fast is it? Well, I must admit, I’m not finished optimizing it yet as I

http://www.mfi.com/gdmag GAME DEVELOPER • APRIL/MAY 1996 33 3D MODELING

Data Capture of 3D Models

about the well-known characters changed as they made the transition to new hard- ware. Maintaining consistency across platforms was a challenge, however, because graphic imaging requirements for each game device differ. For example, the resolution available in a CD-ROM ver- sion, with its prerendered images, is far superior to that of the arcade game which renders scenes in real-time. Consequent- ly, CD-ROM creatures can display more detail and move more realistically. To ensure that Sauron, Talon, and company made an accurate transition to the new PC CD-ROM version of the game, Time Warner hired 3Name3D, a Santa Monica, Calif.-based geometric modeling company. 3Name3D sculpted each of the Primal Rage creatures, then digitized the sculptures using the Faro Arm, a portable coordinate measuring A wireframe model of Armadon, one of the beasties in the Primal Rage game. Every character machine from Faro Technologies in in the game started out as a sculpture, which was then digitized. A coordinate mapping sys- Lake Mary, Fla. tem ensured realistic movement. According to 3Name3D CEO, Sandeep Divekar, this approach assured his company of getting truly realistic recreations of the creatures. “Objects that fficionados of the popular must be replicated exactly must be digi- arcade , Primal tized or scanned rather than modeled on Rage, are well acquainted screen using CAD or other modeling with the combatants— software,” says Divekar. “We chose a Sauron, Talon, Blizzard, Ver- coordinate measuring machine to control tigo, Diablo, Chaos, and where we captured the x, y, z coordi- Armadon. These seven pre- nates. We chose the Faro Arm because historic fantasy creatures are the Primal Rage sculptures we created someA of the largest fighting game char- were up to three-feet long, and we need- acters, and each has a distinct personali- ed its large working envelope.” ty and fighting style. When Time Warner Interactive Inc. Three Architects in Milpitas, Calif. decided to recreate Pri- 3Name3D was founded by three archi- mal Rage for play on home video game tects—Oscar Yglesias, Steve Wallock, equipment, it was imperative that nothing and Divekar. The company creates digi-

34 GAME DEVELOPER • APRIL/MAY 1996 http://www.mfi.com/gdmag Caren D. Potter tal models for clients in a variety of realistic,” explains Divekar. (Imagine a industries and offers a collection of knee positioned mid-way up the thigh. ready-made computer models. The motion of that leg would not look For the Primal Rage project, Time very realistic.) How did Time Warner Warner supplied 3Name3D with the Because grid line placement affect- original nine-inch latex models that had ed the location of the joints and formed the basis for the arcade game 3Name3D needed precise control over characters. To create the arcade game, these lines, laser scanning was ruled out move critters to a these fully jointed models had been as a method of capturing the coordi- filmed using the stop-motion technique, nates. “If a model is going to sit off in in which a series of painstakingly small the corner of a digital set and not move, movements are recorded. Stop-motion it doesn’t need joints and, in that situa- would not work for the PC CD-ROM tion, laser scanning is fine,” says new platform? A game, according to Divekar, because it Divekar. “But laser scanners pick up would not supply the sufficient level of point locations in a regular pattern. A detail or the highly realistic motion jointed, moving model requires irregular Time Warner wanted. grid lines. With a coordinate measuring portable coordinate 3Name3D’s first step was to create machine, grid lines can be placed in its own set of sculptures of the Primal response to the animator’s needs. The Rage creatures. They made them bigger user tells it where to capture coordinates to capture more detail but otherwise they by pointing at them and then clicking measuring machine were identical to the original latex mod- the probe.” els. With the exception of Blizzard (a Although on previous projects gorilla), the new sculptures were con- 3Name3D had used another company’s structed of the modeling clay, Sculpey. small 3D digitizer, its probe was limited was key to replicating Sculpey couldn’t support Blizzard’s long to a sphere of 12 inches. The Primal arms, however, so Blizzard was sculpted Rage models were three-feet long. To in clay. A latex mold was made of the get the reach they needed, 3Name3D clay, then Blizzard was cast in plaster of bought a portable coordinate measuring the arcade game paris with armatures supporting his arms. machine with a six degrees of freedom Once the sculptures were complete arm and a spherical working envelope of and approved by Time Warner, the eight feet. process of recreating them as digital Called a “liberated” coordinate models began. First, grid lines were measuring machine, the Faro Arm used characters for a PC placed on the sculptures to indicate the by 3Name3D is not restricted to three locations of the points (x, y, and z coor- axes. Unlike some other digitizing meth- dinates) to be entered into the computer. ods, there are no line-of-sight limita- Coordinate location was a critical issue tions or restrictions on digitizing metal CD-ROM version of because the models were going to be ani- objects. Although generally used in labs, mated. “This meant they had to be bro- engineering offices, and manufacturing ken at joints, with each joint positioned facilities, computer artists are now start- precisely so the movement would look ing to use it. The Faro Arm features Primal Rage.

http://www.mfi.com/gdmag GAME DEVELOPER • APRIL/MAY 1996 35 3D MODELING

Digitizing the models.

digitizing a sculpture and adding sur- faces to the computer model. The entire Before and after pictures of Vertigo (left) and Sauron (right). The wireframe images appear operation, from making a sculpture to on top and the rendered versions are below. creating a fully surfaced, jointed digital model, took about 10 days per creature, and 3Name3D modeled five of the seven direct serial port input into AutoCAD uses audio cues to provide feedback to Primal Rage creatures. and other modeling packages and sup- the operator. When a point is entered, it For 3Name3D, the Primal Rage ports standard output formats such as signals the computer to emit one kind of project has led to additional work, in IGES, ASCII, DXF, and ACL. sound. If the point has to be locked on part due to the use of a digitizing arm. to a previous point, the computer makes “There’s no way we could have done this One-Person Digitizing a different sound when the two points without one,” says Divekar. Game artists Often, digitizing large objects is a two- are identified. The person who did the interested in rapidly creating complex person job—one person operates the digitizing of Primal Rage sculptures, shapes would do well to consider the probe while the other watches the com- who was also the artist who had created advantages of sculpting and digitizing puter screen to make sure data is cap- them, spent very little time looking at models rather than creating them entire- tured correctly. However, 3Name3D the screen.” ly digitally. The availability of large needed only one person to digitize the HyperSpace was also the software envelope, six-degree-of-freedom digitiz- Primal Rage creatures because the soft- used to create the surfaces over the ing arms makes this a valuable cost-cut- ware they used to capture input from the points. After the points representing a ting option. arm, Mira Imaging’s HyperSpace, incor- certain area of the sculpture were The PC CD-ROM version of Pri- porated audio feedback. entered, the software was given the com- mal Rage was released on August 25, Explains Divekar, “HyperSpace, mand to place a skin over them. 1995 along with versions for other which we run on a Macintosh computer, When the model was completely home game equipment such as the Sega digitized and surfaced, the HyperSpace Genesis, Super Nintendo Entertain- file was transferred to Wavefront’s ment System, and Nintendo Game Advanced Visualizer software running Boy. Time Warner has already shipped on a Silicon Graphics workstation. more than one million units of these There, it was cleaned up and broken new releases, and appears to have down into logical groups to make joints. another hit on its hands. ■ The last step was translating the Advanced Visualizer file to 3D Studio file format. (3D Studio was the model- Caren D. Potter is a freelance writer ing and animation software used by living in McKinleyville, Calif. She has A final screenshot of Talon vs. Time Warner.) been writing about computer technology, in Blizzard. It took 3Name3D about four days its various forms, for 10 years. Contact her per creature to complete the process of via e-mail at [email protected].

36 GAME DEVELOPER • APRIL/MAY 1996 http://www.mfi.com/gdmag THE Z BUFFER ALGORITHM

The Z Buffer Algorithm

show through closer surfaces, producing 5 4 3 2 1 0333 3 3 354 3 3 3 3 a surrealistic effect that is generally not 5 4 3 2 1 3 3 3 3 5 4 3 3 3 desirable. One method of dealing with this 5 4 3 2 3 3 3 3 5 4 3 3 3 += annoying problem of distant objects 5 4 3 3 3 5 4 3 3 showing through closer ones is to draw 5 4 3 3 5 4 3 3 all surfaces (polygons) in a back-to-front order. If done properly, this assures us 5 5 that the resulting view will be rendered ABCaccurately. Known as the Painter’s or Figure 1. The result of Z buffering polygon A and B is shown in Box C. Depth Sort Algorithm, this approach has three serious flaws: first, the amount of time it takes to sort the surfaces increases exponentially with regard to ears ago—when I got my feet the number of polygons in the dataset; wet in the virtual world of 3D second, precious time is wasted rasteriz- computer graphics—I stum- ing pixels that will be over-written fur- bled upon an algorithm. This ther down the list; finally, surfaces can- algorithm, in case the title of not penetrate each other (such as a boat this article hasn’t completely in water, or aircrafts soaring through spoiled the surprise, is popu- clouds). Though you can probably over- larly known as the Z buffer look the second and third deficiencies, algorithmY and deals with the slippery the first one is tough to swallow. In large problem of visual surface determination. datasets, the amount of sorting and test- Visual surface determination and its con- ing that must be performed is prohibi- verse, hidden surface elimination, are tively complex—rendering this method two approaches to solving the age-old useless for many modern applications. problem of correctly rendering 3D sur- Thus, many developers of 3D software faces on a 2D screen. have turned to two more flexible and In the real world, mere mortals can- faster approaches: BSP (Binary Space not see through opaque surfaces. How- Partition) trees and Z buffering. ever, in the world of 3D computer A BSP tree is a collection of poly- graphics, no such limitation exists. In gons listed in an order based on the rela- fact, we 3D programmers go to great tive position and orientation of all poly- lengths to impose this limitation on our gons to each other. Typically, the cre- 3D worlds so as to model the real world ation of this BSP tree is rather time- more accurately. The only other alterna- consuming, and, therefore, a BSP tree tive to imposing this limitation on our compiler creates it in advance. Though 3D worlds is drawing all polygons in the this method provides extremely quick dataset in an arbitrary order, ignoring sorting, it suffers from other problems of their 3D properties, which will almost the Painter’s Algorithm and imposes a guarantee that some distant surfaces will limitation of its own—it restricts the

38 GAME DEVELOPER • APRIL/MAY 1996 http://www.mfi.com/gdmag John De Goes dataset to static objects. The static pixel rasterized; if not, the process con- requirement of the BSP tree has tinues. (See Figure 1 for illustrations.) prompted a number of developers to As you might have guessed, this means search for ways to integrate moving the Z buffer must be cleared (reset) every If you are involved objects into a BSP tree without per- frame to some number (the farthest pos- forming time-consuming calculations, sible Z value), though a later optimiza- most of which are less than successful. tion removes this requirement. With the rise of faster processors, The only apparent difficulty we more memory, and video cards with might have is determining the Z (depth) with 3D graphics, you onboard Z buffers, the Z buffer algo- at each point, which is not as hard as it rithm is starting to look attractive to sounds. The equation for a plane or many developers simply because it over- polygon is as follows: comes all flaws of the Painter’s Algo- rithm (save number two, where a num- Ax + By + Cz + D = 0 are familiar with the ber of adaptations may be used while maintaining visual accuracy). The Z Solving for Z gives us: buffer algorithm is an image-precision algorithm, meaning it deals with visual Z = ( -Ax - By - D ) / C problem of visual surface determination at the image level, requiring an increase in memory However, we can compute Z incre- for an increase in resolution. With mentally for coplanar surfaces, which is 8MB of memory standard on today’s fortunate for our sakes because it saves machines and 16MB common, this us from solving the above at each pixel. surface determina- memory requirement is somewhat less Once the value of Z has been deter- than restricting, especially considering mined (which we’ll call Zc), the value of the number of problems the Z buffer Z at the following pixel is: eliminates. The Z buffer is, as implied by its Zc - (A / C) tion. The Z buffer name, a linear array of Z (the depth coordinate) values. Each pixel in the A single subtraction per pixel! As viewport corresponds to an element in fate would have it, however, we’ll mostly 1 the Z buffer. This array is designed to be interpolating /Z values instead of 1 algorithm can help hold the Z values of all the visible poly- direct Z values. The reason is simple: /Z gons in the viewport. When rasterizing is linear in screen space, and can be a polygon, before each pixel is written to interpolated using a linear equation, the viewport, the corresponding Z value whereas Z is linear in 3D space, and in the Z buffer is checked against the Z cannot be linearly interpolated in screen you get around the value of the pixel being rasterized. If the space. Since this means our Z values are Z value of the current pixel is closer to inverted, we must clear the Z buffer to the viewpoint than the Z value previous- zero each frame, which represents a lit- 1 ly stored in the Z buffer, the current Z eral infinity: the farthest possible /Z value is stored in the Z buffer and the value. On the positive side, interpolating problem.

http://www.mfi.com/gdmag GAME DEVELOPER • APRIL/MAY 1996 39 THE Z BUFFER ALGORITHM

Listing 1. Classes to Make a Z Buffer (Visual Surface Determination Algorithm Implementation)

a#include #include // Performs an “unsafe”, fast Z buffer write: // (Dest must be a 256 color buffer equal in dimensions // The precision to the right of the imaginary decimal point: // to the Z buffer.) const ZPREC = 26; // s00000.00000000000000000000000000 = 0.000000015 void FastWrite ( unsigned int Index, long Z, BYTE Val, BYTE *Dest ) class ZBuffer { { protected: if ( ZBuff [ Index ] < Z ) long *ZBuff, ZTrans; { WORD Init, Code; ZBuff [ Index ] = Z; unsigned int Width, Height; Dest [ Index ] = Val; public: } enum { NoMem = 0, Success }; }

// Sets defaults: // Performs an “unsafe”, fast Z buffer read: ZBuffer () : Init ( 0 ), Code ( NoMem ), long FastRead ( unsigned int Index ) ZBuff ( NULL ), ZTrans ( 0 ) { } { return ZBuff [ Index ]; // Accepts width and height for Z buffer creation: } ZBuffer ( int W, int H ) : Init ( 0 ), Code ( NoMem ), ZBuff ( NULL ), ZTrans ( 0 ) // Clears the Z buffer to zero: { Create ( W, H ); } // (Optionally accepts the number of completed // frames to aid in the clear reduction algorithm.) // Deallocates memory: BOOL Clear ( unsigned int FrameCount = 0 ); ~ZBuffer () { delete [] ZBuff; } };

// Initializes the Z buffer: inline BOOL ZBuffer::Create ( int W, int H ) inline BOOL Create ( int W, int H ); { // Function creates a Z-buffer - can be called // Width and height member functions: // in succession: unsigned int GetWidth () { return Width; } delete [] ZBuff; unsigned int GetHeight () { return Height; } ZBuff = NULL; Init = 0; // Returns the 1/Z translate value: ZTrans = 0; long GetZTrans () { return ZTrans; } if ( ( ZBuff = new long [ W * H ] ) == NULL ) // Returns the error code: { WORD GetCode () { return Code; } Code = NoMem; Width = 0; Height = 0; // Returns a pointer to the Z buffer (use with caution): return 0; long *GetPtr () { return ZBuff; } } Init = 1; Code = Success; // Performs a “safe”, slow Z buffer write: Width = W; Height = H; // (Dest must be a 256 color buffer equal in dimensions // to the Z buffer.) // Clear the Z buffer: void Write ( WORD X, WORD Y, long Z, BYTE Val, BYTE *Dest ) return Clear (); { } unsigned int Index; if ( ( Init ) && ( X < Width ) && ( Y < Height ) ) class ZEdge { { protected: Index = X + Y * Width; long Z, ZStep; if ( ZBuff [ Index ] < Z ) public: { ZEdge () : Z ( 0 ), ZStep ( 0 ) { } ZBuff [ Index ] = Z; // Clip function for clipping a coordinate to boundary: Dest [ Index ] = Val; void Clip ( int C, const B ) } { } // Takes advantage of the fact that } // ( ( a * ( b * c ) ) / c ) is equal to ( a * b ): if ( C < B ) // Performs a “safe”, slow Z buffer read: Z += ZStep * ( B - C ); long Read ( WORD X, WORD Y ) } { // Init function for stepping along polygon edges: if ( ( Init ) && ( X < Width ) && ( Y < Height ) ) inline void Init ( float OneOverZ1, float OneOverZ2, return ZBuff [ X + Y * Width ]; int Length, ZBuffer &ZBuff ); return 0; // Init function for stepping along scanlines: } inline void Init ( ZEdge &Left, ZEdge &Right,

40 GAME DEVELOPER • APRIL/MAY 1996 http://www.mfi.com/gdmag Listing 1. (Continued from p. 40) Listing 2. Code for Z Buffer Classes

unsigned int Width ); #include “ZBuffer.HPP” // Step operators: void operator ++ ( ) { Z += ZStep; } BOOL ZBuffer::Clear ( unsigned int FrameCount ) void operator ++ ( int ) { Z += ZStep; } { // Function returns the current fixed-point Z value: // Function clears — if necessary — the Z-buffer to long GetZ () { return Z; } // zero (infinity): }; // Calculate the number of frames before each Z buffer inline void ZEdge::Init ( float OneOverZ1, float OneOverZ2, // clear: int Length, ZBuffer &ZBuff ) unsigned int MaxWait = pow ( 2.0F, ( 31.0F - ZPREC ) ); { unsigned int N, Length, Rem; // Calculate the steps for a polygon edge: long FixedZ1, FixedZ2; // Determine if a clear is in order: if ( Length ) if ( MaxWait == 0 ) { Rem = 0; FixedZ1 = long ( OneOverZ1 * float ( 1 << ZPREC ) ); else Rem = FrameCount % MaxWait; FixedZ2 = long ( OneOverZ2 * float ( 1 << ZPREC ) ); Z = FixedZ1 + ZBuff.GetZTrans (); Length = Width * Height; ZStep = ( FixedZ2 - FixedZ1 ) / Length; if ( Init ) } { else { if ( Rem == 0 ) Z = 0; ZStep = 0; { } // If clear reduction is enabled, there is no need } // for an assembly Z buffer clear function as the inline void ZEdge::Init ( ZEdge &Left, ZEdge &Right, // Z buffer is cleared only once per so many frames. unsigned int Width ) for ( N = 0; N < Length; N++ ) { ZBuff [ N ] = 0; //Calculate the steps for a scan-line: ZTrans = 0; if (Width) } { // Else no clear - adjust translate value: Z = Left.GetZ (); else ZTrans += ( 1 << ZPREC ); ZStep=(Right.GetZ () - Z) / Width } // Return success: else { return TRUE; Z=0; ZStep = 0 } } } // Return failure: return FALSE; }

1 /Z allows us to use fast linear equations, closer than the previous frame by adding amount equal to the translate value. 1 while at the same time providing infor- a translation value to the /Z terms, thus The number of frames you can wait mation necessary for perspective texture eliminating the need to clear the Z before you clear the Z buffer (and reset mapping. buffer every frame. You can think of it as the translate value) will depend on Optimizations are also important. a translation of all polygons, bringing whether or not you’re using fixed-point Two of the most blindingly obvious per- them closer to the viewport each frame or floating-point math. If you use fixed- formance reducers of the Z buffer are by an amount proportional to the maxi- point math, the number of frames will the test per pixel and the actual clearing mum extents of the dataset. Though this depend on where you place your imagi- of the Z buffer. The clearing of the Z may sound a bit difficult, it adds but a nary decimal point. Traditionally, you’ll buffer cannot be avoided, but you can few lines of code. have a ClearZBuffer function in your reduce the number of Z buffer clears you To implement this optimization, main loop, perhaps such as: must perform by using 32-bit integers for every new frame you should add 1 1 for the Z buffer. I call this optimization more to each of the /Z terms than you ClearZBuffer ( ZBuffer ); the clear reduction algorithm, and it has added the previous frame, taking care saved many a processor cycle on my own not to exceed the limit of the data-type Using this optimization, that same applications. Since the values in the Z you are dealing with. By definition, the portion of code might become: 1 buffer are never greater than 1, and /Z terms will never exceed a [0-1] because 1 is the closest possible value to range, meaning that adding an offset to if ( ( FrameCount % MAX_WAIT ) == 0 ) the viewport, it is possible to fool the Z these terms will effectively translate the { buffer into thinking that each frame is dataset closer to the viewpoint by an ClearZBuffer ( ZBuffer );

http://www.mfi.com/gdmag GAME DEVELOPER • APRIL/MAY 1996 41 THE Z BUFFER ALGORITHM

ZTrans = 0.0F; one of the initialization functions For those curious souls among you, 1 } accepts two /Z values. You can calcu- I decided to put multiple Z buffer read else ZTrans += 1.0F; late these values by taking the inverse and write functions in the ZBuffer class of the Z values at the vertices of the because while debugging an application, Obviously, this example uses float- polygon. The other initialization func- you can use the slow, safe functions; ing-point math, which is a definite no- tion accepts two ZEdge classes, which when optimizing, you should be able to no as far as fast 3D graphics are con- represent the sides of the polygon at a easily convert to the fast, unsafe func- cerned. The ZTrans term is the value that given scan line. tions. Your application can use all the 1 is added to the /Z starting terms at each Typically, you will use one ZBuffer help it can get during debugging, and of the polygon’s vertices preceding ras- object per window, and three ZEdge since the safe functions cannot do any- terization. MAX_WAIT, is of course, the thing harmful to your system memory maximum amount of frames before the (barring unequally sized Z buffers and Z buffer is cleared, and FrameCount is the screen buffers), you can be assured that total number of frames that have been You can be the application’s problems will not be completed. related to the Z buffer classes. If much of what has been discussed One last word on the provided regarding Z buffers has been review for source code: the Z buffer write func- you—with the exception of the clear assured that the tions will actually write to the video reduction algorithm—you’re probably buffer, but the buffer must be equal in wondering what you can do to eliminate dimensions to that of the Z buffer, and the test per pixel that is required for an each byte in the buffer must represent a academic Z buffer. The solution is theo- application’s single pixel (with a range of 256 colors). retically simple, but a pain to implement: In mode 13h, for instance, this is the Z buffer at the scan-line level instead of case, as it is for many windowed appli- the pixel level. Using this approach, you cations running under Windows 95 or never have to write a pixel more than problems will not Windows NT. once, and the Z buffer never has to be For a discussion on proper rasteriza- cleared. Note that, in such an implemen- tion, I suggest checking out the highly tation, the Z buffer becomes a linked list regarded Computer Graphics: Principles and of scan-line information. be related to the Z Practice (Addison-Wesley, 1990) by It’s beyond the scope of this article Foley, van Dam, Feiner, and Hughes, or to discuss the subject of proper rasteri- back-ordering Chris Hecker’s excellent zation, so I will provide a set of 32-bit, series of Game Developer articles on tex- operating system independent classes buffer classes. ture mapping, which also covers correct instead of a full rasterizer. The classes rasterization. For more information on can easily be added to just about any the clear reduction algorithm, along with rasterizer. The classes, whose declara- objects for rasterizing polygons. One general information and source code for tion appears in Listing 1 and whose ZEdge object will represent the right side Z buffering, perspective texture mapping, non-inline code appears in Listing 2, of the polygon being rasterized, anoth- Phong shading, intensity interpolation, implement a Z buffer algorithm in er, the left side, and the third, the scan Gouraud shading, and related informa- fixed-point mathematics and include all line being rasterized. If you perform tion, you can pick up my up-coming the necessary code for the clear reduc- polygon clipping at the image level, you book, Cutting Edge 3D Game Program- tion algorithm (see above). Of particu- will find the Clip () member function ming (Coriolis Group, 1996). There are lar interest is the ZBuffer class’s Clear () most helpful, which accepts a coordi- many resources out there for anyone member function. This function nate and the boundary for that coordi- interested in the topic. ■ optionally accepts the number of frames nate. (The coordinate will be an X or Y that have been displayed since the pro- point, depending on which axis you are gram’s initialization. clipping on; an X point for scan-line John De Goes is a freelance C/C++ If you do not wish to use the clear clipping, and a Y point for the top of programmer currently working on high- reduction algorithm, it is not necessary the polygon clipping.) The ZEdge class performance 2-D and 3-D graphics soft- to provide this argument; however, overloads the ++ operator, so each time ware for individuals and companies providing it lets the function reduce you step in a coordinate (that is, step- wealthy enough to afford his outrageously the number of Z buffer clears that ping down the left or right edge of the high rates. He can be reached at occur without sacrificing visual quality. polygon or across the scan line), you can [email protected] for a mere In the ZEdge class, you will notice that simply use this operator. $10 a message (plus tax).

42 GAME DEVELOPER • APRIL/MAY 1996 http://www.mfi.com/gdmag FULL-SCREEN GRAPHICS

Full-Screen Graphics for Macintosh and Windows 95

he best entertainment meticu- wards to provide Windows 95 applications lously crafts an experience for its low-level hardware access comparable to audience. Just as the best film what has traditionally been available only directors carefully control the under DOS. Microsoft even provides a viewer’s experience, the best game consistent interface to eliminate the night- designers carefully control the mare configuration programs, buggy player’s experience. In simulation VESA drivers, and technical support calls and strategy games, this often over IRQ and DMA settings. Or such is involvesT a system of overlapping windows the religion it preaches. the player can arrange to access maps, We’ll start our DirectX experimenta- charts, and tools they need to play effec- tion with a function that sets up a com- tively. Most adventure and action games plete full-screen, double-buffered environ- immerse the player in the game world by ment for us, called BeginFullScreen. You controlling every visible pixel. In such tell this function the display settings you games, window elements like caption bars, want, and it sets everything up for you. window borders, and other applications in Listing 1 shows the complete source code the background waste space and intrude for BeginFullScreen, if you want to follow on the experience. our negotiations with DirectDraw. Games that use windows can benefit We need a window. Any window from a cross-platform windowing library will do because it’s just an anchor for like the one we’ve seen so far in XSplat. DirectDraw, so we’ll just use a static text For games that want the whole screen, window. The fun begins when we hook however, XSplat as it stands solves the up with DirectDraw. DirectDrawCreate wrong cross-platform problem. returns a pointer to a DirectDraw COM This month, I’m going to step back a object, essentially a pointer to a table of bit from the XSplat windowing system DirectDraw functions. You can think of it and head off in a different direction. as a C++ object except that when you’re We’re going to look into enabling full- done with it, you call Release instead of screen graphics on Windows and Macin- using the delete operator. tosh, leaving their integration with XSplat Once connected to DirectDraw, Set- for another day. CooperativeLevel tells the system that we Once again, I’m going to describe a want to take over the video hardware for a bit too much code to print in a magazine while, and SetDisplayMode makes the actual article, so you’ll find the complete source resolution switch. If the requested mode code on the Game Developer ftp site. isn’t available, SetDisplayMode will return an error code (something other than Direct to Windows DD_OK), and we’ll bail out of the setup func- The amount of hype and number of new tion. We’re going to run our sample appli- trademarks surrounding the Windows 95 cation at 640-by-480-by-8, a mode avail- Game SDK Featuring DirectX has been able on 99.99% of PC video hardware and incredible. The praise is also deserved: the a required mode in all Macintosh monitors DirectX team at the ’soft bent over back- other than the full-page portrait display.

44 GAME DEVELOPER • APRIL/MAY 1996 http://www.mfi.com/gdmag Jon Blossom After switching the video mode, the face immediately after a call to Flip or Blt static text window we created fills the may fail, forcing you to burn cycles wait- screen. DirectDraw only uses the window ing for the video hardware to catch up. as a link to the operating system, handling The flip or blt doesn’t involve the third all the graphics through DirectDraw sur- buffer, though, so one surface will always DirectDraw and faces. The window could be 1-by-1 and be available for drawing. If you can triple we would still have full-screen graphics, buffer, your application will never have to though we’d have problems receiving wait on a lock. mouse messages occurring over most of With a primary surface in hand, we the screen. now need to go for a secondary surface. If cross-platform DirectDraw uses low-level surfaces, DirectDraw succeeded in creating a page not high-level windows, so we need to flipping surface, GetAttachedSurface will create a primary surface representing the return a pointer to the off-screen buffer. If visible portion of video memory, the we had to settle for a simple primary sur- whole display. To create a surface, you use face, we have to create a second surface compatibility? Is it CreateSurface, passing a DDSURFACEDESC manually. The PageFlip global will tell us structure describing the surface you want. later what type of surface we have. The primary surface can have secondary Finally, we have to set up a color (off-screen) surfaces attached to it to environment by setting up an array of enable hardware page-flipping, so we’ll try PALETTENTRY structures, passing it to Cre- possible? Not only to take advantage of that. atePalette, and passing the resulting We begin by setting dwBackBuffer- DirectDrawPalette pointer on to Count to 2 and including the DDSCAPS_FLIP, SetPalette. DDSCAPS_COMPLEX, and DDSCAPS_VIDEOMEMORY If all this succeeds, we’ll have the flags in our primary surface request. This full-screen graphics environment we request asks DirectDraw to create a pri- always wanted (and always had under is it possible, mary surface and to allocate two addition- DOS!). al buffers in off-screen video memory that we can page flip into visible memory. If Managing the this fails, we try again for a primary sur- Macintosh Display face with only one off-screen buffer in Until recently, Macintosh systems we‘ve got the code video memory, and if this fails, we just required a specific dot pitch in their accept a standard no-frills primary surface. monitors. You could change the bit You may be wondering why we go depth of the display, but if you wanted for two offscreen buffers if we want only a more pixels, you bought a larger moni- double-buffered library. Well, Direct- tor. With the introduction of the Pow- to prove that it‘s Draw’s page flipping function can take erMacs, Apple made a number of place asynchronously, temporarily pre- changes to their software architecture, venting access to the two surfaces being including the Display Manager, which switched. It may wait for a vertical retrace worked its way back to the 68K Macs in before flipping or blting, which means system 7.5.1. With the Display Manag- possible! that an attempt to lock the offscreen sur- er installed, it’s possible for Mac appli-

http://www.mfi.com/gdmag GAME DEVELOPER • APRIL/MAY 1996 45 FULL SCREEN GRAPHICS

Listing 1. Setting Up a Full-Screen Environment Using DirectDraw (Continued on p. 47)

static HWND Window; DDSCAPS_FLIP | static HINSTANCE ghInstance; DDSCAPS_COMPLEX | DDSCAPS_VIDEOMEMORY; static LPDIRECTDRAW pDirectDraw; DDReturn = pDirectDraw->CreateSurface(&SurfaceDesc, static LPDIRECTDRAWSURFACE pPrimarySurface; &pPrimarySurface, 0); static LPDIRECTDRAWSURFACE pOffscreenSurface; if (DDReturn != DD_OK) static LPDIRECTDRAWPALETTE pPalette; { // We couldn’t get a triple buffer, try a double-buffer static int PageFlip; SurfaceDesc.dwBackBufferCount = 1; DDReturn = pDirectDraw->CreateSurface(&SurfaceDesc, int BeginFullScreen(int Width, int Height, int Depth) &pPrimarySurface, 0); { if (DDReturn != DD_OK) // Create a Width x Height popup window using the STATIC { // control class so we don’t have to implement a window // We couldn’t get a page-flip-able surface at all. // procedure right now PageFlip = 0; Window = CreateWindow(“STATIC”, “FullScreen”, WS_POPUP, 0, 0, Width, Height, // Just go for a no-frills primary surface 0, 0, ghInstance, 0); SurfaceDesc.dwFlags = DDSD_CAPS; if (!Window) SurfaceDesc.dwBackBufferCount = 0; goto Failure; SurfaceDesc.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE; DDReturn = pDirectDraw->CreateSurface(&SurfaceDesc, ShowWindow(Window, SW_SHOWNORMAL); &pPrimarySurface, 0); UpdateWindow(Window); if (DDReturn != DD_OK) goto Failure; // Connect to DirectDraw, if not already connected } if (!pDirectDraw) } DirectDrawCreate(0, &pDirectDraw, 0); if (!pDirectDraw) if (PageFlip) goto Failure; { // Get the attached page-flip-able surface as the // Set up DirectDraw for full-screen exclusive mode at the // offscreen buffer // requested resolution DDSCAPS caps; HRESULT DDReturn; caps.dwCaps = DDSCAPS_BACKBUFFER; DDReturn = pDirectDraw->SetCooperativeLevel(Window, DDReturn = pPrimarySurface->GetAttachedSurface(&caps, DDSCL_EXCLUSIVE | DDSCL_FULLSCREEN); &pOffscreenSurface); if (DDReturn != DD_OK) } goto Failure; else { DDReturn = pDirectDraw->SetDisplayMode(Width, Height, Depth); // Create a second surface for the offscreen buffer if (DDReturn != DD_OK) ZeroMemory(&SurfaceDesc, sizeof(SurfaceDesc)); goto Failure; SurfaceDesc.dwSize = sizeof(SurfaceDesc); SurfaceDesc.dwFlags = DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH; // Create the primary surface SurfaceDesc.ddsCaps.dwCaps = DDSCAPS_OFFSCREENPLAIN; // Try to get a triple-buffered one we can page flip SurfaceDesc.dwWidth = Width; PageFlip = 1; SurfaceDesc.dwHeight = Height; DDSURFACEDESC SurfaceDesc; ZeroMemory(&SurfaceDesc, sizeof(SurfaceDesc)); DDReturn = pDirectDraw->CreateSurface(&SurfaceDesc, SurfaceDesc.dwSize = sizeof(SurfaceDesc); &pOffscreenSurface, 0); SurfaceDesc.dwFlags = DDSD_CAPS | DDSD_BACKBUFFERCOUNT; } SurfaceDesc.dwBackBufferCount = 2; SurfaceDesc.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE | if (DDReturn != DD_OK)

46 GAME DEVELOPER • APRIL/MAY 1996 http://www.mfi.com/gdmag Listing 1. (Continued from p. 46) we’ll scan through that list until we find an appropriate one. goto Failure; DMGetIndexedDisplayModeFromList iter- ates through the list for us. You give this // Set up a palette - a grey wash in 0..255 function a pointer to a callback function PALETTEENTRY PaletteColors[256]; and a pointer to some data of your choice, int i; and it invokes the callback on each element for (i=0; i<256; ++i) in the list. NewDMDisplayModeListIteratorProc { (whew!) creates a universal procedure PaletteColors[i].peRed = i; pointer to use as your callback (this is simi- PaletteColors[i].peGreen = i; lar to the Win16 MakeProcInstance func- PaletteColors[i].peBlue = i; tion). We’ll pass along a custom DisplayMode PaletteColors[i].peFlags = PC_RESERVED; Request structure that tells the callback what } resolution to look for and includes space for it to return the csMode and csData codes if it DDReturn = pDirectDraw->CreatePalette(DDPCAPS_8BIT, finds the requested resolution. PaletteColors, &pPalette, 0); Once out of the loop, ModeRequest will if (DDReturn != DD_OK) contain valid information if the Display goto Failure; Manager reported a mode we can use. If so, DMSetDisplayMode will make the switch for // Attach the palette to the surface us. DDReturn = pPrimarySurface->SetPalette(pPalette); Finally, we can create an offscreen if (DDReturn != DD_OK) GWorld for the window as we did before, and goto Failure; we have total double-buffered control at the desired resolution. // Success! return 1; Offscreen Access A few more functions round out our full- Failure: screen needs. EndFullScreen will undo every- return 0; thing done by BeginFullScreen. SwapBuffer } will either copy or page flip the offscreen buffer onto the screen. SwapRect will copy a portion of the offscreen buffer onto the cations to exert low-level control over tion to recover the screen space used by screen. OffscreenLock and OffscreenUnlock display settings. the Macintosh menu bar. Once it’s gone, will give us access to the bits of the off- Display Manager 1.0 now ships as we’ll create a window of the requested size screen image, and between these two calls, part of System 7.5.1, but it sports a and set up a palette as I discussed in previ- GetOffscreenBits and GetOffscreenStride clunky programming interface and is not ous articles. will provide us with the information we always reliable. Display Manager 2.0 is Now the Display Manager comes into need to draw on the surface. available as an extension for these systems play. The first thing to do is to store away On the Macintosh, we don’t have to and is integrated into System 7.5.2. It’s the current display settings so we can learn anything new. Sure, we’ve used the cleaner and simpler, so we’ll be writing restore them when we’re done harassing the Display Manager to tweak the monitor to for version 2.0. video hardware. A call to GetMainDevice the settings we want, but otherwise every- If you don’t have Display Manager gives us a handle to the main display device, thing’s fundamentally the same: we still 2.0, you can download it from Apple’s ftp and DMGetDisplayMode fills us in on its cur- have a window, a GWorld, and palette. We’ll site, at ftp://ftp.info.apple.com/ rent settings. still use CopyBits to get the GWorld to the Apple.Support.Area/Developer_Services/ On the Macintosh, a display mode is screen, and we’ll still lock and unlock the Development_Kits/Display_Manager_ defined by two numbers: csMode and csData, bits of the GWorld PixMap to gain access to Development_Kit. which together describe a unique color for- the offscreen buffer, as I demonstrated Listing 2 shows the complete Begin- mat, resolution, and refresh rate setting. In before. FullScreen procedure for the Macintosh so order to change the display mode, we have Under Windows, however, things you can sing along. to find out the appropriate secret numbers have changed. No more DIBSections, no The first step to taking over the Mac- for the mode we want. The Display Man- more WinG. We’re now cooking with intosh display is to get rid of that pesky ager will provide us with a list of available DirectDraw surfaces, and they require menu bar. I’ve written a StealMenuBar func- modes through DMNewDisplayModeList, and some special handling. The OffscreenLock

http://www.mfi.com/gdmag GAME DEVELOPER • APRIL/MAY 1996 47 FULL SCREEN GRAPHICS

Listing 2. Setting Up a Full-Screen Environment Using Display Manager 2.0 (Continued on p. 49)

static WindowPtr Window; pVPBlockInfo = static PaletteHandle hPalette; pModeInfo->displayModeDepthBlockInfo-> static GWorldPtr pOffscreenGWorld; depthVPBlock[Count].depthVPBlock; static GDHandle DisplayDevice; if (pVPBlockInfo->vpPixelSize == static unsigned short csPreviousMode; pRequest->DesiredDepth && static unsigned long csPreviousData; pVPBlockInfo->vpBounds.right == pRequest->DesiredWidth && // This structure encapsulates the data sent to the Display Manager list pVPBlockInfo->vpBounds.bottom == // enumeration callback function. We fill in the desired values, pass pRequest->DesiredHeight) // this on through the enumeration, and it fills in the csMode and { // csData info we need. // Found a mode that matches the request! struct DisplayModeRequest pRequest->csMode = pSwitchInfo->csMode; { pRequest->csData = pSwitchInfo->csData; // Returned values } unsigned short csMode; } unsigned long csData; } } // Provided values int BeginFullScreen(int Width, int Height, int Depth) long DesiredWidth; { long DesiredHeight; // Hide the menu bar long DesiredDepth; StealMenuBar(); }; // Create a window of the requested size // This function filters through the display modes reported by the Rect WindowRect = { 0, 0, Height, Width }; // Display Manager, looking for one that matches the requested Window = NewCWindow(0, &WindowRect, “\pFullScreen”, // resolution. The userData pointer will point to a DisplayModeRequest TRUE, plainDBox, // structure. WindowPtr(-1), FALSE, 0); pascal void DisplayModeCallback(void* userData, DMListIndexType, if (!Window) DMDisplayModeListEntryPtr pModeInfo) goto Failure; { DisplayModeRequest *pRequest = (DisplayModeRequest*)userData; // Set up a palette with a gray wash hPalette = NewPalette(256, 0, pmExplicit | pmAnimated, 0); // Get timing info and make sure this is an OK display mode if (!hPalette) VDTimingInfoRec TimingInfo = *(pModeInfo->displayModeTimingInfo); goto Failure; if (TimingInfo.csTimingFlags & 1<displayModeDepthBlockInfo->depthBlockCount; { Color.red= i << 8; // Filter through each of the modes provided here Color.green = i << 8; VDSwitchInfoRec *pSwitchInfo; Color.blue = i << 8; VPBlock *pVPBlockInfo; for (short Count = 0; Count < DepthCount; ++Count) SetEntryColor(hPalette, i, &Color); { } // This provides the csMode and csData information pSwitchInfo = // Force 0 and 255 to White and Black pModeInfo->displayModeDepthBlockInfo-> SetEntryUsage(hPalette, 0, depthVPBlock[Count].depthSwitchInfo; pmExplicit | pmAnimated | pmWhite, 0); SetEntryUsage(hPalette, 255, // This tells us the resolution and pixel depth pmExplicit | pmAnimated | pmBlack, 0);

48 GAME DEVELOPER • APRIL/MAY 1996 http://www.mfi.com/gdmag Listing 2. (Continued from p. 48)

SetPalette(Window, hPalette, TRUE); for (short Count = 0; Count < DisplayModeCount; ++Count) { // Store information about the current display settings DMGetIndexedDisplayModeFromList(DisplayModeList, Count, DisplayDevice = GetMainDevice(); 0, uppDisplayModeCallback, (void*)&ModeRequest); if (!DisplayDevice) } goto Failure; // Done with the list csPreviousMode = -1; DMDisposeList(DisplayModeList); csPreviousData = -1; // Done with the callback VDSwitchInfoRec DisplayInfo; DisposeRoutineDescriptor(uppDisplayModeCallback); OSErr MacError = DMGetDisplayMode(DisplayDevice, &DisplayInfo); if (MacError != noErr) // If we found a mode fitting the request, switch to it! goto Failure; if (ModeRequest.csMode == -1 || ModeRequest.csData == -1) goto Failure; csPreviousMode = DisplayInfo.csMode; csPreviousData = DisplayInfo.csData; DisplayInfo.csMode = ModeRequest.csMode; DisplayInfo.csData = ModeRequest.csData; // Get the display ID for the main display DisplayIDType DisplayID; unsigned long Mode = DisplayInfo.csMode; DMGetDisplayIDByGDevice(DisplayDevice, &DisplayID, FALSE); MacError = DMSetDisplayMode(DisplayDevice, DisplayInfo.csData, &Mode, // Use it to get a list of available modes from the (unsigned long)&DisplayInfo, // Display Manager 0); DMListIndexType DisplayModeCount = 0; if (MacError != noErr) DMListType DisplayModeList; goto Failure; MacError = DMNewDisplayModeList(DisplayID, 0, 0, &DisplayModeCount, &DisplayModeList); // Create a matching GWorld using current device and window if (MacError != noErr) CGrafPtr CurrentPort = (CWindowPtr)Window; goto Failure; PixMapHandle CurrentPixMap = CurrentPort->portPixMap; // Create a callback function pointer to filter available modes CTabHandle ColorTable = (*CurrentPixMap)->pmTable; DMDisplayModeListIteratorUPP uppDisplayModeCallback = NewDMDisplayModeListIteratorProc(DisplayModeCallback); NewGWorld(&pOffscreenGWorld, (short)Depth, if (!uppDisplayModeCallback) &CurrentPort->portRect, ColorTable, DisplayDevice, noNewDevice); { if (!pOffscreenGWorld) // Aborting - let go of the mode list goto Failure; DMDisposeList(DisplayModeList); goto Failure; // Success! } return 1;

// Go through the list, comparing each available mode with Failure: // this mode request RestoreMenuBar(); DisplayModeRequest ModeRequest; return 0; ModeRequest.csMode = -1; } ModeRequest.csData = -1; ModeRequest.DesiredWidth = Width; ModeRequest.DesiredHeight = Height; ModeRequest.DesiredDepth = Depth;

http://www.mfi.com/gdmag GAME DEVELOPER • APRIL/MAY 1996 49 FULL-SCREEN GRAPHICS

Listing 3. Loading a DirectDraw Surface Listing 4. A 640x480x8 Cross-Platform Demo

static char unsigned *pBits; void DemoMain(void) static long Stride; { if (BeginFullScreen(640, 480, 8)) int OffscreenLock(void) { { // Go for 10 seconds int ReturnValue = 0; char unsigned Color = 0; long unsigned Time = GetMillisecondTime(); pBits = 0; while (GetMillisecondTime() - Time < 10000) Stride = 0; { if (OffscreenLock()) DDSURFACEDESC SurfaceDesc; { ZeroMemory(&SurfaceDesc, sizeof(SurfaceDesc)); // WARNING: YOU CANNOT USE A DEBUGGER IN BETWEEN SurfaceDesc.dwSize = sizeof(SurfaceDesc); // LOCK..UNLOCK CALLS WHEN USING DIRECTDRAW!

// Loop until an error occurs or the lock succeeds // Draw a wash offscreen using memset HRESULT DDReturn = DD_OK; char unsigned *pSurface = GetOffscreenBits(); while (1) long Stride = GetOffscreenStride(); { // Attempt the lock for (int i=0; i<480; ++i) DDReturn = pOffscreenSurface->Lock(0, &SurfaceDesc, 0, 0); { memset(pSurface, (Color + i)%256, 640); if (DDReturn == DD_OK) pSurface += Stride; { } // Successful lock - store bits and stride pBits = (char unsigned *)SurfaceDesc.lpSurface; OffscreenUnlock(); Stride = SurfaceDesc.lPitch; // OK TO USE A DEBUGGER NOW ReturnValue = 1; break; // Next time through we’ll use a different color } // (Allow this to overflow back to zero) else if (DDReturn == DDERR_SURFACELOST) ++Color; { } // Attempt to restore the surfaces DDReturn = pPrimarySurface->Restore(); SwapBuffer(); if (DDReturn == DD_OK) } DDReturn = pOffscreenSurface->Restore(); }

if (DDReturn != DD_OK) // Undo everything done by BeginFullScreen. { // Even if BeginFullScreen failed, it may have partially succeeded // Surfaces could not be restored - lock fails // and may require cleaning up break; EndFullScreen(); } } } else if (DDReturn != DDERR_WASSTILLDRAWING) { // Some other error happened - fail break; } }

return ReturnValue; }

and OffscreenUnlock functions just map of our surfaces before we can use them returning, eliminating the possibility of onto calls to DirectDraw’s Lock and again. Although this shouldn’t happen contention, but that may waste time you Unlock, but these may fail if the surface is when we’ve set ourselves to DDSCL_EXCLU- could spend doing some other processing. busy. SIVE, we should be ready for it. We have Listing 3 shows the DirectDraw If an asynchronous blt or a flip has to wait in a while(1) loop trying to lock implementation of OffscreenLock. The been started but hasn’t finished, we’ll the surface until we receive a DD_OK or a other functions use a similar loop to wait receive a DDERR_WASSTILLDRAWING code from fatal error code. until the operation succeeds, bailing out if most DirectDraw functions, indicating A similar situation occurs during a an error occurs. that we have to wait until the hardware Flip, a Blt, or a BltFast call: it may be nec- has completed its task. If we receive a essary to wait until the surface becomes This Month’s Cheesy Demo DDERR_SURFACELOST notification, Direct- available. Passing DDFLIP_WAIT, DDBLT_WAIT, Of course, to prove this works, I have to Draw has given our video memory to or DDBLTFAST_WAIT will force DirectDraw to write a simple cross-platform program someone else, and we have to restore all wait until the operation completes before using these functions. Unfortunately,

50 GAME DEVELOPER • APRIL/MAY 1996 http://www.mfi.com/gdmag there’s no means of user input in this page fault handler to switch video banks problem remains. Don’t forget! month’s code, though by combining the when you cross a boundary. Only one • When you shrink the resolution of the full-screen code presented here with the display memory bank can be active at screen, Display Manager 2.0 will reposi- message processing architecture in XSplat, any time, so if you write across one of tion the open windows and icons on the you can easily build an interactive system. these boundaries, the fault handler will desktop. When you set the resolution This month’s demo has the simple thrash as it attempts to write to both back, it may not replace them, leaving goal of setting up a 640-by-480-by-8 pages at once. This will hang your sys- your desktop looking very strange. graphics environment and drawing palette tem. Using only 32-bit aligned writes • The display mode you request through washes for ten seconds, starting each wash will guarantee that you never write BeginFullScreen may not be available. with a different index. The resulting pat- across one of these boundaries. You can ask for a 100x609x13 display if tern will make you feel like your old black- • Because the SwapBuffer function may you want, and BeginFullScreen will try and-white has lost vertical synch. The use flip instead of blt, there is no guar- to accommodate you. A more robust code is shown in Listing 4. If you’re look- antee of the contents of the offscreen system would provide a list of available ing at this with a page-flipped DirectDraw buffer after a swap. After a flip, the modes rather than leaving you to cross surface, you’ll see how incredibly smooth buffer will contain the former contents your fingers, but do you expect a maga- page flipping can be. of the display. After a blt, it will remain zine article to do all your work for you? The GetMillisecondTime function was the same. If you need to preserve the That’s it! You can find the complete presented in my last article, if you’re won- contents of your offscreen buffer, always source code referenced in this article on dering about that. It maps onto timeGet- use SwapRect instead of SwapBuffer. the Game Developer ftp site. ■ Time on Windows and TickCount (or • DirectDraw preserves color 0 as black Microseconds) under MacOS. and color 255 as white. Changing the Jon Blossom sometimes wishes operating Macintosh display resolution and creat- systems would go away so he could stop Thoughts and Warnings ing a full-screen window doesn’t cause tweaking with Macintosh, Windows, OS/2, Before I return to my cage for the next the Mac to release colors 0 (white) and and X. He can be reached at [email protected] couple of months, there are a few hairy 255 (black) either, so the color zero or through Game Developer magazine. details you should hear about before plunging in with this full-screen API. Here’s my laundry list of warnings: • When you lock a DirectDraw surface, DirectDraw grabs the Win16 lock, the semaphore that prevents reentrant exe- cution of 16-bit system code including GDI and USER. This means that essential system components shut down as long as you have a locked surface. If you attempt to step through code with a GUI debugger while a surface is locked, you will hang the system. • SetCooperativeLevel uses the contents of the GWL_USERDATA bytes of a window to store information used to restore the display state. This means that the HWND- to-CXSplatWindow mapping used in my previous articles can not coexist with DirectDraw. If you want to use this association technique, set cbWndExtra to sizeof(CXSplatWindow*) when registering the “XSPLAT” window class and use 0 instead of GWL_USERDATA when setting or retrieving the data. • On many banked display cards, Direct- Draw emulates direct video access using a virtual device driver called VFLATD.386, which maps video memory banks onto selectors and uses a

http://www.mfi.com/gdmag GAME DEVELOPER • APRIL/MAY 1996 51 FUZZY LOGIC IN GAMES

Fuzzy Logic in Games

accompanying source code should make it concrete. A fuzzy linguistic variable is an array of labels such as “Hot,” “Warm,” “Cool,” “Cold.” Associated with this array is a mapping of a crisp values such as 68° F into the array. This mapping is done with trapezoidal membership defi- nitions, as illustrated in Figure 1. For each slot in the array, the logic designer chooses four numbers representing the begin low, full membership low, full membership high, and begin high values. Listing 1 shows a simple and quick func- tion for assigning a membership value to a value. As Figure 1 shows, a single crisp value can have some amount of member- ship in several slots in the FLV. For instance, the way I’ve designed the room temperature manifold, 68° is an inflec- Figure 1. Trapezoids map precise variables such as temperature into linguistic variables such tion point, where the set changes from as “Warm.” some membership in Cool as well as Warm to some membership in Hot as well as Warm. The greater the overlap you put in your manifolds, the more continuous will be the fuzzy logic uzzy logic is a powerful artificial response curve—in effect, your critters intelligence (AI) technique will be less decisive. By decreasing the appropriate in many gaming overlap, you can tune your AI for the situations. The basic fuzzy opposite effect—more capriciousness. technique is to specify a situa- This is the essence of fuzzy logic—mani- tion using fuzzy linguistic vari- fold tuning, which can be done by a ables (FLVs), which, when nonprogrammer on a spreadsheet, can cross-referenced on a fuzzy create dazzlingly complex results. associativeF matrix (FAM), create a “fuzzy The complexity stems from the set” on a third FLV. A fuzzy manifold fuzzy associative matrix, a matrix in can either be manipulated as its own type which two FLVs combine to specify of object or it can be defuzzified into a membership in a third, as shown in Fig- more traditional crisp value. Similarly, ure 2. Adjusting the FAM provides gross crisp values can be fuzzified into FAMs. adjustments in fuzzy logic, while mani- If that jargon didn’t explain it all, the fold tuning provides the richness. A

52 GAME DEVELOPER • APRIL/MAY 1996 http://www.mfi.com/gdmag Larry O’Brien fuzzy system is simply one that sets up and relative strength) and the conse- input FLVs and uses the resulting out- quent (movement) are roughed out. For put FLV to specify behavior. simple purposes, you might choose, As a concrete example of the power “Proximate,” “Near,” “Separated,” and Forget classical of fuzzy logic, let’s say you were working “Far” as your distance FLVs “Dead on a real-time strategy game of the Meat,” “Overmatched,” “Equal,” Command & Conquer school. It’s usual- “Undermatched,” and “Steamroller” for ly very difficult to get to work on the AI relative strengths, and “Run away,” “Sur- for such a game early in the design render,” “Retreat,” “Fall Back,” “Hold,” expert systems. process, but fuzzy logic lets you do so. “Probe,” “Assault,” and “Overrun” for The AI designer can start with general movement. Behavior can then be rules such as, “Distance to the enemy roughed into a Fuzzy Associative and relative strength determine unit Matrix, such as that shown in Figure 3. movement.” After the rules have been In a classical expert system or with Fuzzy logic makes determined, the FLVs associated with naive state-based AI, the richness of this the antecedents (distance to the enemy rule is severely reduced by the three-fold your game AI subtle

and complex, but it is

easy to program and

lightning fast at run-

time. Here‘s a look at Figure 2. The two top fuzzy sets define the inputs to fuzzy output set at the bottom. Notice asymmetries introduced to make AI more aggressive. FLVs and FAMs.

http://www.mfi.com/gdmag GAME DEVELOPER • APRIL/MAY 1996 53 FUZZY LOGIC IN GAMES

Listing 1. A Quick Function for Determining Membership in a Trapezoidal Fuzzy Set pigeonholing of crisp values. We all know games where opponent behavior is class FuzzySet{ clearly discontinuous—stand at one spot public: and the guards will ignore you, move ... another step closer and they start swarm- float Membership(const float& inVal); ing at you in their predictable manner. private: Fuzzy logic creates richer, continuous float lowMin, lowTrue, highTrue, highMin; responses by evaluating all the rules, but } gauging them on a spectrum ranging from totally false to totally true, with float FuzzySet::MemberShip(const float& inVal){ infinite gradations (rejecting the law of if(inVal > lowMin && inVal < highMin){ the excluded middle and the law of con- if(inVal > lowTrue){ tradiction, for you fans of dead Greek if(inVal < highTrue){ mathematicians). Since it evaluates all membership = 1.0; the rules, the performance of a fuzzy }else{ logic inference engine degrades propor- //must be on high edge tional to the total number of rules, and it membership = (inVal - lowTrue) / (highMin - lowTrue); is not subject to the catastrophic non- } linear degradations that classical expert }else{ systems are prone to. //must be on low edge After filling in the FAM and the membership = (inVal - lowMin) / (lowTrue - lowMin); FLV array for the fuzzy expert system, } evaluation is the next step. Each cell in }else{ the FAM represents a rule so, for membership = 0.0; instance, the upper-left corner of the } matrix in Figure 3 represents the fuzzy return membership; rule, “If the forces are engaged, and ); we’re dead meat, surrender.” To evaluate the rule, we determine the membership in the input FLVs as described previous- ly and illustrated in Listing 1. While dis- tance is a crisp value, membership in the Relative Strength FLV is probably the result of another fuzzy rule. Assume that membership in the “dead meat” FLV is 28%. The degree of membership in the output is set equal to one of these two values—the minimum if the rule “and”s the antecedents, the maximum if the rule “or”s them. In this case, the rule is intended to be read “If the forces are engaged, and we’re dead meat, surren- der,” and not “If engaged or dead meat, surrender,” so we set the membership in “surrender” for this rule to 28%. Since fuzzy logic allows various shades of truth, the entire rulebase is evaluated, setting various memberships in each of the output FLVs. For an “and” FAM, the maximums of the out- put values are chosen, if an “or” is cho- Figure 3. Being able to see and edit an entire matrix of rules simultaneously is one of the sen, the minimums are taken. A typical strengths of fuzzy logic. result is shown in Figure 4. This output fuzzy set can be used as input to another rule or, if necessary, defuzzified by the

54 GAME DEVELOPER • APRIL/MAY 1996 http://www.mfi.com/gdmag simple technique of calculating the cen- troid of the polygon. Fuzzy logic is an extraordinarily powerful and flexible artificial intelli- gence technique that is much easier to program than alternatives such as classi- cal expert systems. Unlike neural net- works, fuzzy logic systems can be tuned manually, and unlike genetic-based sys- tems, fuzzy systems work “out of the box.” For continually improving perfor- mance, you can use machine-learning techniques to modify the parameters of the FLVs. Of course, “improved” is a fuzzy concept itself, and judging the effi- cacy of a move can be as hard or harder than making the move in the first place. Strategic analysis techniques, one of the oldest and deepest veins in the field of artificial intelligence, will have to wait for another day, however. ■ Figure 4. A moderate distance and slightly inferior enemy make for a cautious advance.

Editorial Director Larry O’Brien spe- cializes in artificial forms of intelligence.

http://www.mfi.com/gdmag GAME DEVELOPER • APRIL/MAY 1996 55 CHOPPING BLOCK

Blizzard of ’96

Mike Michaels elcome to Chopping The game is played from an over- Block. In this issue, we’ll head, isometric viewpoint. Unlike other look at Warcraft II: Tides games in this genre, the viewpoint is The secret to gaming of Darkness, the sequel to close enough to the ground that both last year’s sleeper hit, War- the buildings and the creatures are ren- craft: Orcs & Humans. dered with a high degree of detail. This Warcraft II is a real-time propensity of detail stems from the strategy war game with a game objects (creatures, buildings, ves- Wfantasy theme. The object is to survive sels) being first modeled (using 3D Stu- success is getting long enough to decimate all opposing dio or the like) and then rendered at the forces and destroy all they hold dear. required sizes. The knights you control Like its predecessor, the heart of the in the game are rendered from the same game is resource management. Before model used to generate the knights in you can train your knights and archers, the cut-scenes. users hooked on your you must have a barracks to train them The game is tile based, and all in. Before you can build a barracks, you game objects are an integral number of must mine enough gold and harvest tiles large. Don’t make the mistake of enough trees. Before you can mine gold assuming that the game looks blocky. and harvest trees, you must have peasants The programmers did a wonderful job game. Discover what to do the work for you. How you allocate when they created their map editor. I your limited resources can mean the dif- won’t venture a guess as to what algo- ference between victory and defeat. rithm they used to create their coast- the folks at Blizzard

Entertainment did to make Warcraft II such

an addictive game. In Warcraft II: Tides of Darkness, the player has to learn to manage resources effectively.

http://www.mfi.com/gdmag GAME DEVELOPER • APRIL/MAY 1996 57 CHOPPING BLOCK

lines, but I was extremely impressed by Warcraft II: Tides of Darkness how natural and asymmetric it all is. A creature can move without too much Blizzard Entertainment System Requirements: 486DX/33, hint of tile transitions. Obviously, P.O. Box 18979 8MB RAM, 29MB free hard-drive space, enough frames of animation were pro- Irvine, Calif. 92713 SVGA graphics, Sound Card (Redbook Tel: (800) 953-7669 Audio, General Midi, Sound Blaster, PAS, vided to make the tile transitions seam- Web: http://www.blizzard.com/ Gravis, and compatibles), and a double- less. The only time you realize this Price: $54.95 speed CD-ROM drive. underlying tile system is when a creature must go around another creature or object. When this occurs, the creature makes a 45-degree turn and moves to a via null modem, modem, and IPX net- omniscient intelligence, the computer diagonal tile. Then the creature finds work. With a network connection, up to opponent makes the same mistakes the nearest tile it can move to that reori- eight simultaneous players are possible, repeatedly. ents it on its goal. The overall effect is including computer opponents. For example, assume there is a gold that the creatures move in a very unnat- I didn’t get a chance to try the mine out of visual range for any of the ural manner (angular rather than a more direct connect or modem options, but I enemy’s fighting units. You can sit a few natural, circular path). can attest that the game plays smoothly soldiers and archers around the mine The interface is very intuitive. You over a standard IPX network. I installed and pick off enemy peons as they come can control creatures using either the it at work on two Pentium machines to mine the gold. If this happened to a mouse or the keyboard (or a combina- running Windows 95 with standard net- human player, units would be dis- tion of both). Simply clicking the cursor work support. No extra effort was patched almost immediately to get rid of on a creature selects that creature and required, the game picked up connec- the troublemakers screwing up the gold brings up a series of buttons represent- tion immediately, and the speed of game supply. The computer opponent doesn’t ing actions the creature can perform. play seemed to be identical to that of seem to notice that the peons it is send- Moving the cursor over one of the but- single-player mode. ing to collect gold never seem to return. tons brings up a description of the If you choose to play the single- The map editor is included with action and, if appropriate, the amount of player game, fourteen human and four- the game so that you can create your resources that must be paid to perform teen orc campaigns are provided. Things own scenarios. The map editor requires the action. don’t really start getting difficult until Windows 95 to execute. Building maps Distinguishing itself from it’s pre- around the sixth or seventh campaign, at is a snap. It’s as simple as selecting an decessor, Warcraft II provides sea and which point they get very challenging. object and clicking on the map screen. air units along with shipyard and Unfortunately, this challenge isn’t really There’s even an animate feature that will aviaries to train these units. The beauty due to increasing the game’s artificial let you give your scenario a test run. of the interface is that there is essentially intelligence (AI). Rather, the challenge Like it’s predecessor, Warcraft II is no difference between controlling a sol- comes from increasing the amount of extremely addictive. The graphics are dier and controlling a battleship. The resources your enemy starts the scenario vibrant; the sound is great (hilarious at same options are available for both. Just with. It can be a little discouraging to be times); and the ability to play the game choose an option and choose a target. attacked by dragons when you can’t even against many opponents makes this a It’s that simple. build flying units yet. sure bet at bringing the office network Warcraft II lets players choose But other than the numerical to a standstill. either single-player or multiplayer sce- advantage, the computer opponent That’s it for this month. I’m still narios. Multiplayer support is available doesn’t appear to cheat. It seems to be interested in hearing your opinions following the exact same rules you have about the direction that you’d like to see to follow. On the other hand, the AI this column progress. If you have any doesn’t appear to be particularly smart idea’s or opinions, just drop me an e- either. There doesn’t appear to be an mail at the address provided below! ■ overriding intelligence in the computer opponent. As a human player, I jump around the map keeping track of what Mike Michaels is doubtful that any- is going on in many sectors of the game one reads these little bios (unless they’re at once. The computer artificial intelli- looking for his e-mail address to flame him) gence doesn’t have this advantage. In and therefore chose not to write one this general, it looks like each creature has month. He may be reached via e-mail at In Blizzard Entertainment’s game, you strategize to survive. its own AI routine to determine what [email protected] or through Game its next action should be. With no Developer magazine.

58 GAME DEVELOPER • APRIL/MAY 1996 http://www.mfi.com/gdmag ARTIST‘S VIEW

Where the Sun Don’t Shine

David Sieks ame graphics used to be easy: grounds; it’s all but mandatory to include you’d put row after row of cinematic intros and cut sequences in blocky space aliens at the top everything from flight sims to fight- of the screen and a clunky fests. Since the coming of , adven- Lighting is vital to space cannon at the bottom ture games must (it is a law) try to outdo of the screen, all against a one another in visual atmosphere. When black background (because, you try to make eye-popping visuals at did I mention, this takes this demanding level, when your task is Gplace in space) and ta-dah...you got to capture an audience’s interest and spur making your 3D games game graphics. At this level, graphics its imagination, you need to make use of could routinely be handled by the pro- every tool at your disposal. grammers themselves—no need to Artists working with three-dimen- involve an artist. sional graphics now need to acknowledge Now, of course, it is a different something that photographers and cine- look realistic. Sieks matter. The visual component seems to matographers have held as a central tenet have taken precedence over game play of their art forms throughout the century and originality. (Hey, that’s not my beef: and that realist painters have practiced this is the Artist’s View, man.) The for longer still: control of a scene’s light- market demands that games of all gen- ing determines much of its impact. One res look as good as they can get, which cannot discern color or form without illu- takes us through the provides plenty of opportunity and chal- mination, but, in the context of a scene, lenge for talented artists. lighting takes on added significance. Even relatively straight-ahead Used judiciously, areas of light and dark shooters have gorgeous, rendered back- create the overall composition, direct the ins and outs of hard

and soft lighting— learn how to really set

The addition of a bouncing flashlight beam heightens the creepty tension of the 11th the mood. Hour, sequel to The 7th Guest, from Virgin Entertainment and Trilobyte Inc.

http://www.mfi.com/gdmag GAME DEVELOPER • APRIL/MAY 1996 61 ARTIST‘S VIEW

audience’s attention, and can work to cue Effect over Fact tive. Subtle finagling with additional expectations in the viewer and to under- When tackling the task of lighting a lights, diffusers, reflectors, and filters (or score the narrative. scene, one must think in terms of con- their computer graphics counterparts) Yes, 3D artists should realize the trast—that is, the juxtaposition of light still falls within this first category as long importance of lighting. It is all too easy and dark. The effect is the important as a convincing look is the intent. to focus on the obvious challenges of thing: not how many lights you place or On the other hand, expressionistic, modeling, texture mapping, and anima- where or what the logical source of such nondiegetic lighting is that which tion and pay only perfunctory notice to illumination would be, just how it all throws all pretense of realism out the looks. A common pitfall is to create window (at least for the moment) and lights in the 3D scene that are, as nearly goes purely for effect, using sometimes as possible, strictly analogous to the real- subliminal, psychological connotations There are two world light sources. Unfortunately, in of light, shadow, and color to make its the realm of 3D graphics, good lighting point: bathing a scene of violence in red isn’t as easy as flicking a switch. light or shining a heavenly light from basic approaches First, the particular characteristics above on a redeemed character. of computer graphics lights usually make Nondiegetic lighting can tend to be it necessary to work with placement, clichéd and even campy, but, used with intensity, and so on to finagle the desired restraint, can also be very effective in to lighting a effect. For example, you might need to getting a point across quickly and sure- place additional lights to simulate the ly, as most people in your audience will effects of radiosity (the dispersal and intuit the intended meaning. scene: the realistic propagation of reflected light). Or you Two basic ways of applying light to might need to situate a light somewhere a scene exist: hard and soft lighting. other than its apparent source in the Hard lighting refers to sharply defined and the expres- scene: for example, positioning a light areas of light and shadow, whereas soft outside the dimensional model of the lighting uses a more diffused light, with light fixture to avoid an unwanted hot gentler shadows and blended areas. spot (a bright, central highlight) on a Though you may not have thought sionistic, or, to nearby surface. The guiding precept about it in such, well, black and white should be to forget about what makes terms before, it’s easy to see how hard strict sense and place the light where it and soft lighting fit into the basic light- throw out a real gives the best effect. Artists are only ing styles and how they relate to the dif- constrained by reality on rent day. ferent moods or genres commonly asso- Despite the fact that they are cap- ciated with them. Low-key lighting, film-weenie term, turing images of the real world, photog- often used for scenes of mystery or sus- raphers and cinematographers (who are pense, makes use of moody, atmospheric also rent-paying artists) go to great pools of light and dark. High-key light- lengths to achieve the lighting effects ing is bright but not harsh, even illumi- the diegetic and they want. Even when the end result is nation with minimal shadows, generally intended to be perceived as realistic, they used for lighthearted subjects. And high- make use of multiple lights, reflectors, contrast lighting juxtaposes dramatic the nondiegetic. diffusers, filters, and so on. As Anthony streaks of light and shadow for a stark, Burgess notes in A Clockwork Orange, the edgy look full of tension. colors of the real world never look so real These lighting conventions are not the demands of lighting a scene whose as on the screen. ironclad rules. Of course, you don’t other components we have worked on have to use high-key lighting for a so painstakingly. To do justice to every Pick a Palette of Light lighthearted scene. They are, however, element, you need to spend equal time There are two basic approaches to light- conventions that come with baggage we on and pay equal attention to each. A ing a scene: the realistic and the expres- have carried for millennia: our ancestral careless approach to lighting, however, sionistic, or, to throw out a real film- memory tells us shadows are frighten- can negate much of the hard work put weenie term, the diegetic and the ing; you’d better be prepared to work into every other aspect by creating a nondiegetic. Diegesis refers to the narra- around that if you’re determined to use flat, dull scene—or one that looks tive, so diegetic lighting is that which, low-key lighting in the splash scene for instantly and unmistakably computer for the most part, seems consistent with The Frolicsome Pony’s Interactive generated. the setting and the action of the narra- Learning Adventure For Ages 6 to 9.

62 GAME DEVELOPER • APRIL/MAY 1996 http://www.mfi.com/gdmag ARTIST’S VIEW

Can’t Tell the Players Without a Program The hump, of course, is figuring out how to control the lighting of a scene to use contrast knowingly and to your advan- tage. Though computer artists have many challenges unique to our medium, we can still learn much by observing the tradi- tional approaches to lighting practiced by film artists. There we find not only a long, practical experience with the topic, but an established professional jargon that facilitates its discussion. The classic Hollywood approach to lighting generally involves at least three light sources—namely the key light, fill light, and backlight. Of primary impor- Thanks in large part to its moody, carefully lit 3D scenery, Myst—from Broderbund Software tance among one’s lighting tools is the and Cyan Inc.—showed the world how good-looking a game could be. key light. This is the chief light source for the scene and casts the dominant shadows. A fill light is then used to “fill sometimes fill light is set to gently illu- lights should decrease in brightness from in” or soften shadows created by the key, minate a portion of the background to key light to backlight to fill light. Do test while the backlight serves to separate the diminish a cast shadow. renders and change light levels till the figure from the background. Typically, One great advantage computer overall brightness and mix of light and each major character (or other object of artists have over film artists is their abili- dark is to your liking. You have “roughed focus) will be assigned a key, fill, and ty to use shadow casting selectively. All out the canvas,” so to speak. Now look at backlight, though often one light can 3D programs seem to have some provi- the scene with an eye to detail and really serve more than one figure. sion for turning shadows on or off, so begin to paint with light. The purpose of lights is to define that either a light doesn’t cast them or an form by painting the figure with light object doesn’t receive them. Take advan- See Spot Shine and shadow. To that end, the key light is tage of this ability. A fill light that soft- The spotlight is the lighting technician’s generally positioned so its rays strike the ens existing shadows without adding sable hair brush. Spotlights can be accu- figure diagonally from the front, near but more shadows to the scene can be a great rately aimed to illuminate objects or off to one side and typically higher than tool. Just because a real-world light areas, to highlight details and direct the the camera; this is known as “modeling would cast shadows doesn’t mean every audience’s attention. (3D Studio lets you light” because it tends to model the form light in your 3D scene has to. place a highlight where you want, then it well and be the most flattering. More A kicker or backlight—also known positions the source light accordingly.) direct, frontal lighting is to be avoided, as a rim or separation light—provides One characteristic of spotlights is falloff: as it will work to minimize shadows and depth cues by separating the figure from the extent to which the light diminishes thus flatten the appearance of form. A the background. The intensity of illumi- in intensity away from the center of the “skim” or “raking” light is a key light nation should fall between the key light beam. A light with little or no falloff that comes from an oblique angle to the and the fill lights. If there is not suffi- appears as a sharply defined circle viewpoint; that is, one set more to the cient difference in the intensities of these (assuming a circular spot), where a light side than at a diagonal. It creates strong, lights, the tonal variations will not work with greater falloff has less distinct edges long shadows and is useful for capturing well to suggest form, and the result will with a brighter center: the hot spot. A surface detail. The key light will be the be a flatter, less dimensional look. Back- tightly focused spotlight that highlights brightest in the scene and should be lighting works best when directed from a very specific area is known as an accent placed first. above and, obviously, behind the figure. light. A spot aimed so the hot spot Try a test render with just the key It can be more or less to one side or the “misses” the figure—thus achieving a less light in place. Next, place a fill light to other as preferred. intense highlight on the subject itself—is soften and deepen the shadows cast by At this point in your lighting setup, called a feathered light. the key. The fill light should be lower it is a good idea to balance the intensity You can use multiple spots of vary- than the key in intensity and is also often levels of these main lights to achieve ade- ing size and falloff to highlight and positioned lower in the scene, to light quate illumination for the scene, remem- brighten key features, but be aware of the figure from slightly underneath. Or, bering that to get a good tonal range the the amount of illumination you add to

64 GAME DEVELOPER • APRIL/MAY 1996 http://www.mfi.com/gdmag 2D transparency map used as a gobo. A a jail cell with the stripey shadows of gobo is a screen that blocks light—or, cell bars. more usefully, partially blocks light. In Your gobo can be animated, too, computer graphics terms, the gobo is which adds even more detail and depth used as a projection light: the opaque to the scene with minimal effort: it can areas cast shadows on the scene. With a be much easier to create a 2D animation gobo, it’s easy to create the appearance in silhouette than to model and animate of shadows cast by offstage objects. You a comparable scene in 3D. A 3D pro- can create the effect of dappled sunlight gram that doesn’t have projection lights through a forest canopy without having per se but that does have raytracing From guttering torches to glowing force to model a forest full of trees or suggest capability can still make use of the gobo fields, atmospheric lighting effects set the mood in Buried In Time, by Sanctuary Woods and Presto Studios. the scene. As you add more lights to your scene, you’ll want to adjust the intensity levels of existing lights so you don’t wash out details by over-illuminat- ing them. Avoid overwhelming the scene with shadows that come from all direc- tions because of the myriad lights set about. For most accenting purposes, spotlights can best be set to cast light without shadows. One interesting lighting tool com- puter artists have over film artists is the darkon, a light with a negative intensity value. By setting the intensity level below zero, the darkon’s rays in fact remove light color from areas they con- tact. In addition to a darkening effect, the darkon can force a color shift in the affected area. What it’s doing is sucking light color from everything it touches in the scene, but doing so selectively. Even white light is composed of RGB values (translated to hue, luminance, and satu- ration or HLS values); by removing more of the red channel, for example, the darkon can cause the remaining light to appear greenish. It’s a neat spe- cial effect, but it can be tricky to con- trol. If the darkon is neutral in color— that is, has a zero saturation setting—it reduces the RGB color channels evenly and has a darkening effecting without changing color.

Imitating Mother Nature Effective use of light and shadow not only helps the look of a scene, it can contribute to its narrative strength while saving the artist time and effort. A very useful tool toward this end is a

http://www.mfi.com/gdmag GAME DEVELOPER • APRIL/MAY 1996 65 ARTIST’S VIEW

technique by painting a planar object ed sunlight, avoid using attenuated light gest fire, violence, or danger, while yel- with the transparency map and position- levels—those that diminish with dis- low light is warm and welcoming. ing it in front of the light source so that tance from the source—with the possible Bluish light can be morbid and is good it casts the desired shadow. exception of a sunset effect. for suggesting nocturnal scenes. Green- The gobo technique can also be ish hues seem unnatural and are just used with subtler grey scale or color gra- What Do They Expect? plain creepy. Feathered accent hits of dations as a computer graphics analog to With these tools in your arsenal, you can colored lights in an outwardly natural the photographer’s diffuser to soften the use light and shadow to greater effect in looking lighting scheme can add a nice effect of a light or break up the evenness your scenes. Beyond making an image undercurrent of implied meaning to of its illumination. This results in a less look good, lighting gives you the oppor- your scene. rigid, more natural appearance. When tunity to play on the psychological con- Of course, these expectations can striving for realistic lighting effects— notations with which dark and light are be played with, too. You can build ten- especially for outdoor lighting—don’t be freighted. There are pretty clearly under- sion in the shadows without fulfilling it, constrained by the limits of the computer standable reasons why our primitive and you can rain horror down upon screen. The closer lights are positioned to ancestors feared the darkness, which your scene from a clear blue sky. The the objects in a scene, the more apparent have only been reinforced by the symbol- point is that, used knowingly, lighting the effect of falloff will be, and the more ic use of light and dark through the ages. effects can set your audience up just flare any cast shadows will display. In darkness lurks all that is unknown and where you want them; what you hit Because of its great distance from unsafe—dread, evil, death. By dispelling them with is up to you. ■ the Earth, sunlight produces both an darkness, light promises truth, brings even illumination and shadows we per- reassurance, and suggests virtue, happi- Dave Sieks is a contributing editor to ceive as running parallel. Simulate this ness, safety. Game Developer. You can contact via e- by placing “sun” light sources at a dis- Likewise, lighting color has signif- mail at [email protected] or tance from your scene. Also for simulat- icance as well. Orangey-red lights sug- through Game Developer magazine.

66 GAME DEVELOPER • APRIL/MAY 1996 http://www.mfi.com/gdmag