Você está na página 1de 18

1/3/2016

Lou'sPseudo3dPage

Lou'sPseudo3dPage

(C)2013LouisGorenfeld,updatedMay3,2013
NEW:Importantdetailsonthesegmentedroadsystemandsomeadditionallinks
NEW:An(optional)explanationoffindingfieldofviewforthe3dprojectionformula
NEW:AnanalysisofS.T.U.N.Runner
NEW:Generalwritingimprovements
Previousupdate:
Anexplanationof3dprojectionmathematics(underRoadBasics)andanalysisofActivision'sEnduro(underCaseStudies)!
Thankstoeveryoneforalltheemail!Keepitcoming:)Sorry,Ican'tanswerquestionsaboutwhenI'llpostsourcecode,but
I'malwayshappytoansweranythingelseabouttheseengines!
OfficialmaterialontheRoadRashgraphicsengineandmoredetailedexplanationofcurvesandageneralizedcurve
equation
Isthisinformationinaccurate?AmIwayoff?Don'thesitatetowritemeatlouis.gorenfeldatgmaildotcom!

TableofContents
Introduction
RoadBasics
CurvesandSteering
SpritesandData
Hills
TakingRasterRoadsFarther
True3dProjectedSegments
Enhancements
RelatedEffects
CaseStudies
CodeStuff
Glossary
TheGallery

Introduction
WhyPseudo3d?
Nowthateverysystemcanproducegraphicsconsistingofazillionpolygonsonthefly,whywouldyouwanttodoaroadthe
oldway?Aren'tpolygonstheexactsamething,onlybetter?Well,no.It'struethatpolygonsleadtolessdistortion,butitisthe
warpingintheseoldenginesthatgivethesurreal,exhilleratingsenseofspeedfoundinmanyprepolygongames.Thinkof
theviewasbeingcontrolledbyacamera.Asyoutakeacurveinagamewhichusesoneoftheseengines,itseemstolook
aroundthecurve.Then,astheroadstraightens,theviewstraightens.Asyougooverablindcurve,thecamerawouldseem
topeerdownovertheridge.And,sincethesegamesdonotuseatraditionaltrackformatwithperfectspatialrelationships,it
ispossibletoeffortlesslycreatetrackslargeenoughthattheplayercangoatridiculousspeedswithoutworryingaboutan
objectappearingonthetrackfasterthantheplayercanpossiblyreactsincethephysicalrealityofthegamecaneasilybe
tailoredtothegameplaystyle.
Buttheyhaveplentyofdrawbacksaswell.Thedepthofphysicsfoundinmoresimulationlikegamestendstobelost,andso
theseenginesaren'tsuitedtoeverypurpose.Theyare,however,easytoimplement,runquickly,andaregenerallyalotof
funtoplaywith!
Itisworthnotingthatnoteveryolderracinggameusedthesetechniques.Infact,themethodoutlinedhereisonlyone
possiblewaytodoapseudo3droad.Someusedprojectedandscaledsprites,othersseemtoinvolvevaryingdegreesof
realprojectionfortheroad.Howyoublendrealmathematicswithtrickeryisuptoyou.Ihopeyouhaveasmuchfun
exploringthisspecialeffectasIdid.
HowMuchMathDoINeed?
Ifyou...
...haveTrigonometryknowledge,that'sthemostmathyou'llneedfortheentiretutorial
...havejustAlgebraandGeometry,skipthefieldofviewexplanation
http://www.extentofthejam.com/pseudo/

1/18

1/3/2016

Lou'sPseudo3dPage

...wanttoavoidasmuchmathaspossible,read:TheSimplestRoad,CurvesandSteering,SpritesandData,andHills

Thisisaveryflexibletechnique,andyoucanactuallygetbywithjustaddition!Withmoreadvancedmath,itcanlookbetter,
butwithjustarithmetic,youcangetuptothelevelofdetailseeningameslikePolePositionorthefirstOutRun.
HowMuchProgrammingKnowledgeDoINeed?
Ithelpsalottounderstandrastergraphics:Knowwhatascanlineis,andthateachlineismadeofarowofpixels.The
programmingexamplesarewritteninpseudocode,soyoudon'tneedexperienceinanyspecificlanguagetounderstand
them.
Ready?Let'sbegin!
RasterEffectsSomeBackground
Apseudo3droadisjustavariationofamoregeneralclassofeffectscalledrastereffects.Oneofthebestknownexamples
ofarastereffectisinStreetFighterII:Asthefightersmoveleftandright,thegroundscrollsinperspective.Thisactuallyisn't
3d.Instead,thegroundgraphicisstoredasanextremelywideangleperspectiveshot.Whentheviewscrolls,thelinesofthe
screenwhicharesupposedtobefartherawayscrollmoreslowlythanthelineswhicharecloser.Thatis,eachlineofthe
screenscrollsindependentlyofeachother.Shownbelowisboththeendresultandthegroundgraphicasitisstoredin
memory.

RoadBasics
IntroductiontoRasterRoads
Weareusedtothinkingof3deffectsintermsofpolygonswhoseverticesaresuspendedin3dspace.Oldersystems,
however,werenotpowerfulenoughtomakealargenumberof3dcalculations.Manyoldereffects,ingeneral,fallintothe
categoryofrastereffects.Thesearespecialeffectswhicharedonebychangingsomevariableperline.Mostcommonly,this
meanschangingthecolororpaletteperline,orscrollingperline.Thisiswellsuitedtooldgraphicshardwarewhichhad
accelerationforscrollingandusedanindexedcolormode.
ThepseudorasterroadeffectactuallyworkssimilarlytotheStreetFighterIIperspectiveeffectinthatitwarpsastaticimage
tocreatetheillusionof3d.Here'showtheydoit:
Mostrasterroadsstartoffwithanimageofaflatroad.Thisisessentiallyagraphicoftwoparallellinesontheground
retreatingintothedistance.Astheygetfartherintothedistance,thelinesappeartotheviewertobeclosertogether.Thisisa
basicruleofperspective.Now,inordertogivetheillusionofmotion,mostarcaderacinggameshavestripesontheroad.
Movingthesestripesontheroadforwardsisgenerallyeitherachievedbycolorcyclingorbychangingthepaletteeveryline.
Curvesandsteeringaredonebyscrollingeachlineindependentlyofoneanother,justlikeinStreetFighterII.
Wewillgetintocurvesandsteeringinthenextchapter.Fornow,let'sputthatasideandconcentrateonmakingtheroad
appeartoscrollforwards.
TheSimplestRoad
Taketheimageofaroaddescribedabove:Twoparallellinesdemarcatingtheleftandrightedgesoftheroadretreatintothe
distance.Astheymoveintothedistance,theyappeartotheviewertobeclosertogether.Belowiswhatthismightlooklike:

Whatismissingfromthispictureareroadmarkingstogiveagoodimpressionofdistance.Gamesusealternatinglightand
darkstrips,amongotherroadmarkings,forthiseffect.Tohelpaccomplishthis,let'sdefinea"textureposition"variable.This
variablestartsatzeroatthebottomofthescreenandincreaseseachlinegoingupthescreen.Whenthisisbelowacertain
amount,theroadisdrawninoneshade.Whenitisabovethatamount,itisdrawnintheothershade.Thepositionvariable
thenwrapsbacktozerowhenitexceedsthemaximumamount,causingarepeatingpattern.
http://www.extentofthejam.com/pseudo/

2/18

1/3/2016

Lou'sPseudo3dPage

Itisnotenoughtochangethisbyasetamounteachlinethough,becausethenyou'lljustseeseveralstripsofdifferentcolors
whicharenotgettingsmallerastheroadgoesintothedistance.Thatmeansyouneedanothervariablewhichwillchangeby
asetamount,addittoanothervariableeachline,andthenaddthelastonetothetexturepositionchange.
Here'sanexamplewhichshows,fromthebottomofthescreen,whattheZvaluewillbeforeachlineasitrecedesintothe
distance.Afterthevariables,Iprintwhatisaddedtogetthevaluesforthenextline.I'venamedthevaluesDDZ(deltadelta
Z),DZ(deltaZ),andZ.DDZremainsconstant,DZchangesinalinearfashion,andZ'svaluecurves.YoucanthinkofZas
representingtheZposition,DZasholdingthevelocityoftheposition,andDDZasbeingtheaccelerationoftheposition(the
changeinacceleration).NotethatthevalueIchose,four,isarbitraryandwasjustconvinientforthisexample.
DDZ=4DZ=0Z=0:dz+=4,z+=4
DDZ=4DZ=4Z=4:dz+=4,z+=8
DDZ=4DZ=8Z=12:dz+=4,z+=12
DDZ=4DZ=12Z=24:dz+=4,z+=16
DDZ=4DZ=16Z=40:etc...

NoicethatDZismodifiedfirst,andthenthatisusedtomodifyZ.Tosumitup,sayyouaremovingthroughthetextureat
speed4.Thatmeansthatafterlineone,youarereadingthetextureatposition4.Thenextlinewillbe12.Afterthat,24.So,
thiswayitreadsthroughthetexturefasterandfaster.ThisiswhyIliketorefertothesevariablesasthetextureposition
(whereinthetexturewearereading),thetexturespeed(howquicklywereadthroughthetexture),andthetexture
acceleration(howquicklythetexturespeedincreases).
Asimilarmethodwillalsobeusedtodrawcurvesandhillswithouttoomuchnumbercrunching.Now,tomaketheroad
appeartomove,justchangewherethetexturepositionstartsatthebottomofthescreenforeachframe.
Now,youmaynoticeashortcomingwiththistrick:thezoomingrateisinaccurate.ThiscausesadistortionthatIwillreferto
asthe"oatmealeffect".ItisawarpingeffectpresentinearlypseudogamessuchasOutRuninwhichobjects,includingthe
stripesontheroad,appeartoslowdownastheymoveoutwardsfromthecenterofthescreen.
ThismethodforfindingtheZvaluehasanotherdisadvantage:It'snoteasilypredictablewhatthevalueisinthevery
distance,especiallywhenhillsareinvolved.WewilllearnamoreadvancedmethodwhichIwillcalltheZmap.Thisisatable
thatcalculateswhattheZdistanceisforeveryscanlineofthescreen.Butfirst,weneedalittlemoremath...
AMathematicalDetour:3dPerspectiveProjection
Therearewaystogetridoftheoatmealeffect.However,sometraditional3dmathematicsareneededtomakethem
possible.Whatweneedisawayoftranslating3dcoordinatessothattheyfitontoa2dsurface.

Inthepictureabove,aneyeball(lowerleft)islookingthroughthescreen(theblueverticalline)atanobjectinour3dworld
("y_world").Theeyeballisadistance"dist"fromthescreen,andadistance"z_world"fromtheobject.Now,onethingyou
mighthavenoticedifyou'vespentsometimewithgeometryortrigonometryisthattherearenotonebuttwotrianglesinthe
picture.Thefirsttriangleisthelargestone,fromtheeyeballovertothegroundontherightsideanduptotheobjectwe're
lookingat.ThesecondtriangleI'vecoloredyellow.Thisisfromtheeyeballtowhereonthescreenwe'llseeourobject,down
totheground,andback.
Thesetwotriangles'hypoteneuses(thelinefromtheeyetotheobject)areatthesameangleeventhoughoneislongerthan
theother.Theyareessentiallythesametriangle,butthesmalleroneisjustscaleddown.Whatthisimpliesisthattheratioof
thehorizontalandverticalsidesmustbethesame!Inmathterms:
y_screen/dist=y_world/z_world

Whatweneedtodonowisjuggletheequationtogety_screen.Thisgivesus:
y_screen=(y_world*dist)/z_world

Insummary,tofindtheycoordinateofanobjectonthescreen,wetaketheyworldcoordinate,multiplythatbythedistance
wearetothescreen,andthendivideitbythedistanceitisintheworld.Ofcourse,ifwejustdothat,thecenterofourviewis
goingtobetheupperleftcornerofthescreen!Justpluginy_world=0toseethis.Whatwecandotocenteritisaddhalfof
ourscreenresolutiontotheresulttoputitrightinthemiddle.Theequationcanalsobesimplifiedalittlebitbypretendingthat
ournosesarerightuptothescreen.Inthiscase,dist=1.Thefinalequationthenis:
y_screen=(y_world/z_world)+(y_resolution/2)

Thereisarelationshipbetweentheratiosandtheviewingangle,aswellasscalingtheimagesothatitisresolutionneutral,
butwewon'treallyneedanyofthattofixourroadproblem.Ifyouarecurious,trylookingatthediagramfromthetopview:
theangletotheedgeofthescreenisthefieldofviewandthesamerelationshipshold!
MoreMath:AddingFieldofViewto3dProjection
Now,thisislargelyunnecessaryformostroadenginecases.But,it'susefulformakingprojectionparametersresolution
independent,orforobjectsthatneedtorotateorforintegrationwithtrue3deffects.
http://www.extentofthejam.com/pseudo/

3/18

1/3/2016

Lou'sPseudo3dPage

Let'sgobacktotheoriginalprojectionformula.The"dist"fromtheexplanationabovewillnowbecalled"scaling":
y_screen=(y_world*scaling)/z_world+(y_resolution/2)

Theideaisthatweneedtoscaleallthepointsonthescreenbysomevaluewhichletspointswithinacertainfieldofview
(FOV)remainvisible.You'llneedaconstantforthexFOVandaconstantfortheyFOV.
Asanexample,let'sassumewe'reworkingin640x480resolutionandwewantaFOVof60degrees.We'veseenadiagram
of3dprojectionfromthesideview.Forthis,let'slookatthistopviewoftheprojectionspaceinstead:

OnewaytothinkabouttheproblemisthatifanobjectisattherightedgeofourFOV,itneedstoappearonthescreenat
x=640(sincewe'reat640x480).Lookingatthechart,ourFOVcanbesplitintotworighttriangleswheretheangleofeachis
fov_angle/2(a/2).AndsinceourFOVisacone,anobjectisontherightedgeofitsFOVifitsx=R*sin(a/2)andz=R*cos(a/2),
whereRisanyradiusvaluewewant.WemightaswellmakeR=1.Andweneedtheobjecttoappearatx_screen=640.That
givesusthis(startingfromthebasicprojectionformula):
x_screen=640fov_angle=60y_world=sin(60/2)z_world=(60/2)x_resolution/2=320scaling=?
x_screen=(y_world*scaling)/z_world+(x_resolution/2)
640=(sin(30)*scaling/cos(30))+320
320=tan(30)*scaling
320/tan(30)=scaling
Ingenericterms:scaling=(x_resolution/2)/tan(fov_angle/2)

We'vereplaceda/2by30(halfof60degrees),recognizedthatsin/cos=tan,andvoila!Weshouldbeabletotestthisby
placinganobjectattherightedgeofthefieldofview,pluggingthesevaluesintotheoriginalprojectionequation,and
ensuringthattheXvaluewindsupas640.Forexample,an(x,z)pointat(20,34.64)willwindupatX=640because20is
40*sin(30)and34.64is40*cos(30).
Notethatyou'llhavedifferentFOVvaluesforhorizontal(x)andvertical(y)forastandardorwidescreenmonitorthat'sin
horizontalorientation.
AMoreAccurateRoadUsingaZMap
Whatwewanttodotofixourperspectiveproblemistoprecomputealistofdistancesforeachlineofthescreen.Inshort,
theproblemishowtodescribeaflatplanein3d.Tounderstandhowthisworks,firstthinkofthe2dequivalent:aline!To
describeahorizontallinein2d,youwouldsaythatforevery(x,y)coordinatetheyisthesame.Ifweextendthisinto3d,it
becomesaplane:foreveryxandzdistance,theyisthesame!Whenitcomestoaflathorizontalsurface,itdoesn'tmatter
howfarfromthecameraitis,theyisalwaysthesame.Likewise,itdoesn'tmatterhowmuchtotheleftorrightthepointis,
theywillstillbethesame.Backtofiguringoutthedistanceofeachlineofthescreen:let'scallthisaZMap.Calculatingthe
ZMapisjustamatterofrearrangingthe3dprojectionformulatofindaZvalueforeachscreenY!
First,taketheequationfromthelastsection:
Y_screen=(Y_world/Z)+(y_resolution/2)

Now,sincewe'regivenY_screen(eachline),juggletheequationsothatwe'refindingtheZ:
Z=Y_world/(Y_screen(height_screen/2))

Y_worldisbasicallythedifferencebetweenthegroundandthecameraheight,whichisgoingtobenegative.Thisisthe
sameforeachlinebecause,asdescribedintheintroductoryparagraph,we'reinterestedinaflatroadforthetimebeing.In
additiontolookingmuchmoreaccurateandavoidingthe"oatmealeffect",ithastheadvantagethatitiseasytocompute
whatthemaximumdrawdistanceis.
Theroadismappedontothescreenbyreadingthroughthisbuffer:Foreachdistance,youmustfigureoutwhatpartofthe
roadtexturebelongstherebynotinghowmanyunitseachstripeorpixelofthetexturetakeup.
Thoughwenowknowthedistanceofeachrowofthescreen,itmayalsobeusefultocacheeitherthewidthoftheroador
scalefactorforeachline.Thescalingfactorwouldjustbetheinverseofthedistance,adjustedsothatthevalueis1onthe
linewhichtheplayer'scargraphicspendsthemosttime.Thiscanthenbeusedtoscalespriteswhichareonagivenline,or
tofindwhatthewidthoftheroadis.

CurvesandSteering
MakingitCurve
Tocurvearoad,youjustneedtochangethepositionofthecenterlineinacurveshape.Thereareacouplewaystodothis.
OnewayistodoitthewaytheZpositionsweredonein"TheSimplestRoad":withthreevariables.Thatis,startingatthe
bottomofthescreen,theamountthatthecenteroftheroadshiftsleftorrightperlinesteadilyincreases.Likewiththetexture
reads,wecanrefertothesevariablesasthecenterline(curve)position,thecurvevelocity,andthecurveacceleration.
Therearesomeproblemswiththismethodthough.OneisthatScurvesarenotveryconvinient.Anotherlimitationthatgoing
intoaturnlooksthesameascomingoutofaturn:Theroadbends,andsimplyunbends.
http://www.extentofthejam.com/pseudo/

4/18

1/3/2016

Lou'sPseudo3dPage

Toimprovethesituation,we'llintroducetheideaofroadsegments.Aroadsegmentisapartitionwhichisinvisibletothe
player.Thinkofitasaninvisiblehorizontaldividewhichsetsthecurveoftheroadabovethatline.Atanygiventime,oneof
thesesegmentdividersisatthebottomofthescreenandanotheristravellingdownatasteadyratetowardsthebottomof
thescreen.Let'scalltheoneatthebottomthebasesegment,becauseitsetstheinitialcurveoftheroad.Here'showit
works:
Whenwestartdrawingtheroad,thefirstthingwedoislookatthebasepointandsettheparametersfordrawing
accordingly.Asaturnapproaches,thesegmentlineforthatwouldstartinthedistanceandcometowardstheplayerkindof
likeanyotherroadobject,exceptitneedstodriftdownthescreenatasteadyrate.Thatis,foraspecificspeedthatthe
playeristraveling,thesegmentdividertravelsdownthescreenatsomanylinesperframe.Or,ifyou'reusingaZMap,so
manyzmapentriesperframe.Ifthesegmentwereto'accelerate'attheplayertheway3dobjectsonthetrackdo,theroad
wouldswingtoowildly.
Let'sseehowthisworks.Supposethesegmentlineforaleftcurveishalfwaydowntheroadandthebasesegmentisjusta
straightroad.Astheroadisdrawn,itdoesn'tevenstartcurvinguntilithitsthe"leftcurve"segment.Thenthecurveofthe
roadbeginstochangeattheratespecifiedbythatpoint.Asthemovingsegmenthitsthebottomofthescreen,itbecomes
thenewbasesegmentandwhatwaspreviouslythebasesegmentgoestothetopoftheroad.
Shownbelowaretworoads:Oneisastraightawayfollowedbyaleftturn,andoneisaleftturnfollowedbyastraightaway.In
boththesecases,thesegmentpositionishalfwaydowntheZMap(or,halfwaydownthescreen).Inotherwords,theroad
beginstocurveorstraightenhalfwaydowntheroad,andthecameraisenteringtheturninthefirstpictureandleavingthe
turninthesecond.

AndthisisthesametechniqueandsamesegmentpositionappliedtoanScurve:

ThebestwaytokeeptrackofthesegmentpositionisintermsofwhereontheZMapitis.Thatis,insteadoftyingthe
segmentpositiontoascreenyposition,tieittoapositionintheZMap.Thisway,itwillstillstartattheroad'shorizon,butwill
moregracefullybeabletohandlehills.Notethatonaflatroadthatthetwomethodsoftrackingthesegmentpositionare
equivalent.
Let'sillustratethiswithsomecode:
current_x=160//Halfofa320widthscreen
dx=0//Curveamount,constantpersegment
ddx=0//Curveamount,changesperline
foreachlineofthescreenfromthebottomtothetop:
iflineofscreen'sZMappositionisbelowsegment.position:
dx=bottom_segment.dx
elseiflineofscreen'sZMappositionisabovesegment.position:
dx=segment.dx
endif
ddx+=dx
current_x+=ddx
this_line.x=current_x
endfor
//Movesegments
segment_y+=constant*speed//Constantmakessurethesegmentdoesn'tmovetoofast
ifsegment.position<0//0isnearest
bottom_segment=segment
segment.position=zmap.length1//Sendsegmentpositiontofarthestdistance
segment.dx=GetNextDxFromTrack()//Fetchnextcurveamountfromtrackdata
endif

Onebigadvantageofdoingthecurvesthiswayisthatifyouhaveacurvefollowedbyastraightaway,youcanseethe
straightawayasyoucomeoutofthecurve.Likewise,ifyouhaveacurvefollowedbyacurveintheoppositedirection(or
evenasteepercurvethesamedirection),youcanseethatnextpieceoftrackcomingaroundthebendbeforeyouhitit.
Tocompletetheillusion,youneedtohaveahorizongraphic.Asthecurveapproaches,thehorizondoesn'tchange(or
scrollsonlyslightly).Thenwhenthecurveiscompletelydrawn,itisassumedthatthecarisgoingaroundit,andthehorizon
scrollsquicklyintheoppositedirectionthatthecurveispointing.Asthecurvestraightensoutagain,thebackground
http://www.extentofthejam.com/pseudo/

5/18

1/3/2016

Lou'sPseudo3dPage

continuestoscrolluntilthecurveiscomplete.Ifyouareusingsegments,youcanjustscrollthehorizonaccordingtothe
settingsonthebasesegment.
GeneralCurveFormula
Thereisoneinterestingobservationwecanmakeaboutthecurvetechniquedetailedinthesection"TheSimplestRoad".
Thisobservationismoremathematicalthantheabovematerial,andcanbesafelyskippedaslongasyourgraphicsengine
eitherdoesnothavetoberesolutionindependentorisusingthe"3dprojectedsegments"techniquediscussedinthechapter
onhills.
Lookingatthecurveexampleusing"Z"fromthesection"TheSimplestRoad",wecanseethatthezposition(orxposition)
atagivenlineisthesumofanincreasingseriesofnumbers(e.g.1+2+3+4).Thisiswhat'scalledanarithmeticseries,or
anarithmeticprogression.Insteadof1+2+3+4,asharpercurvecanbeproducedbyadding2+4+6+8,or2*1+2*2+
2*3+2*4.The"2"inthiscaseisthevariablesegment.dxfromabove.Itcanalsobefactoredouttoget2(1+2+3+4)!Now
allthathastobedoneistofindaformulatodescribe1+2+...+N,whereNisthenumberoflinesmakingupthecurve.It
turnsoutthatthesumofanarithmeticseriesisequaltoN(N+1)/2.So,theformulacanbewrittenass=A*[N(N+1)/2]
whereAisthesharpnessofthecurveandsisthesum.Thiscanbefurthermodifiedtoaddastartingpoint,forinstance,the
centeroftheroadatthebottomofthescreen.Ifwecallthis'x',wenowhaves=x+A*[N(N+1)/2].
Wenowhaveaformulatodescribeourcurve.Thequestionthatwewanttoaskitis,"givenastartingpointxandNlinesof
thecurve,whatshouldAbetomakethecurvereachxposition's'bytheend?"JugglingtheequationtosolveforAgetsusA
=2(sx)/[n(n+1)].Thismeansthatthesharpnessofagivencurvemaybestoredintermsoftheendpoint'sXposition,
makingthegraphicsengineresolutionindependent.
PerspectivestyleSteering
It'smuchlessinterestinglookingtohaveagameinwhichwhenyousteer,itonlymovesthecarsprite.So,insteadofmoving
theplayer'scarsprite,youkeepitinthecenterofthescreenandmovetheroadmoreimportantly,youmovethepositionof
thecenterlineatthefront(bottom)ofthescreen.Now,youwanttoassumethattheplayerisgoingtobelookingattheroad
always,somaketheroadendatthecenterofthescreen.You'llneedanangleofroadvariableforthis.So,calculatethe
differencebetweenthecenterofthescreenandthepositionofthefrontoftheroad,anddividebytheheightoftheroad's
graphic.Thatwillgiveyoutheamounttomovethecenteroftheroadeachline.

SpritesandData
PlacingObjectsandScaling
Spritesshouldbedrawnbacktofront.ThisissometimesreferredtoasthePainter'sAlgorithm.Todothis,you'llhavetonote
inadvancewhereonthescreeneachobjectshouldbedrawn,andthendrawtheminadifferentstep.ThewayIdothisisas
follows:AsIgothroughtheZMapwhiledrawingtheroad,Iliketoalsonoteatthattimewhichlineofthescreeneachsprite
willbeassociatedwith.Ifyou'vekeptyourspritessortedbyZ,thisistrivial:EachtimeanewZMapvalueisread,checkto
seewhetherthenextsprite'sZpositionisclosertothecamerathanthecurrentZMapvalue,orwhetherit'sequal.Ifso,note
thatsprite'sscreenYpositionasbelongingtothecurrentline.Thencheckthenextspritethesameway.Keepdoingthisuntil
youtakeaspriteoffthelistwhichhasafartherZpositionthanthecurrentone.
TheXpositionoftheobjectshouldbekepttrackofrelativetothecenteroftheroad.Theeasiestwaythentopositionthe
spritehorizontallyisjusttomultiplyitbythescalingfactorforthecurrentline(inverseofZ)andaddthattotheroad'scenter.
StoringTrackData
WhenIdidmyfirstroaddemo,Istoredthelevelinformationasalistofeventswhichwouldhappenatspecifieddistances.
Thedistancesare,ofcourse,intermsoftexturepositionunits.Theeventswouldconsistofcommandstobeginandstop
curves.Now,asfarasIcantell,thespeedatwhichtheroadstartsandstopscurvingisarbitrary.Theonlyruleseemstobe
thatitmustcorrelatetothespeedoftheplayervehicle.
If,however,youareusingasegmentedsystem,youcanjustusealistofcommands.Thedistancethateachcommandtakes
isequivalenttohowquicklytheinvisiblesegmentlinedriftsdownthescreen.Thisalsofreesyouuptocreateatrackformat
whichworksonatilemap,forrepresentingsomewhatrealistictrackgeography.Thatis,eachtilecouldbeonesegment.A
sharpturncouldturnthetrack90degrees,whileamoremildturnwouldcomeoutat45degrees.
TexturingtheRoad
Now,youprobablywouldlikearealgraphicaltextureonyourroadinsteadofthealternatinglinesandsuchthatyouhaveat
themoment.Thereareacouplewaystodothis.Acheapandeasywaytodoitisthis:Youhaveacoupleoftexturesforthe
road(forthealternatinglineeffect).Wheneachhorizontallineoftheroadisdrawn,youstretchthetexturetofitthewidthof
thatline.Or,ifyoucan'tstretch,pickalineoutofoneoftwocompleteroadbitmaps(alaOutrunners).
Ifyouwanttheroadtolookmoreaccurate,maketheZforeachlinecorrespondtoarownumberonatexturegraphic.Voila!
Onetexturedroad!
However,ifyouonlywantstripsofalternatingcolor,theanswerisevensimplerespeciallywhenusingfixedpoint.Foreach
Z,makeoneofthebitsrepresenttheshadeoftheroad(darkorlight).Then,justdrawtheappropriateroadpatternorcolors
forthatbit.

Hills
VarietiesofHills
Itseemsthereareanearinfinitenumberofwaystoproducehilleffects.Hilleffectshaveawiderangeofgeometric
accuracy,withsomeofthelessaccuratetechniquesbeingmoreconvincingthanothers.Herewewillexaminetwopossible
methods.
FakedHills
Aftermuchexperimentation,I'vecomeupwithaflexiblemethodforfakinghillswhichuseslittleinthewayofcalculations.
Additionally,itaccuratelytracksobjectswhicharebeneaththehorizon.Itisascalingandwarpingeffectwhichvertically
http://www.extentofthejam.com/pseudo/

6/18

1/3/2016

Lou'sPseudo3dPage

stretchesandcompressestheroad.Itusesthesameadditiontrickusedtodrawthecurvestogeneratethecurvatureofthe
hill.
Here'showit'sdone:Firstofall,thedrawingloopwouldstartatthebeginningoftheZMap(nearest)andstopwhenitgetsto
theend(farthest).Ifwearetodecrementthedrawingpositioneachlineby1,theroadwillbedrawnflat.However,ifwe
decrementthedrawingpositioneachlineby2,doublinglinesaswego,theroadwillbedrawntwiceashigh.Finally,by
varyingtheamountwedecrementthedrawingpositioneachline,wecandrawahillwhichstartsflatandcurvesupwards.If
thenextdrawingpositionismorethanonelinefromthecurrentdrawingposition,thecurrentZMaplineisrepeateduntilwe
getthere,producingascalingeffect.
Downhillsaresimilar:Ifthedrawingpositionisincrementedinsteadofdecremented,itwillmovebeneaththelastlinedrawn.
Ofcourse,lineswhicharebelowthehorizonwillnotbevisibleonscreenonlylineswhichare1ormorepixelsabovethe
lastlineshouldbedrawn.However,we'llstillwanttokeeptrackofobjectswhicharebeneaththehorizon.Todothis,note
thescreenYpositionofeachspriteastheZMapistraversed.ItmayhelptomaketheZMaplargerthanneededforaflat
road.Thisway,asthebufferstretches,itwon'tbecometoopixellated.
Now,wehavetomovethehorizontoconvincetheplayer.IliketouseaLotusstylebackgroundinwhichthehorizondoesn't
justconsistofjustaskyline,butalsoadistantgroundgraphic.Whenthehillcurvesupwards(elongatingtheview),the
horizonshouldmovedownwardsslightlyrelativetothetopoftheroad.Whenthehillcurvesdownwardsasthecameracrests
thehill(shorteningtheview),thehorizonshouldmoveupwards.
Thisiswhattheeffectlookslikeforadownhillandanuphillminusthehorizongraphicofcourse:

Pros
Inexpensiveintermsofcalculations:Nomultipliesordividesnecessary
Objectsonthebacksideofthehillaretracked
Theview'sangleappearstofollowtheplayeroverhills
Cons
Accurate3dgeometryisimpossible
Tweakingisrequiredtocreateaconvincingeffect

Wrapup:TakingRasterRoadsFarther
Theseaccumulationstylecurveformulascanbeusedverbatimifyoudon'tneedcrazycurvesorhuge,rollinghills.Many
gameswhichusethesekindsoftricksscrolltheroadsofastthatevenaslightcurvecanbeconvincing.
However,youmaywanttoexaggeratetheeffectinordertogetamoredramaticroad.Onethingthatcanbedonewithanyof
thesecurveformulasistousehighddxorddyvalues,butnotallowdxordytoexceedasanevalue.Andauseron
YouTube,Foppygames,hasdiscoveredanothertrickforgettingmoreseverecurvesoutoftheseaccumulationformulas:
multiplythedxordyvaluebythezvalueforeachline!Thismakesthecurvemoresevereinthedistancethanitisinthe
foreground,anditcreatesaprettyconvincingeffect.
And,theexperimentationdoesn'tstopthere.Infact,thebestthingabouttheseenginesisthatthere'sno"right"wayofdoing
it.Anythingthatcreatescurvesandwarpagewhichispleasingtotheeyeisallowed!Inmyearliestroadengines,Iuseda
sinewavelookuptabletobendtheroad.
Youcanalsousemultiplication:Toshifttheroadright,youmightmultiplythexpositionby,forexample,1.01eachline.To
moveitleftthesameamount,you'dmultiplyitby0.99,or1/1.01(reciprocalof1.01).However,armedwiththeknowledge
thatmanyoldprocessorsdidnothavemultiplicationorwereslowatit,Isettleduponusingtheaccumulationtechnique
becauseitonlyusesaddition.Itseemedthemostlikley"authentic"wayofcurvingtheroad.
Somegames,likeOutRun,evenuseasimplesplinesystematleastjudgingbythegreatreverseengineeredopensource
C++port,Cannonball.
So,playaroundandexperiment,andseewhattechniqueyoulikebest!
...or,readonforadescriptionofaclevertrickthatmixes3dpolygons,isnearlyasfast,isevenmoreconvincing,andcanbe
displayedwiththesameoldschoolrasterhardware.Intrigued?

True3dProjectedSegments
http://www.extentofthejam.com/pseudo/

7/18

1/3/2016

Lou'sPseudo3dPage

3dProjectedSegmentsvs.RasterRoads
Asniceasrasterroadsare,theycanbemadeevenmoreimpressivebyinvolvingasimpleformofpolygonrendering.This
formofrenderingcanactuallybepulledoffusingthesamelimitedrasterhardware.However,itinvolvesmorecalculations.
ThistrickisknowntohavebeenusedingamessuchasRoadRashandTestDriveII:TheDuel.Here'swhatitis:Thetrack
ismadeofpolygonalsegments.However,ratherthanmovinginfull3dspace,itstillonlymovestowardsthecamera.For
curves,theroadstilljustskewsleftandrightinalmostanidenticalwaytotherasterroad:Thereisnoactualrotationwhen
goingaroundcurvesastherewouldbeinafullpolygonalengine.
Here'sarundown:
Sincewearestillfakingcurvesandroadangles,thatmeansexpensiverotationcalculationsstillwon'tbeneeded
Theroadisessentiallyastripofquads:eachsectionoftheroadisattachedtothenextsection.Thismeanswecan
calculatewhetherpartoftheroadisvisibleornotbasedsolelyonitsscreenYpositionrelativetoitspreviousneighbor.
Therelationshipofthesequadstooneanotherwillneverchange.Thatis,theangleneveractuallychanges,sothe
quadsarealwaysandautomaticallysortedbyZ.
TheBasic3dRoad
First,breaktheroadintopolygonalquads.Eachofthesewillbecalledasegment.Justlikeasegmentinapurelyrasterroad,
eachsegmentherestillhasacurveamount(ddx),andeitherahillamount(ddy)oraypositionthatdetermineshowhighup
itis.Ofcourse,thesecanalsohaveotherattributesaswellsuchasterrainchanges.
Picturedbelowisasegmentedroadmadeofveryfewpolygonssowecaneasilyseetheboundariesbetweenthesegments
andhowitaffectsthecurvatureoftheroad:

Whenrendering,firstfindthescreenylocationofeach3dsegmentbyusingthescreen_y=world_y/zformula.Or,ifdivision
istooslow,youcouldfindtheheightoffthegroundofagivensegmentbymultiplyingthesegment'sheightbythescaling
factorforthatline.Thatcouldthenbesubtractedthatfromareversezmap(thismapwouldbe:foreveryzpositionofaflat
road,whatisthey?)tofindthefinalpositiononscreen.
Then,youwouldlinearlyinterpolatetheroadwidthsandtexture(ifdesired)betweentheseheights.Decidingwhich3d
segmentstodrawandwhichnottocanbedeterminedeasily:Fromthefrontofthescreenback,a3dsegmentwhose
screen_yisprojectedaslowerthanthelastdrawn3dsegmentwouldnotbeshown(however,itsspritesmaystillbevisible
becausetheystickupkeepthatinmind).
ScrollingtheRoad
Now,wealsoneedtolearnhowtoscrollthesesegments.Movetheentiremessofpolygonswhichmakeuptheroad
towardsthecamera.Asthefrontmostsegment'spolygonpassesthroughthecamera,movetheentireroadbacktoits
startingpointsothatitloops.Thisisakintohowascolling2dtilefieldcanbemadebyscrollinguptoonetileworth,and
whenthatishitallthetilesareshiftedoverandnewtilemapdataispulledin.Inthis,wescrolluptoonesegmentworth,and
whenthatishit,wemovetheroadbackandpullinnewroaddata.
Butthereisonelastveryimportantdetail:Let'ssaytheroadisasharpcurve.Youmighthavenoticedthatasyougoaround
thispolygonalcurvethatitjittersasyoucrossthesegmentboundaryandtheroadissubsequentlyreset.Oneobviousthing
thatishappeningtocausethisisthatasyoutraverseaskewedsegment,thecamera'scenterrelativetotheroadchanges.
Thatis,bythetimeyougettotheendofthatsegment,theroadisnolongercentered.It'sasifyou'redrivingontheroadat
anangle.Youmightbetemptedtofixitbymovingtheroadtocenteritjustasobjects'xpositionsarelinearlyinterpolated.
However,thisiswronganddoesnotcompletelysolveourproblem:Iftheroadwereskewedinastraightline,thiswouldbe
fine.Theproblemisthatourroadcurves,sothepolygonsinthedistancestillarenotlinedup!Anotherwaytothinkaboutitis
this:Weareapproximatingacurveusingpolygonalsegments.Wewanttheshapeofthecurvetobemoreorlessconstant
evenasitscrolls.
Jakeoveratcodeincomplete.comhasagreatsolutionforthis.Insteadofchangingthexpositionastheroadasyoumove
acrossthesegment,whataboutchangingtheinitialdxvaluefrom0tosomethingthatkeepstheroadinlineasyoumove
throughthesegment?Theformulausedisthis:
dx=percentage_of_segment_traversed*ddx

Thepercentageofthesegmenthastogofrom0to1.0andbackasthecameracrossesthesegments.
Inmathematicalterms,doingthismakestheXoftheroadafunctionofitsZ.Inotherterms,we'rekeepingthecurvethe
sameshaperegardlessofhowthepointswhichapproximateitscroll.Thefrontmostsegmentis"pulledintoposition"withthe
restoftheroad,whichthenmeansthatthesubsequentsegments'Xpositionareplacedcorrectly.Youcanseethisclearlyif
youtestitwitharoadmadeoffewpolygons.Itsolvesthefollowingproblemsasthesegmentistraversed(assumingthe
curve'sshapedoesnotchange):
Itkeepsthecenteroftheroad(xposition)constant
http://www.extentofthejam.com/pseudo/

8/18

1/3/2016

Lou'sPseudo3dPage

Itadjustsdxsothatthenextsegmentstartsatanappropriatexlocationregardlessofthescrollpositionoftheroad
Thisvideodemonstratesthetechnique.I'veusedveryfewsegmentsandaverysharpcurvetodemonstratehowthislooks.
Noticethatasthepolygonsmovetowardstheplayerthattheycarveoutaperfectcurveshape.Thisismostapparentifyou
watchtherightsideoftheroad.

Pseudo 3d Segmented Road: Well-beh...

PlacingSprites
Thespritesonthat3dsegmentwouldstillneedtobeshownandproperlycropped,howeverassumingyou'remakinga
customrendererandnotusingaZbuffer.Wecanactuallydrawthespritesasthelaststep:Ifaspriteisonasegmentwhich
iscompletelyvisible,itdoesnotneedtobecroppedsinceitsticksstraightupfromtheground,whichisouronlypolygon.
Butifaspriteisonasegmentwhichiseithernotvisibleorpartiallyvisible,wecaneasilycropit.First,findthetopofthe
sprite.Then,everylineofthespritewillbedrawnuntilithitsthelastvisiblesegment'sscreenYposition.Thatis,ifthereisa
segmentbehindthespritewhichissupposedtocoverpartofit,youstopdrawingthespritewhenyouhitthatline.Andifthe
topofthespriteisbelowthelastsegment'sYposition,thespritewon'tbevisibleatallandwillbeskipped.
VariationsandRenderingTechnologies
Now,sincewe'rethrowingaroundthetermpolygon,youmaybetemptedtothinkthatyouneedpolygonalrenderingroutines
topullthisoff.UsingtechnologieslikeOpenGLorasimpletrapezoidaldrawingroutinedefinitelydowork.Buteventileand
spritebased2dhardwareareperfectlycapableofpullingthisoff.
Observethateachroadsegment'sbeginningandendareperfectlyhorizontal.Thismeansthattheyalwaysstartandendon
aspecificscanline.Muchthewaythepurelypseudo3droadisrenderedontilehardwarebyscrollingtheflatroadgraphicas
it'sbeingdrawn,wecandoexactlythesamewiththese3dsegments.Forfurtherreading,checkoutthesectioncalled
DedicatedRoadHardware.Thoughitdiscussesarcadehardwaredesignedfromscratchtodrawroadeffects,thesame
techniquecanbeachievedwithbasic2dspritetilesystemsthroughscrollingtheroadgraphicverticallyaswellas
horizontally.
FurtherReadingon3dProjectedSegments
Sincemymockupofthisspecificvariationisunderdeveloped,IwillpointyoutoCodeinComplete'samazingtutorialifyou're
interestedinfurtherdetailsonthistechnique.
Pros
Real3dgeometrycanbeusedforthehills,addinggreatlytotheamountofdetailpossible
Thesystemismoreconsistent:Terrainandroadwidthchangesdon'tneedtobedoneusingaseparatetechnique
Cons
Therearemorecalculationsinvolved
Adecentnumberofsegmentsmustbeusedortheroadwilllookjaggedandpolygonal

Enhancements
MultipleRoads
Mostarcaderacinggameshandlemultipleroadsatatime.Thoughthemostobviousreasontodothisistohavemorethan
oneroadonthescreenatatime,othereffectscanbeachievedaswell.Forexample,OutRunusesmorethanoneroadto
formitssixlanefreeway.Thisletsthegamewidenandnarrowtheroadeasily,aswellasconvincinglyfork.Theydothisby
overlappingthetworoadsandgivingonedrawingpriorityovertheother.HereisthefamiliarbeginningofOutRunbothwith
andwithouttworoads(looktotherightofthebushes):

And,evenmoredramatic,belowisthefreewayafterthetworoadsareoverlappedtoformsixlanes,bothwithandwithout
http://www.extentofthejam.com/pseudo/

9/18

1/3/2016

Lou'sPseudo3dPage

thesecondroad:

RelatedEffects
EndlessCheckerboard
TheendlesscheckerboardinthearcadegameSpaceHarrierisjustavariationontheroadtechnique.Likearoad,thegame
containsgraphicsoflinescomingattheplayerinperspective.Infact,SpaceHarrierusesthesamehardwareasHangOn.
PicturedbelowistheSpaceHarriercheckerboardeffectwithandwithoutthepalettechanges.Toturnthisintoa
checkerboard,allthathastobedoneistoflipthecolorpaletteeveryfewlines.Thinkofitasanalogoustothelightanddark
stripsonaroad.

So,howthendoesitscrollleftandright?Thisisjustavariationonperspectivestylesteering:Astheplayermovestotheleft
orright,thegroundgraphicisskewed.Afterafewpixelshavescrolledpast,theground"resets"or"wraps"itsposition.This
ishowitappearstoscrollendlesslytotheleftandright.

CaseStudies
DedicatedRoadHardware
Althoughtherearemanywaystorenderroads,itisinterestingtonotethatmanyarcadegamesusedhardwaredesignedfor
thisspecificpurpose.Thesechipsautomatethebasicsofroaddrawing,butnottheroadcalculationsthemselves.Asa
typicalexample,IwilltakeSega'sOutRunroadchip,usedingamessuchasSuperHangon,OutrunandSpaceHarrier.
Firstoff,thechiphasitsowngraphicsmemory.WhatisstoredinthisroadROMisnearlyaperspectiveviewoftheroad,
giventhatitisflat,centered,andnotcurving.Then,foreachlineofthescreen,theprogrammerspecifiesroughlywhichline
oftheperspectivegraphictodrawthere.EachlinealsohasanXoffset(forcurvingtheroad)andeachlinecanalsohavea
differentcolorpalette(todrawroadmarkingsandsimulatemovement).Toshowanexample,herearesomeimagestaken
fromSegaracinggameroadgraphicssidebysidewiththeroadasseeningame(specialthankstoCharlesMacDonaldfor
hisroadviewingapplication):

http://www.extentofthejam.com/pseudo/

10/18

1/3/2016

Lou'sPseudo3dPage

Thefirstthingyoumightnoticeisthattheroadgraphicsaremuchhigherresolutionthantheingamegraphics.Inthese
particulargames,theroadisupto512x256resolutionwhilethegame'sdisplayresolutionisonly320x224.Thisgivesthe
graphicsengineplentyofgraphictoplaywith,whichcutsdownontheamountofjaggies.Anotherthingwhichmightpopout
atyouisthattheperspectiveoftheroadstoredintheROMiscompletelydifferentfromtheperspectiveshowningame.This
isbecausethegraphicintheROMmerelystoreswhattheroadmightlooklikeforvariousroadwidths.Itisthejobofthe
programtoselectthecorrectlinesoutofthislargegraphicforeachlineofthescreen.
Thehardwaresupportstworoadsatatime,andsoyoucanassignprioritytotheleftorrightroad.Thisisforthepartsofthe
gameinwhichtheroadbranches,orwhenthereisacenterdividerbetweenlanesoftraffic.
ForyouROMhackersoutthere,checkoutMAME'ssrc/mame/video/segaic16.candsrc/mame/video/taitoic.cfilesfor
examplesofroadchips.NotethattheSegaroadgraphicsarestoredina2bitplanarformat,withthecenterofthegraphic
abletosportafourthcolor(thisistheyellowlineshowninthegraphicsabove).
Enduro
Enduroisaremarkablegame.Releasedin1983foranincrediblyunderpowered70'sgamingconsole,Endurostillmanages
toproduceaconvincingroadeffectcompletewithchangingweatheranddaynightcycles.Ontopofthat,itmanagestobe
anexcitinggameeven25yearsafteritsrelease!

ScreenshotofEnduro
Asyoucanseehere,Endurolooksalittledifferentfromotherroadengineswe'veseensofar.Immediatelyapparantisthat
theroadisonlydrawninoutline:Theterraintothesidesoftheroadarenotdrawninadifferentcolorfromthepavement.
Therearealsonoroadsideobstacles.OnceyoustarttoplayEnduro,youmightalsonoticethattheroaddoesn'tmovein
perspective.Instead,theplayercarspriteandroadbothshiftleftandrighttogivetheillusionofsteering.
InordertobetterunderstandwhyEndurolooksthewayitdoes,let'stakeapeekattheAtari2600'slimitations.TheAtari
2600wasdesignedprimarilytoplayCombatlikegames(tankgames)andPonglikegames.So,itwascapableofdisplaying:
twosprites,twosquaresrepresentingmissilesforeachplayer,asquarerepresentingaball,andaveryblockybackground.
Andthat'sit.
Butwhat'snotableabouttheAtari'svideohardwareisthatit'sessentiallyonedimensional:thesoftwaremustupdatethe
graphicsforeachscanlineitself.Forexample,toshowasprite,theprogrammerhastouploadanewlineofgraphicsto
displayatthebeginningofeachscanline.Todrawtheballobject,theprogrammerwouldturnontheballwhentheTV's
beamgottotherightline,andturnofftheballwhenthebeamgottoalinewheretheballshouldnolongerbevisible.
Thisleavesanimportantsideeffect:asolidverticallinecanbedrawndownthescreenbyturningontheballormissilesand
http://www.extentofthejam.com/pseudo/

11/18

1/3/2016

Lou'sPseudo3dPage

thenneverturningthemoff!Iftheprogrammermovestheseobjectseachline,diagonallinesmaybedrawn.
Now,backtothetaskathand.Wecoulddrawtheroadusingthebackgroundblocks,buttheresolutionismuchtoolowtobe
effective.WhatAtaridrivinggamesdidinsteadwasusethetwomissileorballgraphicobjectstodrawtheleftandrightsides
oftheroad,muchinthesamewaytheycanbeusedtodrawlines.Enduroinparticularusesthefirstplayer'smissilesprite
andtheballspriteinordertodrawtheleftandrightsides.PolePosition,ontheotherhand,usesbothmissilespritesforthe
sidesoftheroadandthenusestheballspritetodrawadottedlinedownthecenter.

ScreenshotofPolePositionon2600forcomparison
OnethingIhaven'tdiscussedishowyoumoveobjectsperlineonanAtari2600.TheAtari'sgraphicchiphasafacilitycalled
HMOVE(horizontalmove).Thisallowstheprogrammertosetupmoveseachlineforallthedifferentobjectsveryeasily.All
theprogrammerhastodoissethowmanypixelstomoveforthevariousobjects,andthencallHMOVEandvoilatheyall
moveaccordingtowhatwasset!
Enduroexploitsthisinordertodrawcurves.Inshort,whatEndurodoescreateatableinmemoryofhowtheHMOVEvalues
oftheleftandrightsidesvaryasthescreenisdrawn.ThisusesalmosthalfoftheAtari2600'savailablememory.Sincethe
Atari'smemoryissotiny,thisvalueisonlyreadevery4lines.Thereisadifferenttablefortheleftandtherightsidesofthe
road.
Whentheroadisstraight,thearrayfortherightsideoftheroadisall8's.TheHMOVEonlyusestheupper4bits,so8
loadedintoHMOVEwouldn'tmovethesidesoftheroadatall.Thelower4bitsareusedforacrudeformoffixedpoint.
Asanexample,here'swhatacurvelookslikeinmemoryasitapproaches(thehorizonistheendofthearray):
08,08,08,08,08,08,0a,0a,0b,0c,0e,0d,0e,0e,0f,10,13,11,12,13,14,17,16,17

Andthenextframe:
08,08,09,09,0a,0a,0b,0b,0c,0d,0d,0e,0f,0f,10,11,12,12,13,14,15,16,17,18

Notethatthehighercurvevaluesprogressivelywriteoverthelowervalues,shiftingdowntowardsthefrontofthescreento
providetheillusionthatthecurveiscomingtowardstheplayer.AndwhatdoesEndurodowiththisdata?Here'ssomeofthe
codeusedtowriteoutthecurvefortherightsideoftheroad
Foreachscanlineoftheroad:
LDA$be;Loadwhat'sinaddress$be
AND#$0f;Blowawaytheupper4bits(thebitsHMOVEuses)
ADC$e4,x;Addthevaluefromthecurvetable(Xishowfartowardsthefrontofthescreenweare)
STA$be;Savethevalueagain(sowecanloaditagainnextscanlinelikewedidabove)
STAHMBL;AlsoshoveitintotheHorizontalMotionBallregister

Sowhat'sthisdoing?Well,$beisacounterforthecurveamountwhichincrements.Whenit'sloaded,theupper4bitsare
tossedoverboard,leavingarangeof0to16($0F).Then,thecurvetableentryforthatparticularscanlineisloadedand
addedin.Finally,it'sstoredbacktothecounterandalsoloadedintothehorizontalmoveregisterfortheballobject(theright
sideoftheroad).
Thisdoesafewthings.First,itonlyresultsinthesidesoftheroadmovingeverytwolineswhentheroadisstraight:Ifthe
arrayisall8sand$becontains0onthefirstline,thenextlinewillcontain8(theuppernybbleisstill0).Thenextlineafter
thatwillcontain$10.Butwhen$10isloadedbackintotheregisterAonthenextscanline,theuppernybbleisdiscarded
leaving0again!Thiscausesthecountertoflipbetween$10and8.SincetheHMOVEvaluesonlyusetheupper4bytes,the
linemoves0positionsor1positionsalternating.
OK,butwhatifthearrayisall9sinsteadof8s?Here'swhathappens:Onthefirstscanline,9isstoredintotheballHMOVE
registerandwrittenbacktothecounter.Thenextline,9isagainaddedtothevaluefromthetablemaking$12(18decimal).
Thiswillmovetheballby1(upper4bitsis1).Onthelineafterthat,theuppernybbleisdiscardedleaving2.Adding9from
thetablemakes$B.Let'slookatonemorescanline.Bisloaded.Thereisnouppernybble.Adding9makes$14(20).
Thesequencedescribedaboveis09,12,0b,14.Thisisstillonlygoingtocausetheballtomoveeveryotherlineforthese4
lines.But,eventuallythelowernybbleisgoingtobecomehighenoughthatitwillcausetheroutinetomovetheballspriteleft
twolinesinarow.Thepatternwillthenwrap,butafterafewmorelines,thesideoftheroadwillmovetwolinesinarow
again.Inessence,thisisasimpleandblazingfastformoffixedpointmath.
Thereisanotherhurdleinimplementingaroadsystemonsuchlimitedhardware:positioningsprites.Onmoresophisticated
systems,spritescanbepositionedhorizontallyontheroadasapercentageoftheroadwidth.Butthisrequireseitherfixed
pointorfloatingpointmultiplication,bothofwhichareextremelyslowona6502.Incontrast,Enduroonlyhasthreepossible
positionsforthecars,whichsavessomecalculation.
RoadRash
RoadRashand3doRoadRashbothhaveamazinggraphicsengines.TheoriginalGenesisversionofthegamepulledoffa
http://www.extentofthejam.com/pseudo/

12/18

1/3/2016

Lou'sPseudo3dPage

relativelyaccurate3dsensationontheGenesis'7.25mhz68000processor,completewithrealtimescalingoftheroadside
objects.The3dofollowupisnolessfascinating,asitturnsouttobeamixtureof3dandpseudotechniqueartistically
combinedtogivetheplayeranamazingsensationofspeed.
AsImentionedabove,boththeRoadRashand3doRoadRashenginesareamixtureof3dandpseudo3dtrickery.They
useatechniquesimilartotheonedescribedinthe"RealisticHillsUsing3dProjectedSegments"chapterinwhichthehills
arein3dspace,buttheroad'scurvesarenot.RoadRash'scurvesusethesamemethoddescribedinthisarticle,andeach
roadsegmenthasitsownDDXor"xacceleration"value.Eachsegmentalsohasaheightwhichisrelativetothelast
segment'sheight.Thereareroughly50segmentsonscreenatonce.
Butwherethe3doRoadRashisreallyinterestingisthattheprogrammersaddedwarpingwhichincreasesthesensationof
speedthattheplayerexperiences:Objectsfarfromthecameramovemoreslowly,andobjectsnearthecameramovemore
quickly.
The3doRoadRashalsoaddspolygonalroadsideobjectswhoseXcoordinatesarestillrelativetotheroad.Theseareused
tocreatehills,buildings,andotherrelativelycomplexscenery.Thisusesafairamountofdata,sothegeometryandtextures
botharestreamedfromthediscasthetrackistraversed.
S.T.U.N.Runner:Arcadevs.Lynx
S.T.U.N.Runnerwasamarvelousgamewhenitdebutedatarcadesin1989.Itmadegreatuseoffully3dfilledpolygon
technology,allowingtheplayertotakecontrolofafuturisticracecraftbarrelingdowntwisting,turningcorridorsatbreakneck
speed.Notlongafter,IsawaversionfortheAtariLynx.TheAtariLynxwasahandheldsystemwhichcameoutaboutthe
timeoftheoriginalGameBoy.LiketheGameBoy,ithada4MHz8bitprocessor.So,theportwashorrible,right?Well,
checkoutthefootagebelow:

Lynx S.T.U.N. Runner played badly

Actually,theportwasfantastic!Itcameclosetoperfectlycapturingwhatmadethearcadegamesothrilling.WithGameBoy
eraportablehardware,howonearthwasitdone?
ItturnsoutthattheLynxhadoneimportantweaponinitsarsenal:hardwarescaling.Butthisisn'tahugehelpinrendering
polygonalgraphics.Itturnsoutthatitwasn'tjusttheLynxthathadsometricksupitssleeve:Theauthorwhoportedithad
sometricksofhisown.
Torecreatethespeedofthearcademachine,theLynxversionofS.T.U.N.Runnerresortedtoapseudo3droadengine.The
polygonslicesthatmakeupthetunnelwallsareactuallysprites.Theseareessentiallytracksideobjectswhicharegluedto
theroad,muchliketheroadsideobjectsinanyotherpseudo3dracinggame,andaredrawnusingthepainter'salgorithm
(backtofront).Thisconvincinglycreatestheillusionofpolygongraphicswhilestillplayingtothestrengthsofthehardware.
Andtosavespaceonthecartridge,onespritewasn'tafullringofthetunnelgraphic.Notonlydoesthissaveonthenumber
ofblank,transparentpixels,butit'sarrangedsothathorizontalflippingofthegraphicshardwarecouldbeused.
Oneinterestingproblemthattheauthorhadtosolvewaswhenthetunnelbranches.Youcanalsoseethisinthevideo
above.Thebranchingtunnelisactuallyabigspritewhichscalesattheplayer.Aftertheplayerhaschosentheirnewpath,
thesplitgraphicgoesaway.Accordingtotheauthor,sometimesyoucanspotvehiclesdrivingrightthroughthissprite!
Ifyou'reinterestedinreadingmore,theconversationonAtariAgewiththeoriginalauthorcanbefoundhere.
RoadsontheCommodore64
ThisinformationiscourtesyofSimonNicol,whofiguredoutagreattechniqueforfastroadsontheC64.
First,somebackground:Onmanyconsolesystems,apseudo3droadcanbedonebydrawingastraightroadwithtilesand
scrollingperlinetomakeitappeartocurve.However,thisturnedouttobetooslowforafullframerategameonthe
Commodore64.
Simon'sengineinsteadusesC64'sbitmapmodeandusesafastfillalgorithm.Hisfastfillalgorithmusesselfmodifyingcode
tospeedupdraws:Eachlineisaseriesofperpixelstoreswhichspecifyanaddressinvideomemory.Atthepointthough
thatthecolorhastochange,thecodeisaltered.Thestorecommandisturnedintoaloadcommand,andwhatwasthe
addressforthestoreisturnedintotheliteralnumberofthenewcolor.
Onemajoradvantageofthistechniqueisthatspritemultiplexingtechniquestoshowmorethaneightspritesonthescreen
canstillbeused.InSimon'swords:"Offsettingthehorizontalscrolltogetastablerastereffectwouldinvolvemanipulating
register$D011.TherasterIRQat$D012wouldflickerbadlyotherwisedependingonthenumberofspritesonthatparticular
rasterline.Tohaveanysortofsmoothdisplaywouldinvolvelockinguptheprocessortogetthetimingjustright,orbynot
usingthescreengraphicsandjustchangingthebordercolour.Thiswhichwouldbesolidandflickerfree,buttherewouldn't
beroadvisibleonthescreenbecauseitwouldhavetobeswitchedoff.Thesesmooth,perlinebordercolourchangeswere
usedchasingtherasterdownthescreen,anditcouldalsobeusedto'holdoff'wherethetopofthescreencouldbe
displayed.Itwascalled$D011holdofforsometimesFLDforflexiblelinedistancing(thetechniqueusedtoeliminateVIC's
badlines).
OtherEngines
http://www.extentofthejam.com/pseudo/

13/18

1/3/2016

Lou'sPseudo3dPage

PowerDrift

PowerDriftisinterestingbecauseitisoneofthefewgamesIknowofwhichusespritebased3d.Eachchunkofthetrackis
asmallspriteblob,andtheflybyisSega'swayofshowingitoff.Idon'thaveproof,butIbelievegamessuchasF1Exhaust
HeatandRadMobileuseasimilarsystem.ItisalsoworthnotingthatthedeluxecabinetofPowerDrifttiltedalmost45
degrees,makingitsomewhatimportanttowearthatseatbeltforonce.Screenshotsfromsystem16.com.
Racin'Force

Racin'ForcewasreverseengineeredbytheintrepidCharlesMacDonald.Racin'ForcerunsontheKonamiGXboard,which
featuresadaughterboardwithavoxelenginecapability.Thishardwareisbaseduponolderhardwarewhichcouldonlydraw
aSNESmode7likefloormap.Itwasextendedtodoaheightmapthroughthisclevertechnique:Itprojectsnotjustthe
tilemapontoaflat3dplane,butalsotheheightinformationforeachpixelontoitsownseparate3dplane.Then,foreach
pixelofthescreen,itlooksuptheheightinformationontheprojectedheightmap,andextrudeseachpixelupwardsas
necessary.Screenshotsfromsystem16.com.

FurtherExploration
Herearesomesiteswhichmaybeusefulforlearningmoreaboutpseudo3droads:
Cannonball:OpensourceOutRunport
CodeinCompleteJavaScriptRacer

CodeStuff
FormulasandTips
3dProjection
y_screen=(y_world*scale/z)+(screen_height>>1)

or:

z=(y_world*scale)/(y_screen(screen_height>>1))

Thisformulatakesthexoryworldcoordinatesofanobject,thezoftheobject,andreturnsthexorypixellocation.Or,
alternately,giventheworldandscreencoordinates,returnsthezlocation.
Thescaledeterminesthefieldofview(FOV),andcanbefoundby:
scale_x=x_resolution/tan(x_angle/2)
scale_y=y_resolution/tan(y_angle/2)

FastLinearInterpolation
o(x)=y1+((d*(y2y1))>>16)

Thisassumesthatallthenumbersarein16.16fixedpoint.y1andy2arethetwovaluestointerpolatebetween,anddisthe
16bitfractionaldistancebetweenthetwopoints.Forexample,ifd=$7fff,thatwouldbehalfwaybetweenthetwovalues.This
isusefulforfindingwherebetweentwosegmentsavalueis.
FixedPointArithmetic
Floatingpointisveryexpensiveforoldsystemswhichdidnothavespecializedmathhardware.Instead,asystemcalledfixed
pointwasused.Thisreservedacertainnumberofbitsforthefractionalpartofthenumber.Foratestcase,sayyouonly
reserveonebitforthefractionalamount,leavingsevenbitsforthewholenumberamounts.Thatfractionbitwouldrepresent
onehalf(becauseahalfplusahalfequalsawhole).Toobtainthewholenumbervaluestoredinthatbyte,thenumberis
shiftedrightonce.Thiscanbeexpandedtouseanynumberofbitsforthefractionalandwholeportionsofthenumber.
Fixedpointmultiplcationistrickierthanaddition.Inthisoperation,youwouldmultiplythetwonumbersandthenshiftrightby
howevermanybitsarereservedforfractions.Duetooverflow,sometimesyoumayneedtoshiftbeforemultiplicationinstead
ofafter.See"FastLinearInterpolation"foranexampleoffixedpointmultiplcation.
PointRotation
http://www.extentofthejam.com/pseudo/

14/18

1/3/2016

Lou'sPseudo3dPage
x'=x*cos(a)y*sin(a)
y'=x*sin(a)+y*cos(a)

Mentionedbrieflyinthetutorialasbeinganexpensiveoperation,hereisthebasicpointrotationformula.Asyoucansee,it's

atleast2tablelookups,4multiplications,andtwoadditions,butthesineandcosinevaluescanbereusedforeachpoint.
RotatingforthepurposeofhillswouldmeanrotatingtheZandYcoordinates,nottheXandYcoordinates.Tofindthe
derivationofthisformula,lookupRotationofAxes.

AvoidDivision

Insteadofdividingbythezofanobjectinthestandardprojectionformulas,youcantakeadvantageofsomepropertiesof
theroadtospeedupcalculations.Sayyouhavea3dsegmentzpositionandayposition,andyouwanttofindwhichlineof
thescreenitbelongson.First,readthroughthezmapuntilyougettothe3dsegment'szposition.Then,multiplytheheight
ofthesegmentbythecorrespondingscalingvalue.Theresultisthenumberofpixelsabovetheroadthatthesegment
belongs.
UseZasScalingValue

Scalingroutinesworkbyslowingorspeedingupthespeedatwhichadrawroutinereadsthroughgraphicsdata.For
example,ifyouweretosetthereadspeedtohalf,thiswoulddrawaspritedoublethesize.Thisisbecauseforeachtimea
pixelisdrawn,thereadpositioninthespritedataisonlyincrementedbyhalf,causingthereadpositiontoonlyincrementby
awholenumbereverytwopixels.
Usually,ascalingroutinehasparameterslikex,y,andscalingfactor.Butsinceascalingfactorisjust1/z,wecanjustreuse
theZvalueofthatsprite!Wewillstillneedthescalingfactorthoughtodeterminetheboundariesofthespritesothatwecan
keepitcenteredasitscales.

Glossary
BadLineIntheC64'sVICIIgraphicschip,atthefirstpixelofeverybackgroundtile,theVICtakesovertheprocessorto
pullinmoredatasuchascolors.Sincetherearefewercyclesleftforaprogramtodocomputations,thesearereferedtoas
badlines
HeightMapAheightmapisanarrayofheightvalues.Inapolygonorvoxellandscapeengine,thismightbea2darray
(thinkofalandscapeviewedfromthetop).However,inaroadengine,aheightmapwouldonlyneedtobeonedimensional
(thinkofalandscapeviewedfromtheside).
IndexedColorModeOldersystemswhichfeaturefewcolorsonthescreenatatimearegenerallyinindexedcolormodes.
Someofthemostcommonindexedcolormodesarethe256colorVGAmodes.Inthesemodes,eachpixelisrepresentedby
abyte.Eachbytestoresanindexvaluefrom0to255.Whenthescreenisdrawn,theindexnumberforeachpixelislooked
upinthepalette.EachentryinthepalettecanbeoneofVGA's262,144possiblecolors.Insummary,eventhoughonly256
colorscanbeonscreenatatime,theusercanchooseeachcolorfromamuchlargerpalette.
LinearInterpolationTheprocessofobtaininginbetweenvaluesfromadatasetbydrawinglinesbetweenthepoints
Painter'sAlgorithmThePainter'sAlgorithmisthepracticeofdrawingoverlappingobjectsfromfartonear.Thisensures
thatcloserobjectsalwaysappearontopoffartherones.
PlanarGraphicsModeAPlanargraphicsmodeisoneinwhichanNbitimageismadeupofN1bitimageswhichare
combinedtoproducethefinalimage.Thisisopposedtomostgraphicsmodes,sometimesreferredtoaschunky,inwhichan
NbitimageismadeupofNbitpixelvalues.
RasterEffectArastereffectisagraphicaltrickwhichtakesadvantageofthescanlinebasednatureofmostcomputer,or
raster,displays.
ScalingFactorThereciprocalofZ.ThisgivesyoutheamountbywhichtoscaleanobjectatagivenZdistance.
Segment(Road)Iamusingthetermsegmenttomeanapositionbelowwhichtheroadactsoneway,andabovea
differentway.Forexample,thesegmentcoulddividealeftturnonthelowerhalfofthescreenfromarightturnontheupper
half.Asthesegmentmakesitswaytowardstheplayer,theroadwillappeartosnakeleftthenright.
Segment,3d(Road)Iamusingtheterm3dsegmenttomeanahorizontallinewhichhasbothaZdistanceandaworldY
height.Unlikeavertex,whichcouldbea3dpoint,a3dsegmentwouldbea3dlinewiththeleftandrightXaxisendpointsat
positiveandnegativeinfinity.
VoxelA3dpixel.Raycast/landscapevoxelengineswerepopularizedinthegameCommanche:MaximumOverkill.
ZMapAlookuptablewhichassociateseachlineofthescreenwithaZdistance.

TheGallery
Hereisacollectionofscreenshotsthatshowvariouswaystodounorthodoxroadengines.Takealook!
CiscoHeat

http://www.extentofthejam.com/pseudo/

15/18

1/3/2016

Lou'sPseudo3dPage

Thehillsinthisgamecomeatyoulikeasolidwall.Theturnsarealsoveryexaggerated.Theengineseemsquiteflexibleand
dealswithmultipleroadssimultaneously,aswellasbeingabletoshowtheheightofoneroadrelativetoanother.
PolePosition

ThisisthefirstsmoothlyrunningpseudogameIremember.Notextremelyimpressivetodaygraphically.
Hydra

ThisisanotherAtarishootemupalongthelinesofRoadblasters.Itfeaturesaverynicejumpingeffectinwhichtheroad
layer'sperspectivetips,causingtheclosestobjectstofalloffthescreen.Italsonicelyprojectsobjectsofvaryingdistances
abovetheground.
Outrunners

ThissequeltoOutrunisaprimeexampleofrollercoasterlikehillsinaracinggame.Everythingisquiteexaggeratedinthis,
andtheresultisoneofthemostblindingfastyetnicelycontrollableracinggamesever.
RoadRash

Inthe32bitgenerationversionofRoadRash,everythingwastexturedandbuildingswerecleverlydrawnnexttothe
roadside,leavingsomepeoplewiththeimpressionthatitwasapurelypolygonalgamerunningfastonthe3do.However,the
http://www.extentofthejam.com/pseudo/

16/18

1/3/2016

Lou'sPseudo3dPage

wayobjectswhiparoundthecorners,buildingswarp,andthatyoucan'tgobackwardswouldseemtogiveawaythatit'snot
reallyapolygonengine.Thesharplinesonthepavementdohintatsomesortofprojectedsegmentsystemthough.The
trackshavealotofdetailandvariety.The16bitgenerationRoadRashwasalsonoslouch,alsofeaturingaflexibleengine
withatinybitoffakedtexuring(butwasslow).
Turbo

ThispredatesPolePositionandalsofeatureshillsandbridges.Thedrawback?Therearenotransitionsfromhilltobridgeto
curve.Thisusedanaloggraphicsscalinghardware.
SpyHunterII

Idon'tknowwhatthemakersofSpyHunterIIwerethinking.Niceidea,badexecution.Theroadeffectsseemverysimilarto
Turbo'swithalittlemoreinthewayoftransitions.
PitstopII

ThistechniqueissoquickthatonthelowlyCommodore64,peoplewereabletopulloffasplitscreenracinggame.
Enduro

Endurodemonstratestheuseofpseudo3dontheAtari2600.
EnduroRacer
http://www.extentofthejam.com/pseudo/

17/18

1/3/2016

Lou'sPseudo3dPage

NottobeconfusedwithEnduro,thiswasasortof3dExcitebikelikegame.Thescreenshotshowsoffthehilltechnique.Hills
arerathersharp,flexible,butgenerallydon'taffectthehorizon'sposition,soI'mguessinginterpolatedpoints.
Lotus

Lotuscomesthroughwiththeperfectlycurvedhilltechnique.OneinterestingthingisthatLotuswilldrawtheroad'stopbelow
thehorizonandthenfillthegapwithasolidcolortoimplyadownhill.
TestDriveII

I'mnotsureexactlywhattomakeofTestDrive2'sgraphics.Whileclearlynotapolygonracer,ittriesveryhardtorealistically
representavarietyofroads.ThegameissimilartotheNeedforSpeedseriesbutpredatesitbyseveralyears.
SpeedBuggy

Whenyousteerinthis,inadditiontoshiftingtheperspective,theroadalsoslidesleftandrightalittle.

http://www.extentofthejam.com/pseudo/

18/18

Você também pode gostar