You are on page 1of 86

Entering the 3d dimension...

Hi t her e! Rel sof t agai n back wi t h an ar t i cl e f or you.


: *) . Thi s ar t i cl e i s t he f i r st of a ser i es of 3d ar t i cl es t hat
I ' l l be ser i al i zi ng i n QBASI Cnews. com. I don' t know how f ar I
coul d t ake you or how many chapt er s wi l l I make. I t depends upon
t he user f eedback and my f r ee t i me. ; *)
I ' mmost l i kel y t o cover a l ot of t hi ngs t hat af t er you' ve r ead
t he whol e ser i es, you' r e l i kel y t o be abl e t o make your own FPS
r ender , a 3d st r at egy game or even a Ragnar ok st yl e engi ne. ; *)
I. Course outline
What I wi l l be cover i ng i n t hi s ser i es ar e l i st ed bel ow:
1. 3d Pr oj ect i on
a. Theor y
b. Camer a
c. Tr ansl at i on
2. 2d and 3d r ot at i ons
a. Si n/ Cos
b. Pol ar coor di nat es
c. Pr oof of r ot at i on
d. Tr ansf or mat i on
e. 3d Opt i mi zat i on
3. 3d coor di nat e syst ems
a. Car t esi an
b. Spher i cal
c. Cyl i ndr i cal
d. 3d Model gener at i on
e. Pol ygon 101
4. Pol ygon f i l l s
a. Vect or s
b. wi r ef r ame
c. Fl at
5. Nor mal s and l i ght sour ci ng
a. Mor e on Vect or s
b. Cr oss pr oduct
c. Dot Pr oduct
Lamber t shadi ng
Gour aud shadi ng
Phong shadi ng
d. Movi ng Li ght sour ce
e. Mul t i pl e Li ght
f . Text ur eMappi ng
6. Mul t i pl e obj ect s
a. Sor t i ng Met hods
b. Vi si bi l i t y check
c. Dept h- Buf f er i ng
7. Desi gni ng a 3d game engi ne
a. Camer a as a vect or
b. Mat r i ces
8. I don' t know yet . ; *)


II. Introduction

The pur pose of t hi s ar t i cl e i s t o t r y t o expl ai n t he
r easons behi nd 3d pr oj ect i on and a l i t t l e on 2d r ot at i on. 3d i s
onl y as har d, or as easy, as you want i t t o be. Don' t be af r ai d
as I ' l l t ake you t o t he wor l d of 3d st ep by st ep.
What you need t o be abl e t o r un t he sampl e pr ogr ams t hat I wi l l
be t hr owi ng f r omt i me t o t i me i s any f l avor of
QuickBASIC( QBASI C, QB4. 5, 7. 1, et c) . A l i t t l e exper i ence i n
al gebr a and Tr i g i s al so a pl us but not necessar y. I wi l l al so
t r y t o expl ai n opt i mi zat i on t echni ques as we go al ong t he whol e
ser i es. ; *)

III. 3d cartesian coordinate system

The 3d car t esi an coor di nat e syst emi s al most l i ke t he 2d
car t esi an coor di nat e syst emt hat we gr ew up wi t h, onl y wi t h an
ext r a di mensi on: The Z axi s. *Ther e ar e sever al ot her 3d
coor di nat e syst ems l i ke spher i cal and cyl i ndr i cal . I wi l l
expl ai n t hemt o you i n det ai l i n f ut ur e i ssues, but when I t al k
3d coor di nat es f or now, i t s t he car t esi an coor di nat e syst em
unl ess speci f i ed.
i e. a. 2d
p( x, y)
b. 3d
P( x, y, z)

But how do we def i ne a 3d coor di nat e? Wher e does t he z-
axi s go? As we know al r eady, i n 2d coor di nat e, t he x- axi s i s
goi ng t o t he r i ght and t he y- axi s i s goi ng up. The 2 axes( pl ur al
f or axi s) i nt er sect at p( 0, 0) . Read as " Poi nt 0, 0" wher e t he
f i r st val ue i s t he x(abscissa) and t he second val ue i s t he
y(ordinate). P( 0, 0) i s al so cal l ed t he "Origin". They ar e al so
PERPENDI CULAR t o each ot her . Per pendi cul ar means a l i ne, pl ane or
a r ay( vect or ) whi ch has a uni on of 90 degrees. Meani ng t hey f or m
a " +" when t hey i nt er sect .



See how al l t he angl es( 1, 2, 3, 4) ar e al l 90 degr ees?
That ' s t he essence of per pendi cul ar i t y. Al so be sur e t hat you
under st and t hi s concept as per pendi cul ar i t y i s used on al most
al l t hi ngs t hat got t o do wi t h 3d. *Perpendicular
lines/Planes/rays are also called "orthogonal".

Ther e i s not t hat much di f f er ence i n 3d, al l t he axes
ar e per pendi cul ar t o each ot her . i e:
Z axi s i s per pendi cul ar t o t he XY Pl ane, Y axi s i s per pendi cul ar
t o t he XZ pl ane as t he X axi s t o t he YZ pl ane. Now how about t he
di r ect i ons t he axes go? Wel l , t her e ar e t wo ways t o def i ne a 3d
syst em. The "RIGHT-HANDED" and t he "LEFT-HANDED" syst ems. The
choi ce i s your s t o make, or me i n t hi s case because I ' mt he one
wr i t i ng t hi s ar t i cl e.



a. Lef t handed syst em( Fi g. 2)
The l ef t - handed syst emmeans t hat when i ncr eased:
x goes r i ght
y goes Up
z goes i nt o t he scr een ( away f r omyou)

b. Ri ght Handed syst em( Fi g. 1)
When i ncr eased:
x goes r i ght
y goes up
z goes out of t he scr een ( I nt o you)

Si nce most books use t he r i ght handed syst em, I ' l l use
t hat syst em. Anot her r eason i s t hat t he coor di nat es when pl ot t ed
on t he scr een, r esembl es a r eal - wor l d syst em. Hey, I ' mr i ght
handed. ; *)

IV. 3d to 2d projection.

As you mi ght have guessed, QB has no PSET3d or LI NE3d
r out i ne so we have t o make one. : *) The beaut y of l ear ni ng t he
t heor i es and pr i nci pl es behi nd how t hi ngs wor k i s t hat you won' t
get l ost at di scussi ons on f or ums. : *) So l et me st ar t by t he
pr i nci pl e:


Nor mal way: "The farther the thing from the viewer the smaller
it gets"
J ocke' s way: "I'm gonna kick this ball so far you won't be able
to see it."
Mat h way: "Distance is inversely proportional to the size of an
object"

Tr yi ng t o make an equat i on usi ng J ocke' s or t he Engl i sh
st at ement woul d be ver y har d. So we' l l use t he Mat h way:

Si ze=1/ di st ance
so:
Newsi ze=Si ze/ Di st ance
assume:
a.
Or i gSi ze = 100
Di st ance = 1
= 100/ 1
= 100
b.
Or i gi ze = 100
Di st ance = 50
= 100/ 50
= 2

*This is just an approximation. Just to show you the
relationship of size and distance.

Now you woul d want t o pr oj ect and obj ect but how do we
do i t wi t h t he knowl edge t hat we have al r eady l ear ned? Wel l ,
Fi r st , we have t o deci de wher e z =0 i s. Tur ns out t hat a good
way t o def i ne z=0 i s a number of uni t s away f r omyou. Whi ch
means t hat you can see i t when you l ook at your moni t or . A good
val ue i s 256. Why 256? Wel l , t hi s i s not ent i r el y t he l aw si nce
you coul d make i t as smal l or as bi g as you want i t t o be, but
256 i s a good mul t i pl i er ( or any power of 2 val ue) as you wi l l
see l at er . Secondl y, wher e t o put t he moni t or i n our 3d space.
Thi nk of your moni t or as a "camera" t hat poi nt s ont o t he 3d
space and t he scr een as t he LENS( camer a l ens) per pendi cul ar t o
t he z- axi s( Yes, your XY pl ane) . Si nce ( 0, 0, 0) or z=0 i s at a
di st ance of 256 l ooki ng at t he negat i ve di r ect i on, our Lens
shoul d be 0+256. So t hat t he coor di nat e of our l ens i s
( 0, 0, 256) . Anyt hi ng mor e t han 256 i s behi nd t he camer a and
shoul d not be pl ot t ed. Remember t hat we ar e l ooki ng on t he
negat i ve z i n r i ght - handed syst ems.

And why did we use 256?
Seasoned pr ogr ammer s woul d know t hat 256 i s a power of
t wo. Si nce you can use shi f t s t o mul t i pl y and di vi de, you coul d
make your r ender s f ast er by mi l es as shi f t s ar e way f ast er t han
di vs or mul s. ; *)

I n scr een 13, t he di mensi ons of t he scr een i s 320*200
and i t s cent er i s ( 160, 100) . We know t hat at z =0, t he
r el at i onshi p of each x, y, z uni t s i s t hat x and y i s one uni t
wi de. So pl ot t i ng ( 8, 5, 0) :

Di st ance= 256
scr eenx = 160+x
scr eeny = 100- y ( t he scr een y- wi se i s r ever sed)
Then:
Scr eenx = 160 + 8 = 168
Scr eeny = 100 - 5 = 95
Pset ( 168, 95) , col

How about i f z = 128? ( 8, 5, 128)
t hen:
di st ance = 256 - 128
= 128
128 i s near er whi ch means t he si ze of t he uni t s shoul d
i ncr ease. But how much? Si nce 128 i s hal f of 256, our uni t s
shoul d be 2x( t wi ce) t he si ze of t he uni t s at z = 0. so. .

scr eenx = 160+x*2 = 160+8*2
scr eeny = 100- y*2 = 100- y*2
Then:
Scr eenx = 160 + 16 = 176
Scr eeny = 100 - 10 = 90
Pset ( 168, 95) , col

Pr et t y easy huh? Put t i ng i t al l t oget her , t he pr oj ect i on
woul d l ook l i ke t hi s:

Di st ance= LENS- z
scr eenx = xcent er +( LENS*x/ Di st ance)
scr eeny = ycent er - ( LENS*y/ Di st ance)

Now l et me expl ai n how each component af f ect s t he whol e
pr oj ect i on f or mul a:

1. Lens
We know t hat LENS, t he l ens of our camer a or moni t or i n
t hi s case, i s a mul t i pl i er t o gi ve your pr oj ect i on a f i el d of
vi ew( FOV) and si nce t he camer a i s 256 uni t s away f r om( 0, 0, 0) we
woul d want t he val ue of our l ens t o have a di r ect cor r el at i on
wi t h di st ance. eg: z = 0
Di st ance = 256- 0 = 256
Lens = 256
x = 8
xcent er = 160
=( 256*8/ 256) +160 =168

(See the relationship already?)
* some people use a value of Lens=1 so that it weeds out
2 muls or shifts in the actual projection fomulas but in my
experience, the objects does not look "natural".

2. Distance
Thi s i s j ust how f ar a 3d pi xel i s away f r omt he camer a.
Si nce we l ook i n t he negat i ve di r ect i on, " The f ar t her t he
di st ance, t he smal l er t he z val ue. i e. p( 0, 0, - 100) i s f at her
t han p( 0, 0, 100) . Let us see i f t hi s hol ds t r ue i n equat i on f or m.
a. ( 0, 0, - 100)
Di st ance = 256- ( - 100)
' di st r i but e t he [ - ] si gn:
Di st ance = 256+100
Di st ance = 356

b. ( 0, 0, 100)
Di st ance = 256- ( +100)
Di st ance = 256- 100
Di st ance = 156

Ahem! 356>156. ; *)
What about z=>256 or di st ance i s 0 or l ess? Wel l , unl ess
you want t o poke your sel f i n t he eye, you woul dn' t want t o pl ot
em. ; *) Pl ot t i ng at di st ance=0 i s t echni cal l y cor r ect but You
had t o change your pr oj ect i on f or mul a because n/ 0 i s undef i ned.
And i n geomet r y, "Distance is always positive :*)" Her e' s t he
f or mul a:

Di st ance = 0
scr eenx = xcent er + ( LENS*x)
scr eeny = ycent er - ( LENS*y)

To t est your i nt el l i gence, I ' l l l et you t hi nk about i t
your sel f . ; *)

FINAL PROJECTION EQUATIONS!!!

Distance = LENS-z
screenx = xcenter+(LENS*x/Distance)
screeny = ycenter-(LENS*y/Distance)


Now l et ' s see i f t he pr oj ect i on equat i ons woul d r et ur n
t he same val ues f or ( 8, 5, 128) :
Remember t hat we r et ur ned x=176, y=90)
Di st ance = 256- 128=128
scr eenx = ( 256*8/ 128) + 160
scr eeny =- ( 256*5/ 128) + 100
=
scr eenx = ( 2048/ 128) + 160
scr eeny =- ( 1280/ 128) + 100
=
scr eenx = ( 16) + 160 = 176
scr eeny =- ( 10) + 100 = 90
Ahem. . . ; *)

V. Translation
Tr ansl at i on i s j ust movement of a poi nt f r omone
l ocat i on t o anot her . To si mpl i f y t hi ngs, I put t he t r ansl at i on
coor ds i n t he f or mof a camer a of f set s, camx, camy, camz.
Movi ng t he l ocat i on of t he poi nt i s j ust as si mpl e as
addi ng or subt r act i ng val ues t o t he camer a of f set s and
subt r act i ng t hose component s; x, y & z f r omp( x, y, z) i e:

Xt r ansl at ed= x - camx
Yt r ansl at ed= y - camx
Zt r ansl at ed= z - camx

VI. Putting it in action
Now f or t he f un par t , pl ot t i ng! . Let ' s st ar t by t he
si mpl est of al l " model s" ( When I say model s I mean an ar r ay of
poi nt s t hat def i ne a 3d obj ect ) , t he pl ane. I n t hi s case we want
t o pl ot a gr i d of 16*16 pl ane. As we woul d want t he gr i d t o be
cent er ed at x=0 and y=0, t he st ar t i ng x and y val ues of our gr i d
i s negat i ve. We al so woul d want t o st ar t at z=0 addi ng an
i ncr ement ( 20) f or ever y y- l oop. We al so woul d want t o scal e t he
di st ance bet ween each poi nt , i n t hi s case 4.

QBcode:
Gsi ze = 16
si ze%= Gsi ze * Gsi ze ' 16 * 16 gr i d
DI M SHARED Pl ane( si ze%- 1) AS Poi nt 3D ' di mout pl ane

Scal e = 4 ' scal e f act or
' change t o a smal l er i f you want t o
' r educe t he si ze.
z = 0 ' st ar t 256 uni t s away f r omscr een
i = 0 ' i ndex f or pi xel s

Hal f Si ze = Gsi ze \ 2 ' 1/ 2 of our gr i d f or
cent er i ng
FOR y = Hal f Si ze - 1 TO - Hal f Si ze STEP - 1 ' l oop t hr ough i t
FOR x = Hal f Si ze - 1 TO - Hal f Si ze STEP - 1 ' and cal cul at e each coor d

Pl ane( i ) . x = x * Scal e ' make t he model bi gger
Pl ane( i ) . y = y * Scal e
Pl ane( i ) . z = z
i = i + 1 ' i ncr ement ar r ay i ndex
NEXT x
z = z + 20 ' go out i nt o t he scr een 20 uni t s ever y
l i ne.
NEXT y

Now t o pr oj ect i t ,

1. start
2. read pixel at location i
3. translate the pixel using p(x,y,z) - cam(x,y,z)
4. project each pixel
5. Plot
6. If I<maxpoints go to start else end


QBCode:
FOR i = 0 TO UBOUND( Pl ane)
sx! = Pl ane( i ) . x - camx% ' coor ds
sy! = Pl ane( i ) . y - camy% ' sub t r act ed by t he
sz! = Pl ane( i ) . z - camz% ' camer a
' we can st i l l di r ect l y subt r act
' camer a of f set s t o our or i gi nal
' coor ds as we ar e not r ot at i ng yet . ; *)

Di st ance%= ( LENS - sz! ) ' get Di st ance
I F Di st ance%> 0 THEN ' i f di st >>0 t hen
' Pr oj ect i on f or mul a
x%= XCENTER + ( LENS * sx! / Di st ance%)
y%= YCENTER - ( LENS * sy! / Di st ance%)
PSET ( x%, y%) , 15 ' Dr aw each st ar
ELSE
' do not hi ng
' you woul dn' t wan' t t o
' di vi de by 0 woul d ya? : *)
' and i n geomet r y, di st ance i s
' al ways posi t i ve. ; *)
END I F
NEXT i



Now her e' s t he exampl e f i l e of a pr oj ect ed pl ane:
( camer a i s cont r ol l ed by AZSXDC)
Pr oj ect . BAS
You can even pr oj ect t ext s:
PROJ CHAR. BAS

Her e' s how you can appl y t he pr oj ect i on equat i ons t o a
st ar f i el d:
Pr oj st ar . bas


VII. Using sprites instead of pixels

Pi xel s al one t end t o be bor i ng af t er a whi l e. So why not
use spr i t es? Consi der i ng we al so have t o pr oj ect t he si ze of t he
spr i t e or t i l e, we can' t use t he nor mal QB PUT r out i ne, so we
have t o make a st r et ch spr i t e r out i ne f or t hi s pur pose al one.
The al go behi nd t he st r et ch spr i t e r out i ne i s pr et t y t r i vi al so
I won' t expl ai n i t her e i n det ai l . Al l you have t o r emember i s
t hat you coul d zoomor pan on a spr i t e dependi ng on t he
par amet er s, NewHei ght and NewWi dt h.

For t he act ual al go i n cal cul at i ng t he new di mensi ons, her e' s
t he f or mul a:

NewHei ght =Ol dHei ght * LENS/ Di st ance%
NewWi dt h =Ol dWi dt h * LENS/ Di st ance%

Ol dWi dt h and Ol dHei ght ar e t he act ual di mensi ons of t he
spr i t e. I e. I f you GET( 0, 0) - ( 15, 15) , Ar r ay t hen t he si ze of t he
spr i t e i s 16*16. So Ol dHei ght = 16 and Ol dWi dt h =16.
Di st ance i s t he same di st ance i n out pr oj ect i on
equat i ons. Same wi t h t he LENS.
I ' l l l et you f i gur e out t he r at i onal e behi nd t he equat i ons
your sel f . : *)

Her e ar e some sampl e f i l es:
Met eor . bas
St ar s. bas

Hope you' ve l ear ned somet hi ng f r omt hi s. The best way t o
l ear n t hough i s t o j ust pl ay wi t h t he val ues, r unni ng t he
pr ogr amand see t he ef f ect of t he changed val ues.
Next t i me, I wi l l t each you 2d and 3d r ot at i ons, pol ar
coor di nat es, ot her f or ms of t r ansf or mat i on besi des t r ansl at i on,
opt i mi zat i ons of 3d r ot at i ons usi ng const ant s, and pr obabl y i f
space wi l l pr ovi de 3d model gener at i on( The mat h way) . So you
mi ght want t o r ead on:

1. Tr i g Funct i ons
Si n and Cos onl y
2. Tr i g I dent i t i es
Cos/ Si n addi t i on l aws
3. Ri ght Tr i angl e r el at i onshi ps i n Tr i g f unct i ons
4. Pol ar t o car t esi an coor di nat e conver si on.
*Don't worry even if you don't know a thing about those
things I mentioned because I will be teaching you all of those
next issue as if you're am 8 year-old kid. ;*)
So unt i l next t i me, Rel sof t si gni ng out . Happy codi ng! ! ! !


Rel sof t 2004
vi c_vi per ph@yahoo. com
ht t p: / / r el . phat code. net /
Rotations, the how's and why's...


I. Introduction

I bet you f el t ver y annoyed by t he f act t hat I onl y
expl ai ned pr oj ect i on on my f i r st ar t i cl e r i ght ? Wel l , t he ser i es
i s pr i mar i l y gear ed t o coder s who had no exper i ence i n 3d codi ng
and t o advance one' s knowl edge r egar di ng 3d i n gener al .
Thi s t i me ar ound, I wi l l be expl ai ni ng t o you 2d and 3d
r ot at i ons. " 2D r ot at i on i n a 3d ar t i cl e?! ! ! Ar e you out of your
mi nd?! ! ! " Har dl y, i n f act , 2d r ot at i on i s t he basi s of 3d
r ot at i on as you wi l l know l at er . But bef or e I coul d di scuss
r ot at i ons t o you, l et me st ar t by some basi c i nt er medi at e and
t r i gonomet r i c mat h. Don' t wor r y, t hi s i s not as har d as you
mi ght t hi nk. So pr epar e your sel f f or some st r eet mat h. ; *)
II. The polar coordinate system

Up t o t hi s poi nt , we have used t he car t esi an coor di nat e syst em
i n 2d or i n 3d. Coor di nat es i n t hese syst ems ar e def i ned as
ei t her p( x, y) or p( x, y, z) .
I n t he pol ar coor di nat e syst emhowever , t he or der ed pai r i s not
r epr esent ed by x or y but of r and angl e or i gi nat i ng f r omt he
or i gi n or t he pol e, whi ch i s t he cent er of t he coor di nat e
syst em. Gi ven an angl e Thet a and a r adi us r t he or der ed pai r
woul d be wr i t t en as: p( r , t het a) .
r r epr esent s t he di st ance f r ompol e,
and t het a i s t he measur e of t he angl e f r omt he posi t i ve x- axi s.


So i n t he pol ar syst em, we onl y need t he l engt h( r ) ,
somet i mes cal l ed t he magni t ude, and t he angl e f r omt he posi t i ve
x- axi s. Why di scuss pol ar syst emwhen t he moni t or i s best sui t ed
f or a car t esi an syst em? The answer i s t hat some t hi ngs can be
easi l y done i n t he pol ar coor di nat e syst em. And one of t hose
t hi ngs i s " r ot at i on" ; *)
III. The basic trigonometric functions and their relationship to
the Polar and Cartesian systems...

Ther e ar e si x basi c t r i g f unct i ons. The si ne, cosi ne,
t angent , secant , cosecant , and t he cot angent . As of t he moment ,
we ar e i nt er est ed i n j ust 2, t he SINE and COSINE.



Say you have t he uni t ci r cl e above( a uni t ci r cl e i s a
ci r cl e havi ng a r adi us of 1) , wi t h an angl e( t het a) at 45
degr ees. I al r eady dr ew t he r i ght t r i angl e f or you l abel ed as Y
or O( Opposi t e si de) , X or A( adj acent si de) and r or
H( Hypot eneuse. I n Tr i gonomet r y, t her e i s a mnemoni c cal l ed t he
" SOH- CAH- TOA" whi ch r oughl y means:

SOH = Si n( Thet a) = Opposi t e/ Hypot eneuse
CAH = Cos( Thet a) = Adj acent / Hypot eneuse
TOA = Tan( Thet a) = Take a wi l d guess. : p

Tr ansl at i ng i t t o x, y and r . .

si n( t het a) =y/ r
cos( t het a) =x/ r

As I sai d we onl y need SI N and COS f or now.

Mul t i pl yi ng bot h si des by r . . .

r ( Si n( Thet a) = y/ r ) r
r ( Cos( Thet a) = x/ r ) r
=
r *( Si n( Thet a) = y
r *( Cos( Thet a) = x
=
EQ. 1
x = r * cos( Thet a)
EQ. 1- 1
y = r * si n( Thet a)

Si nce on a uni t ci r cl e r = 1 t hen

x = 1 * cos( Thet a)
y = 1 * si n( Thet a)
or
EQ. 2
x = cos( Thet a)
EQ. 2- 1
y = si n( Thet a)

By now you shoul d al r eady have r eal i zed t hat Si ne has
somet hi ng t o do wi t h t he y coor di nat e and Cosi ne t o t he x coor d.
; *)
Now how do we conver t f r ompol ar t o car t esi an? Easy, as
l ong as you know t he r adi us and t he angl e( t het a) j ust pl uck t he
val ues t o EQ' s 1 and 1- 1.
i e:

x = r * cos( Thet a)
y = r * si n( Thet a)
Pset ( x, y)

Her e' s and exampl e f i l e:
Pol Rot . Bas

To change f or mpol ar t o car t esi an:

r = Sqr ( x^2 + y^2)
Thet a = ATN( y/ x) ; x<>0

*These 2 would be useful later on but keep it on the
sidelines for now. ;*)
Bef or e f or get , al l t he ot her t r i g f unct i ons can be der i ved f r om
t he SI N and COS f unct i on.
Tan( a) = Si n( a) / Cos( a)
Sec( a) = 1/ Cos( a)
Csc( a) = 1/ Si n( a)
Cot ( a) = 1/ Tan( a) = Cos( a) / Si n( a)
IV. Degrees and Radians

Okay, t hi s i s ver y i mpor t ant so l i st en cl osel y. We, as
st udent s ar e used wi t h t he degr ee measur ement of angl es.
Pr obabl y because degr ees ar e easy t o vi sual i ze, so our t eacher s
and begi nner s mat h books use i t . But i t t ur ns out t hat comput er
l anguages, BASI C i ncl uded, cannot di r ect l y accept degr ee measur e
i n t hei r bui l t i n t r i g f unct i ons. Why? Fr ankl y, I don' t know.
Maybe because r adi ans i s an exact measur e or t he i mpl ement or s
j ust want t o be cool er . : *)
Now, si nce QB won' t l et you pass degr ees t o t hei r bui l t -
i n t r i g f unct i ons, and r adi ans i s somet i mes a pai n t o
i mpl ement ( due t o t he f act t hat i t ' s a smal l val ue) , we have t o
use degr ee measur ement and conver t i ng i t t o r adi an measur e
bef or e passi ng i t t o t he f unct i ons.
To conver t :

1. Degrees to Radians
Radi ans = Degr ees*PI / 180
2. Radians to Degrees
Degr ees = Radi ans*180/ PI

*PI is a value of the circumference of a circle divided
by its diameter. Its actual value is 3.141593...
Fun fact: Pi i s 180 degr ees. Guess what 2*PI i s? : *)
Fun fact: You can easi l y cal cul at e PI by PI =ATN( 1) *4


V. 2d Rotation

Usi ng t he pol ar syst emt o r ot at e a poi nt ar ound t he
cent er i s pr et t y easy. But how about r ot at i on f r omt he poi nt ' s
coor di nat e i t sel f ? Thi s i s wher e our 2d coor di nat e r ot at i on
comes f r om. Rot at i ng f r omp( x, y) t o p( x' , y' ) :



x' = x*cos( Thet a) - y*si n( Thet a)
y' = y*cos( Thet a) + x*si n( Thet a)
Wher e:
x = or i gi nal x coor d
y = or i gi nal y coor d
x' = r ot at ed x coor d
y' = r ot at ed y coor d

But how di d t hose equat i ons came about ? Most ar t i cl es
j ust smack you i nt o t hese equat i ons and never l ook back on how
t hose came t o be. I bet some of t hemdoesn' t know how t o der i ve
i t t hemsel ves. : *) . And because I ' mdi f f er ent , I wi l l t each you
how t hey came t o be. Mor eso, you coul d i mpr ess your f r i ends by
your geeki ness when you t el l t hemyou know. : *)

V-a. Proof on how the 2d rotation is derived.

Remember t hese equat i ons?
EQ. 1
x = r * cos( Thet a)
EQ. 1- 1
y = r * si n( Thet a)
Yep t hey ar e t he Pol ar t o Car t esi an coor di nat e syst em
conver si on. : *)
We al so need t he Angle addition identities



Legend:
P = Phi
T = Thet a

Cosine Identity:
EQ. 3
Cos( P+T) = Cos( P) *Cos( T) - Si n( P) *Si n( T)
Sine Identity:
EQ. 3- 1
Si n( P+T) = Si n( P) *Cos( T) +Cos( P) *Si n( T)

Let ( P+T) = Thet a( J ust one angl e) . . .
EQ. 1 becomes:
x = r * cos( P+T)
EQ. 1- 1
y = r * si n( P+T)

Then by subst i t ut i on f r omEQ 1 and 1- 1
EQ. 1 becomes:
x' = r * ( Cos( P) *Cos( T) - Si n( P) *Si n( T) )
EQ. 1- 1 becomes:
y' = r * ( Si n( P) *Cos( T) +Cos( P) *Si n( T) )

Di st r i but i ng r :

x' = r *Cos( P) *Cos( T) - r *Si n( P) *Si n( T)
y' = r *Si n( P) *Cos( T) + r *Cos( P) *Si n( T)

And l ooki ng back at EQ' s 1 and 1- 1:
Let P = Thet a. . .
x = r * cos( P)
y = r * si n( P)

Then by subst i t ut i on:

x' = x * Cos( T) - y * Si n( T)
y' = y * Cos( T) + x * Si n( T)

And Vi ol a! ! ! That ' s how you pr ove t he 2d r ot at i on f or mul a. ; *)

Final equations:

Newx=oldx*Cos(Theta) - oldy*Sin(Theta)
Newy=oldy*Cos(Theta) + oldx*Sin(Theta)

*Not e: Act ual l y, had I used EQ' s 2 and 2- 1, t he pr oof
woul d be much easi er si nce r i s al r eady r emoved. Though I
bel i eve t hat usi ng r f or ces you t o under st and t he concept behi nd
t he pr oof . So as an exer ci se, why don' t you t r y i t your sel f ? ; *)

I f you have under st ood al l t he st uf f t hat I have wr i t t en
f or mar t i cl e 1 up t o her e, you mi ght have al r eady guessed t hat
our st andar d 2d r ot at i on i s THE SAME AS ROTATI NG FROM THE Z-
AXI S. I f you di d, good. I f not , l ook agai n on t hi s f i gur e:



See, r ot at i ng f r omt he z- axi s r ot at es your poi nt on t he
XY pl ane. Her e' s t he code suppl ement whi ch added r ot at i ons t o
our pr evi ous st ar f i el d. Don' t get di zzy. : *)
Pr oj - r ot . Bas


VI. Let's go 3d!!!!

Remember when I sai d t hat 3d r ot at i on i s al most l i ke 2d
r ot at i on? Wel l , I ' mnot a man who br eaks my wor d. So l et me
begi n by sayi ng t hat si nce r ot at i on on t he z- axi s t akes on t he
xy pl ane and r ot at i on on t he x- axi s t akes on t he yz pl ane, wher e
do you t hi nk r ot at i on on t he y axi s t ake pl ace? Yes, t he xz
pl ane! . : *)
Now doi ng t hese r ot at i ons ar e pr et t y st r ai ght f or war d,
al l we have t o do i s smack t he needed val ues on our 2d r ot at i on
equat i on f or each axi s and we' r e good t o go. One t hi ng t o
r emember t hough i s "TO USE THE OLD VALUES UNTIL THE NEW ONES ARE
FOUND". Whi ch means f or a f ul l r ot at i on on al l t he axes, do not
di r ect l y put val ues unt i l t hey ar e f ul l y r ot at ed on t he axi s
t hat t hey ar e r ot at ed.

Her e' s t he f ul l 3d r ot at i on Equat i ons:
*Al l val ues ar e f l oat i ng poi nt number s

' ***Rot at i on on t he Z- axi s
NewY = y*cos( Thet ax) - z*si n( Thet ax)
NewZ = z*cos( Thet ax) + y*si n( Thet ax)
y = NewY
z = NewZ

' ***Rot at i on on t he Y- axi s
NewZ = z*cos( Thet ay) - x*si n( Thet ay)
NewX = x*cos( Thet ay) + z*si n( Thet ay)
x = NewX

' ***Rot at i on on t he Z- axi s
NewX = x*cos( Thet az) - y*si n( Thet az)
NewY = y*cos( Thet az) + x*si n( Thet az)

Rot at edx = NewX
Rot at edy = NewY
Rot at edz = NewZ

Your r ot at ed x/ y/ z ar e t he poi nt s compl et el y r ot at ed
over t he x, y and z axes. I had t o save t he r ot at ed val ues at
some poi nt t o make i t wor k or our r ot at i ons woul dn' t l ook r i ght .
: *) . I t s al so not abl e t hat "THE ORDER IN WHICH YOU ROTATE FROM
EACH AXIS IS VERY IMPORTANT". Rot at i ng i n z- x- y or der woul d not
pr oduce t he same r esul t as r ot at i ng i n t he x- y- z or der . I ' m
usi ng x- y- z because of t he al phabet . Act ual l y, Ki wi dog' s
r ot at i on i s i n x- y- z or der and si nce hi s ar t i cl e st ar t ed me wi t h
3d, I ' mwr i t i ng t hi s as a t r i but e t o hi m. As t hey say, " ol d
habi t s di e har d" . : *)

Si nce, QB' s i mpl ement at i on of t he FPU( The Fl oat i ng Poi nt
Uni t ) i s r eal l y cr ap, we coul d opt i mi ze t hi s by usi ng l ookup
t abl es or j ust cal cul at i ng some const ant s bef or e t he act ual
r ot at i on equat i ons.
i e.

QBcode:
cx! = COS(AngleX!)
sx! = SIN(AngleX!)
cy! = COS(AngleY!)
sy! = SIN(AngleY!)
cz! = COS(AngleZ!)
sz! = SIN(AngleZ!)

FOR i = 0 TO Maxpoints
x! = model(i).x
y! = model(i).y
z! = model(i).z

NewY! = (y! * cx!) - (z! * sx!)
NewZ! = (z! * cx!) + (y! * sx!)
y! = NewY!
z! = NewZ!
NewZ! = (z! * cy!) - (x! * sy!)
NewX! = (x! * cy!) + (z! * sy!)
x! = NewX!
NewX! = (x! * cz!) - (y! * sz!)
NewY! = (y! * cz!) + (x! * sz!)
Next i

Doi ng t hi s woul d speed your r ender a l ot . : *)
Her e' s an exampl e f i l e:
3dr ot . bas

Bef or e I f or get , t o t r ansl at e, subt r act cam( x, y, z) AFTER
r ot at i on. Unl ess, you' d want your r ot at i ons t o be of f - cent er .
Thi nk about when t o use ei t her . Heck, why don' t you t r y i t t o
see t he ef f ect s? : *)

However , t her e' s st i l l a f ast er way t o r ot at e. Not i ce
t he amount of mul t i pl i cat i on j ust t o t o do a f ul l 3 axi s
r ot at i on? Yep, 12 mul t i pl i es! I t t ur ns out t hat we can r educe
t hi s t o j ust 9! But how do we do i t ? Ei t her by usi ng mat r i ces or
weedi ng out const ant s usi ng st andar d al gebr a. Bot h met hods woul d
wor k wel l and woul d r oughl y pr oduce t he same r esul t . Same ni ne
mul t i pl i es, same amount of ar i t hmet i c. Though you coul d di r ect l y
t r ansl at e t he poi nt s usi ng t he 4t h r ow of a 4*4 mat r i x, we can
al so do i t by subt r act i ng our camer a val ue f r omt he r ot at ed
coor di nat e. And i f you l ook cl osel y ei t her t he mat r i x or t he
al gebr a met hod woul d pr oduce t he same const ant s. : *) *I wi l l
t ouch up on mat r i ces af t er t he t ext ur emappi ng ar t i cl e so don' t
wor r y. : *)

VII. From 12 to 9

Ther e ar e ot her ar t i cl es di scussi ng t hi s t ype of
opt i mi zat i on but sadl y, t he f i nal 3*3 mat r i x j ust does not
r ot at e r i ght . So i f you want t o der i ve a f i nal 3*3 mat r i x
your sel f f r omyour own r ot at i on or der , you have t o do i t
your sel f . : *)
BTW, t he const ant s we wi l l der i ve af t er t hi s i s a 3*3
r ot at i on mat r i x. We j ust di dn' t use t he mat r i x way but t he
al gebr a 101 way. : *)

So now l et ' s begi n t he headache.

Standard 12 mul rotation:

Let ox, oy, oz t he ol d coor ds

Let nx, ny, nz t he new r ot at ed coor ds

cx = cos( angl ex)
cy = cos( angl ey)
cz = cos( angl ez)

sx = si n( angl ex)
sy = si n( angl ey)
sz = si n( angl ez)

I ' mnumber i ng t he equat i ons f or easy r ef er enci ng l at er
so you won' t get l ost i n t he mess.

******
1. ny = oy*cx - oz*sx ' x axi s
2. nz = oz*cx + oy*sx

oy = ny
oz = nz

3. nz = oz*cy - ox*sy ' y axi s
4. nx = ox*cy + oz*sy

oy = ny
oz = nz

5. nx = ox*cz - oy*sz ' z axi s
6. ny = oy*cz + ox*sz

' ' ' Al l poi nt s r ot at ed ; *)

*****

*From 12 to 9 multiplies. We will simplify each axis equation
starting from the x axis. Not the numbers as they reference
equations from our original 12 mul rotation.

So. . .
Oz( 2) = Nz( 2)
= Nz = oz*cx + oy*sx

* I don't know if this would make sense to you but this I'm
trying to minimize the text for the actual math to be
understandable. ;*)

****For X axi s. . . .

nx( 4) = ox*cy+oz*sy ' or i g
nx( 4) = ox*cy+oz( 2) *sy

*l et ' s subst i t ut e nz( 2) t o oz
nx( 4) = ox*cy+[ oz*cx+oy*sx] *sy

*di st r i but e sy i nsi de nz( 2)
nx( 4) = ox*cy+oz*cx*sy+oy*sx*sy
nx( 5) = ox*cz- oy*sz ' or i g

*now subst i t ut e nx( 4) and ny( 1)
nx( 5) = [ ox*cy+oz*cx*sy+oy*sx*sy] *cz
- [ oy*cx- oz*sx] *sz

*di st r i but e cz and sz
nx( 5) = ox*cy*cz+oz*cx*sy*cz+oy*sx*sy*cz
- [ oy*cx*sz- oz*sx*sz]

*di st r i but e t he negat i ve si gn( - ) and r emove par ent hesi s.
(note the change of signs)
nx( 5) = ox*cy*cz+oz*cx*sy*cz+oy*sx*sy*cz
- oy*cx*sz+oz*sx*sz

*use t he commut at i ve pr oper t y of addi t i on t o r eor der t he t er ms
i n x+y+z or der .
nx( 5) = ox*cy*cz ' X
+ oy*sx*sy*cz - oy*cx*sz ' y
+ oz*cx*sy*cz + oz*sx*sz ' Z

*f act or out x, y and z
nx( 5) = ox*[ cy*cz] ' X
+ oy*[ sx*sy*cz - cx*sz] ' y
+ oz*[ cx*sy*cz + sx*sz] ' Z

*We al r eady have pr ecal cul at ed t he const ant s t o use( i nsi de
squar e br acket s) . Let ' s st or e ' em.

so. . .
xx = cy*cz
xy = sx*sy*cz - cx*sz
xz = cx*sy*cz + sx*sz

****For Y axi s. . .

ny( 6) = oy( 1) *cz + ox( 4) *sz
ny( 6) = [ oy*cx - oz*sx] *cz
+{ox*cy+[ oz*cx+oy*sx] *sy}*sz

*di st r i but e cz and sy
ny( 6) = oy*cx*cz - oz*sx*cz
+[ ox*cy+oz*cx*sy+oy*sx*sy] *sz
ny( 6) = oy*cx*cz - oz*sx*sy*cz
+ox*cy*sz + oz*cx*sy*sz + oy*sx*sy*sz

*Rear r ange i n x, y, z or der
ny( 6) = ox*cy*sz
+oy*cx*cz + oy*sx*sy*sz
- oz*sx*cz + oz*cx*sy*sz

*Fact or out x, y and z
ny( 6) = ox*cy*sz
+oy*cx*cz + oy*sx*sy*sz
- oz*sx*cz + oz*cx*sy*sz
ny( 6) = ox*[ cy*sz]
+oy*[ cx*cz + sx*sy*sz]
- oz*[ sx*cz + cx*sy*sz]

*oz has a ( - ) si gn. Make sx*cz negat i ve so t hat we coul d use
addi t i on.
ny( 6) = ox*[ cy*sz]
+oy*[ cx*cz + sx*sy*sz]
+oz*[ - sx*cz + cx*sy*sz]
' st or e. . .
yx = cy*sz
yy = cx*cz + sx*sy*sz
yz = -sx*cz + cx*sy*sz


****For Z axi s. . . ( easi est ! ! ! ! )
nz( 3) = oz( 2) *cy - ox*sy
*subst i t ut e nz( 2)
nz( 3) = [ oz*cx + oy*sx] *cy - ox*sy
*di st r i but e
nz( 3) = oz*cx*cy + oy*sx*cy - ox*sy
nz( 3) = - ox*sy + oy*sx*cy + oz*cx*cy

*make sy negat i ve as t o make ox posi t i ve
nz( 3) = ox*[ - sy] + oy*[ sx*cy] + oz*[ cx*cy]
zx = -sy
zy = sx*cy
zz = cx*cy

****Fi nal Pr ecal cul at ed const ant s! ! ! !
****Thi s i s our f i nal 3*3 Mat r i x.

' X axi s
xx = cy*cz
xy = sx*sy*cz - cx*sz
xz = cx*sy*cz + sx*sz

' Y axi s
yx = cy*sz
yy = cx*cz + sx*sy*sz
yz = -sx*cz + cx*sy*sz

' Z axi s
zx = -sy
zy = sx*cy
zz = cx*cy

We smack t he above const ant s down our
or i gi nal coor d and we get t he r ot at ed
coor d wi t hout much hassl e. Fast er and
si mpl er t oo! ! !

Fi nal Equat i ons! ! ! ! ( 9 mul s onl y)

nx = ox*xx + oy*xy + oz*xz
ny = ox*yx + oy*yy + oz*yz
nz = ox*zx + oy*zy + oz*zz


Speed i ncr ease may not be appar ent i f
you' r e j ust r ot at i ng a cube but t r y
t o r ot at e a 1000 pol ygon model and
you' l l see how much speed di f f er ence
t her e i s. ; *)

Her e' s a sampl e f i l e benchmar ki ng t hi s agai nst t he
st andar d 12 mul r ot at i on.

3dBench. bas

You mi ght want t o see what ' s i n st or e f or you on t he
next ar t i cl e. So her e i s j ust one( Two act ual l y) l i t t l e par t of
i t . : *)

3dwi r e. bas
Text ur e. Bas

Last l y, don' t l i mi t your sel f t o j ust poi nt s, you can use
spr i t es f or bet t er and cool er ef f ect s. : *)

vecbal l s. bas

Get your sel f a st r et chspr i t e r out i ne and you cammake
some even cool er st uf f ! ! !

st r et ch. bas

Fr omnow on I ' l l be usi ng t he 3*3 mat r i x const ant s as
opposed t o t he 12 mul r ot at i on so t hat our r ender s ar e a l ot
f ast er . And al so because i t wi l l not onl y be poi nt s t hat we wi l l
r ot at e l at er but VECTORS. : *) Ther e i s al so a bet t er way t o
r ot at e t han t hi s. I ' l l t ake i t up when we get t o mat r i ces. : *)


Now go ahead and code your sel f a 3d r ot at or even i f i t s
j ust a cube. Because next t i me I ' l l be di scussi ng t o you on how
t o gener at e 3d shapes t he mat h way and I ' l l t ouch up on pol ygons
so t hat you can f i l l your model s at r unt i me and i mpr ess your
f r i ends. I ' l l al so t ouch up on 2 mor e 3d coor di nat e syst ems. The
SPHERI CAL and CYLI NDRI CAL coor di nat e syst ems. : *) . So unt i l next
' i sh, Happy Codi ng! ! !

Cr edi t s:

Ki wi dog f or i nt r oduci ng me t o t he wor l d of 3d
Pl asma357 f or Set Vi deoSeg
SCM f or pr oof r eadi ng
Bi skbar t f or t he t essel at i on al go


Rel sof t 2003
vi c_vi per ph@yahoo. com
r el . phat code. net
Vectors are cool!!!
I t ' s al most i mpossi bl e t o do gr aphi cs pr ogr ammi ng wi t hout
usi ng vect or s. Al most al l mat h concer ni ng 3d codi ng use vect or s.
I f you hat e vect or s, r ead on and you' l l pr obabl y
l ove t hemmor e t han your gi r l f r i end af t er you' ve f i ni shed
r eadi ng t hi s ar t i cl e. ; *)

What are vectors?

Fi r st of f , l et me def i ne 2 quant i t i es: The SCALAR and VECTOR
quant i t i es. Okay, scal ar quant i t i es ar e j ust val ues. One exampl e
of i t i s Temper at ur e. You say, " I t ' s 40 degr ees Cel si us her e" ,
and t hat ' s i t . No sense of di r ect i on. But t o def i ne a vect or you
need a di r ect i on or sense. Li ke when t he pi l ot say' s, " We ar e 40
ki l omet er s nor t h of Mi dway" . So a scal ar quant i t y i s j ust a
val ue whi l e a vect or i s a val ue + di r ect i on.

Look at t he f i gur e bel ow: The arrow(Ray) r epr esent s a
vect or . The " Head" i s i t s "Sense"( di r ect i on i s not appl i cabl e
her e) and t he " Tai l " i s i t s st ar t i ng poi nt . The di st ance f r om
head t o t ai l i s cal l ed i t s " magni t ude" .




I n t hi s vect or t her e ar e 2 component s, t he X and Y
component . X i s t he hor i zont al and Y i s t he ver t i cal component .
Remember t hat "ALL VECTOR OPERATIONS ARE DONE WITH ITS
COMPONENTS."

I l i ke t o set up my vect or s i n t hi s TYPE:

Type Vector
x as single
y as single
End TYPE

The difference between the "sense" and "direction" is that
direction is the line the vector is located while sense can go
either way on that line.


Definitions:

*|v| means that |v| is the magnitude of v.

*Orthogonal vectors are vectors perpendicular to each other.
It's sticks up 90 degrees.




To get a vect or bet ween 2 poi nt s:

2d:
v = (x2 - x1) + (y2 - y1)
3d:
v = (x2 - x1) + (y2 - y1) + (z2 - z1)

QBcode:
vx = x2 - x1
vy = y2 - y1
vz = z2 - z1

wher e: ( x2- x1) i s t he hor i zont al component and so on.

Vect or s ar e not l i mi t ed t o t he car t esi an coor di nat e syst em.

I n pol ar f or m:

v = r * theta



Resolving a vector by its components


Suppose a vect or v has a magni t ude 5 and di r ect i on gi ven by
Thet a = 30 degr ees. Wher e t het a i s t he angl e t he vect or makes
wi t h t he posi t i ve x- axi s. How do we r esol ve t hi s vect or s'
component s?


Remember t he Pol ar t o Car t esi an conver si on?

v.x = cos(theta)
v.y = sin(theta)

Let vx = hor i zont al component
Let vy = hor i zont al component
Let Thet a = Be t he angl e

So. . .
v.x = |v| * cos(theta)
v.x = 5 * cos(30)
v.x = 4.33

v.y = |v| * sin(theta)
v.y = 5 * sin(30)
v.y = 2.50


What I ' ve been showi ng you i s a 2d vect or . Maki ng a 3d
vect or i s j ust addi ng anot her component , t he Z component .

Type Vector
x as single
y as single
z as single
End TYPE



Operations on vectors needed in 3d engines

1. Scaling a vector(Scalar multiplication)

Pur pose:
Thi s i s used t o scal e a vect or by a scal ar val ue. Needed
i n t he scal i ng of model s and changi ng t he vel oci t y of
pr oj ect i l es.

I n equat i on:
v = v * scale
I n qbcode:
v.x = v.x * Scale
v.y = v.y * Scale
v.z = v.z * Scale

2. Getting the Magnitude(Length) of a vector

Pur pose:
Used i n "Normalizing"( maki ng i t a uni t vect or ) a vect or . Mor e
on t hi s l at er .

Equat i on:
|V| = Sqr(v.x^2 + v.y^2 + v.z^2)

QBcode:
Mag! = Sqr(v.x^2 + v.y^2 + v.z^2)

3. Normalizing a vector

Pur pose:
Used i n l i ght sour ci ng, camer a t r ansf or ms, et c. Makes
t he vect or a "unit-vector" t hat i s a vect or havi ng a magni t ude
of 1. Di vi des t he vect or by i t s l engt h.

Equ:
v = v
-------
|v|

QBCode:
Mag! = Sqr(v.x^2 + v.y^2 + v.z^2)
v.x = v.x / mag!
v.y = v.y / mag!
v.z = v.z / mag!

4. The DOT Product

Pur pose:
Used i n many t hi ngs l i ke l i ght sour ci ng and vect or
pr oj ect i on. Ret ur ns t he cosi ne of t he angl e bet ween any t wo
vect or s ( Assumi ng t he vect or s ar e Nor mal i zed) . A Scal ar .
The dot pr oduct i s al so cal l ed t he " Scal ar " pr oduct .

Equ:
v.w = v.x* w.x + v.y* w.y + v.z* w.z

QBCode:
Dot! = v.x* w.x + v.y* w.y + v.z* w.z

Fun f act :
* 2 Vectors are orthogonal if their dot product is 0.
Proof: "What is the cosine of 90?"


5. The CROSS product

Pur pose:
Used i n l i ght sour ci ng, camer a t r ansf or mat i on, back- f ace
cul l i ng, et c. The cr oss pr oduct of 2 vect or s r et ur ns anot her
vect or t hat i s or t hogonal t o t he pl ane t hat has t he f i r st 2
vect or s. Let ' s say we have vect or s U and F.

Equ:
U x F = R

QB code:
R.x = U.y * F.z - F.y * U.z
R.y = U.z * F.x - F.z * U.x
R.z = U.x * F.y - F.x * U.y

Fun f act s:
* C is the vector orthogonal to A and B.
* C is the NORMAL to the plane that includes A and B. The
cross-product of any two vectors can best be remembered by the
CRAMERS RULE on DETERMINANTS. Thought of it while taking a
bath. I'll tell you when I finish my matrix chapter.
* The cross product is exclusive to 3d and its also called the
"Vector" product.


6. Vector Projection

Pur pose:
Used i n r esol vi ng t he second vect or of t he camer a mat r i x
( Thanks Toshi ! ) . For vect or s A and B. . .



Equ:
U.Z * Z

QB code:
Let N = vect or pr oj ect i on of U t o Z. The vect or par al l el t o Z.

T! = Vector.Dot(U, Z)

N.x = T! * Z.x
N.y = T! * Z.y
N.z = T! * Z.z


7. Adding vectors
Pur pose:

Used i n camer a and obj ect movement s. Anyt hi ng t hat you' d
want t o move r el at i ve t o your camer a. Addi ng vect or s i s j ust
t he same as addi ng t hei r component s. Let A and B be vect or s i n
3d, and C i s t he sum:
Equ:
C = A + B
C = (ax + bx) + (ay + by) + (az + bz)

QBcode:
c.x = a.x + b.x
c.y = a.y + b.y
c.z = a.z + b.z

Now t hat Most of t he Mat h i s out of t he way. . . .


Applications

I. WireFraming and BackFace culling

I l i ke t o make use of t ypes wi t h my 3d engi nes.
For Pol ygons:

Type Poly
p1 as integer
p2 as integer
p3 as integer
end type

P1 i s t he f i r st ver t ex, p2 second and p3 t hi r d. Let ' s say
you have a ni ce r ot at i ng cube composed of poi nt s, l ooks spi f f y
but you want i t t o be composed of pol ygons( Tr i angl es) i n t hi s
case) . I f we have a cube wi t h ver t i ces:

Vtx1 50, 50, 50 :x,y,z
Vtx2 -50, 50, 50
Vtx3 -50,-50, 50
Vtx4 50,-50, 50
Vtx5 50, 50,-50
Vtx6 -50, 50,-50
Vtx7 -50,-50,-50
Vtx8 50,-50,-50

What we need ar e connect i on poi nt s t hat def i ne a f ace. The
one bel ow i s a Quadr i l at er al f ace( 4 poi nt s)
Face1 1, 2, 3, 4
Face2 2, 6, 7, 3
Face3 6, 5, 8, 7
Face4 5, 1, 4, 8
Face5 5, 6, 2, 1
Face6 4, 3, 7, 8

Face1 woul d have ver t ex 1, 2, and 3 as i t s connect i on
ver t i ces.

Now si nce we want t r i angl es i nst ead of quads, we di vi de each
quad i nt o 2 t r i angl es, whi ch woul d make 12 f aces. I t ' al so
i mper at i ve t o ar r ange your poi nt s i n count er - cl ockwi se or
cl ockwi se or der so t hat backf ace cul l i ng woul d wor k. I n t hi s
case I ' musi ng count er - cl ockwi se.

The f ol l owi ng code di vi de t he quads i nt o 2 t r i angl es wi t h
ver t i ces ar r anged i n count er - cl ocki se or der . Tr i ( j ) . i dx wi l l be
used f or sor t i ng.

QBcode:
j = 1
FOR i = 1 TO 6
READ p1, p2, p3, p4 'Reads the face(Quad)
Tri(j).p1 = p1
Tri(j).p2 = p2
Tri(j).p3 = p4
Tri(j).idx = j
j = j + 1
Tri(j).p1 = p2
Tri(j).p2 = p3
Tri(j).p3 = p4
Tri(j).idx = j
j = j + 1
NEXT i

To r ender t he cube wi t hout backf ace cul l i ng, her e' s t he
pseudocode:

1. Do
2. Rotatepoints
3. Project points
4. Sort(Not needed for cubes and other simple polyhedrons)
5. Get Triangles' projected coords
ie.
x1 = Model(Tri(i).P1).ScreenX
y1 = Model(Tri(i).P1).ScreenY
x2 = Model(Tri(i).P2).ScreenX
y2 = Model(Tri(i).P2).ScreenY
x3 = Model(Tri(i).P3).ScreenX
y3 = Model(Tri(i).P3).ScreenY
6. Draw
Tri x1,y1,x2,y2,x3,y3,color

BackFace Culling

Backf ace cul l i ng i s al so cal l ed "Hidden face removal". I n
essense, i t ' s a way t o speed up your r out i nes by NOT showi ng a
pol ygon i f i t ' s not f aci ng t owar ds you. But how do we know what
f ace of t he pol ygon i s t he " r i ght " f ace? Let ' s t ake a CD as an
exampl e, t her e ar e 2 si des t o a par t i cul ar CD. One si de t hat t he
dat a i s t o be wr i t t en and t he ot her si de wher e t he l abel i s
pr i nt ed. What i f we deci de t hat t he Label - si de shoul d be t he
r i ght si de? How do we do i t ? Wel l i t t ur ns out t hat t he answer
i s our wel l l oved NORMAL. : *) But f or t hat t o wor k, we shoul d
*sequent i al l y* ar r ange our ver t i ces i n count er or cl ockwi se
or der .
I f you ar r anged your pol ys' ver t i ces i n count er - cl ockwi se
or der as most 3d model er s do, you j ust get t he pr oj ect ed z-
nor mal of t he
pol y and check i f i t s gr eat er t han( >) 0. I f i t i s, t hen dr aw
t r i angl e. Of cour se i f you ar r anged t he ver t i ces i n cl ockwi se
or der , t hen t he pol y i s f aci ng us when t he Z- nor mal i s <0.
Counter-Clockwise arrangement of vertices:


Clockwise Arrangement of vertices:


Si nce we onl y need t he z component of t he nor mal t o t he
pol y, we coul d even use t he " pr oj ect ed" coor ds( 2d) t o get t he z
component !

QBcode:
Znormal = (x2 - x1) * (y1 - Y3) - (y2 - y1) * (x1 - X3)
IF (Znormal > 0) THEN '>0 so vector facing us
Drawpoly x1,y1,x2,y2,x3,y3
end if

Her e' s t he exampl e f i l e:

3dwire.bas


Sorting

Ther e ar e numer ous sor t i ng t echni ques t hat I use i n my 3d
r ender s her e ar e t he most common:
1. Bubble sort (modified)
2. Shell sort
3. Quick sort
4. Blitz sort (PS1 uses this according to Blitz)

I won' t go about expl ai ni ng how t he sor t i ng al gor i t hms wor k.
I ' mher e t o di scuss how t o i mpl ement i t i n your engi ne. I t may
not be appar ent t o you ( si nce you ar e r ot at i ng a
si mpl e cube) but you need t o sor t your pol ys t o make your
r ender s l ook r i ght . The i dea i s t o dr aw t he f ar t hest pol ys f i r st
and t he near est l ast . Bef or e we coul d go about sor t i ng
our pol ys we need a new el ement i n our pol yt ype.

Type Poly
p1 as integer
p2 as integer
p3 as integer
idx as integer
zcenter as integer
end type

*Idx would be the index we use to sort the polys. We sort via
IDX, not by subscript.
*Zcenter is the theoretical center of the polygon. It's a 3d
coord (x,y,z)

To get t he cent er of any pol ygon or pol yhedr a( model ) , you add
al l t he 3 coor di nat es and di vi de i t by t he number of ver t i ces( I n
t hi s case 3) .

Si nce we onl y want t o get t he z cent er :

QBcode:
Zcenter= Model(Poly(i).p1)).z + Model(Poly(i).p2)).z +
Model(Poly(i).p3)).z
Zcenter = Zcenter/3


Opt i mi zat i on t r i ck:
We don' t r eal l y need t o f i nd t he *r eal * Zcent er si nce al l
t he z val ues t hat wer e added ar e goi ng t o be st i l l sor t ed
r i ght . Whi ch means. . . No di vi de! ! !

Now you sor t t he pol ys l i ke t hi s:

QBcode:
FOR i% = Lbound(Poly) TO UBOUND(Poly)
Poly(i%).zcenter = Model(Poly(i%).p1).Zr + Model(Poly(i%).p2).Zr +
Model(Poly(i%).p3).Zr
Poly(i%).idx = i%
NEXT i%

Shellsort Poly(), Lbound(Poly), UBOUND(Poly)

To Dr aw t he model , you use t he i ndex( Pol y. i dx)

QBcode:
FOR i = 1 TO UBOUND(Poly)
j = Poly(i).idx
x1 = Model(Poly(j).p1).scrx 'Get triangles from "projected"
x2 = Model(Poly(j).p2).scrx 'X and Y coords since Znormal
x3 = Model(Poly(j).p3).scrx 'Does not require a Z coord
y1 = Model(Poly(j).p1).scry
y2 = Model(Poly(j).p2).scry
y3 = Model(Poly(j).p3).scry

'Use the Znormal,the Ray perpendicular(Orthogonal) to the
'Screen defined by the Triangle (X1,Y1,X2,Y2,X3,Y3)
'if Less(>) 0 then its facing in the opposite direction so
'don't plot. If <0 then its facing towards you so Plot.

Znormal = (x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3)
IF Znormal < 0 THEN
DrawTri x1,y1,x2,y2,x3,y3
END IF
NEXT i



Her e' s a wor ki ng exampl e:

Sorting.Bas


II. Spherical and cylindrical coordinate systems.

These 2 syst ems ar e ext ent i ons of t he pol ar coor di nat e
syst em. Wher e pol ar i s 2d t hese 2 ar e 3d. : *)

a. Cylindrical coordinate system

The cyl i ndr i cal coodi nat e syst emi s usef ul i f you want t o
gener at e model s mat hemat i cal l y. Some exampl es ar e Hel i xi s,
Cyl i nder s( of cour se) , t unnel s or any t ube- l i ke model . Thi s
syst emwor ks much l i ke 2d, but wi t h an added z component t hat
doesn' t need and angl e. Her e' s t he equat i ons t o conver t
cyl i ndr i cal t o r ect angul ar coor di nat e syst em.

Her e' s t he Cyl i ndr i cal t o r ect angul ar coor di nat e conver si on
equat i ons. Al most l i ke 2d. Of cour se t hi s cyl i nder wi l l coi l on
t he z axi s. To t est your sel f , why dont you change
t he equat i ons t o coi l i t on t he y axi s?

x = COS(theta)
y = SIN(theta)
z = z

To gener at e a cyl i nder :

QBcode:
i = 0
z! = zdist * Slices / 2
FOR Slice = 0 TO Slices - 1
FOR Band = 0 TO Bands - 1
Theta! = (2 * PI / Bands) * Band
Model(i).x = radius * COS(Theta!)
Model(i).y = radius * SIN(Theta!)
Model(i).z = -z!
i = i + 1
NEXT Band
z! = z! - zdist
NEXT Slice


Her e' s a 9 l i ner I made usi ng t hat equat i on.

9Liner.Bas

b. Spherical coordinate system

Thi s i s anot her usef ul syst em. I t can be used f or Tor us and
Spher e gener at i on. Her e' s t he conver si on:
x = SIN(Phi)* COS(theta)
y = SIN(Phi)* SIN(theta)
z = COS(Phi)
Wher e: Thet a = Azi mut h ; Phi = El evat i on

To gener at e a spher e:
QBcode:
i = 0
FOR SliceLoop = 0 TO Slices - 1
Phi! = PI / Slices * SliceLoop
FOR BandLoop = 0 TO Bands - 1
Theta! = 2 * -PI / Bands * BandLoop
Model(i).x = -INT(radius * SIN(Phi!) * COS(Theta!))
Model(i).y = -INT(radius * SIN(Phi!) * SIN(Theta!))
Model(i).z = -INT(radius * COS(Phi!))
i = i + 1
NEXT BandLoop
NEXT SliceLoop

Her e' s a l i t t l e par t i cl e engi ne usi ng t he spher i cal
coor di nat e syst em.
Fountain.bas
Her e' s an exampl e f i l e t o gener at e model s usi ng t hose
equat i ons:

Gen3d.Bas


III. Different Polygon fillers

A. Flat Filler
Ti r ed of j ust wi r ef r ame and pi xel s? Af t er maki ng a wi r ef r ame
demo, you' d want your obj ect s t o be sol i d. The f i r st t ype of
f i l l t hat I ' l l be i nt r oduci ng i s a f l at t r i angl e f i l l er . What ?!
But I coul d use PAI NT t o do t hat ! Wel l , you st i l l have t o
under st and how t he f l at f i l l er wor ks because t he gour aud and
t ext ur e f i l l er wi l l be based on i t . ; *)
Now how do we make a f l at f i l l er ? Let me i nt r oduce you f i r st
t o t he i dea of LINEAR INTERPOLATION. How does i nt er pol at i on
wor k? Let ' s say you want t o make dot on t he
scr een at l ocat i on ( x1, y1) t o ( x2, y2) i n 10 st eps?

Let A = (x1,y1)
B = (x2,y2)
Steps = 10

f(x) = (B-A)/Steps

So. . . .

QBcode:
dx! = (x2-x1)/steps
dy! = (y2-y1)/Steps

x! = x1
y! = y1
For a = 0 to steps - 1
Pset(x,y), 15
x! = x! + dx!
y! = y! + dy!
next a

That ' s al l t o t her e i s t o i nt er pol at i on. : *)

Now t hat we have an i dea of what l i near i nt er pol at i on i s we
coul d make a f l at t r i angl e f i l l er .

The 3 types of triangle
A. Flat Filled

1. Flat Bottom


2. Flat Top


3. Generic Triangle



I n bot h t he Fl at Top and Fl at bot t omcases, i t ' s easy t o do
bot h t r i angl es as we onl y need t o i nt er pol at e A t o B and A t o
C i n Y st eps. We dr aw a hor i zont al l i ne i n bet ween ( x1, y) and
( x2, y) .
The pr obl eml i es when we want t o dr aw a gener i c t r i angl e
si nce we don' t know i f i t ' s a f l at t op or f l at bot t om. But i t
t ur ns out t hat t her e i s an al l t oo easy way t o get ar ound wi t h
t hi s. Anal yzi ng t he gener i c t r i angl e, we coul d j ust di vi de t he
t r i angl e i nt o 2 t r i angl es. One Fl at Bot t omand One Fl at Top!
We dr aw i t wi t h 2 l oops. The f i r st l oop i s t o dr aw t he Fl at
Bot t omand t he second l oop i s f or t he Fl at Top.


PseudoCode:
TOP PART ONLY! ! ! ! ( FLAT BOTTOM)
1. I nt er pol at e a.x and dr aw each scanl i ne f r oma.x t o b.x i n
(b.y-a.y) st eps.
ie. a.x = x3 - x1
b.x = y3 - y1
Xstep1! = a.x / b.x
2. I nt er pol at e a.x and dr aw each scanl i ne f r oma.x t o c. x i n
(c.y-a.y) st eps.
ie. a.x = x1 - x3
c.x = y1 - y3
Xstep3! = a.x / c.x
3. Dr aw each scanl i ne( Hor i zont al l i ne) f r oma.y t o b.y
i ncr ement i ng y wi t h one i n each st ep, i nt er pol at i ng LeftX wi t h
Xstep1! and RightX wi t h Xstep3!. You' ve j ust f i ni shed dr awi ng
t he TOP par t of t he t r i angl e! ! !
4. Do t he same wi t h t he bot t om- hal f i nt er pol at i ng f r omb.x t o
c.x i n b.y st eps.
PseudoCode:
1. Sort Vertices
IF y2 < y1 THEN
SWAP y1, y2
SWAP x1, x2
END IF
IF y3 < y1 THEN
SWAP y3, y1
SWAP x3, x1
END IF
IF y3 < y2 THEN
SWAP y3, y2
SWAP x3, x2
END IF


2. Interpolate A to B
dx1 = x2 - x1
dy1 = y2 - y1
IF dy1 <> 0 THEN
Xstep1! = dx1 / dy1
ELSE
Xstep1! = 0
END IF

3. Interpolate B to C
dx2 = x3 - x2
dy2 = y3 - y2
IF dy2 <> 0 THEN
Xstep2! = dx2 / dy2
ELSE
Xstep2! = 0
END IF

4. InterPolate A to C
dx3 = x1 - x3
dy3 = y1 - y3
IF dy3 <> 0 THEN
Xstep3! = dx3 / dy3
ELSE
Xstep3! = 0
END IF

5. Draw Top Part
Lx! = x1 'Starting coords
Rx! = x1

FOR y = y1 TO y2 - 1
LINE (Lx!, y)-(Rx!, y), clr
Lx! = Lx! + Xstep1! 'increment derivatives
Rx! = Rx! + Xstep3!
NEXT y

6. Draw Lower Part

Lx! = x2
FOR y = y2 TO y3
LINE (Lx!, y)-(Rx!, y), clr
Lx! = Lx! + delta2!
Rx! = Rx! + delta3!
NEXT y

Her e' s an exampl e f i l e:
FlatTri.bas

B. Gouraud Filled
Ther e i s not t hat much di f f er ence bet ween t he f l at
t r i angl e and t he gour aud t r i angl e. I n t he cal l i ng sub, i nst ead
of j ust t he 3 coodi nat es, t her e ar e 3 par ament er s mor e. Namel y:
c1,c2,c3. They ar e t he col or s we coul d want t o i nt er pol at e
bet ween ver t i ces. And si nce you know how t o i nt er pol at e al r eady,
i t woul d not be a pr obl em. : *)
Fi r st we need a hor i zont al l i ne r out i ne t hat dr aws wi t h
i nt er pol at ed col or s. Her e' s t he code. I t ' s sel f expl anat or y.
*dc! i s t he Col or St ep( Li ke t he Xst eps)
QBcode:
HlineG (x1,x2,y,c1,c2)

dc! = (c2 - c1)/ (x2 - x1)
c! = c1
For x = x1 to x2
Pset(x , y) , int(c!)
c! = c! + dc!
next x
Now t hat we have a hor i zont al gour aud l i ne, we wi l l modi f y
some code i nt o our f l at f i l l er t o make i t a gour aud f i l l er . I
won' t gi ve you t he whol e code, but some i mpor t ant sni ppet s.
1. In the sorting stuff: (You have to do this to all the IF's.
IF y2 < y1 THEN
SWAP y1, y2
SWAP x1, x2
SWAP c1, c2
END IF

2. Interpolate A to B; c1 to c2. do this to all vertices.

dx1 = x2 - x1
dy1 = y2 - y1
dc1 = c2 - c1
IF dy1 <> 0 THEN
Xstep1! = dx1 / dy1
Cstep1! = dc1 / dy1
ELSE
Xstep1! = 0
Cstep1! = 0
END IF
5. Draw Top Part

Lx! = x1 'Starting coords
Rx! = x1
Lc! = c1 'Starting colors
Rc! = c1

FOR y = y1 TO y2 - 1
HlineG Lx!, Rx!, y, Lc!, Rc!
Lx! = Lx! + Xstep1!
Rx! = Rx! + Xstep3!
Lc! = Lc! + Cstep1! 'Colors
Rc! = Rc! + Cstep3!
NEXT y
I t ' s t hat easy! You have t o i nt er pol at e j ust 3 mor e
val ues! Her e' s t he compl et e exampl e f i l e:
GourTri.Bas

C. Affine Texture Mapped
Agai n, t her e i s not much di f f er ence bet ween t he pr evi ous 2
t r i angl e r out i nes f r omt hi s. Af f i ne t ext ur emappi ng al so
i nvol ves t he same al go as t hat of t he f l at f i l l er . That i s,
Li near i nt er pol at i on. That ' s pr obabl y why i t doesn' t l ook good.
: *( But i t ' s f ast . : *) . I f i n t he gour aud f i l l er you need t o
i nt er pol at e bet ween 3 colors, you need t o i nt er pol at e bet ween 3
U and 3 V t ext ur e coor di nat es i n t he af f i ne mapper . That ' s 6
val ues i n al l . I n f act , i t ' s al most t he same as gour aud
f i l l er !


Now we have t o modi f y our Gour aud Hor i zont al l i ne r out i ne
t o a t ext ur ed l i ne r out i ne.
*This assumes that the texture size is square and a power of 2.
Ie. 4*4, 16*16, 128*128,etc. And is used to prevent from reading
pixels outside the texture.
*The texture mapper assumes a QB GET/PUT compatible image.
Array(1) = width*8; Array(2) = Height; Array(3) = 2 pixels.
* HlineT also assumes that a DEF SEG = Varseg(Array(0)) has been
issued prior to the call. TOFF is the Offset of the image in
multiple image arrays. ie: TOFF = VARPTR(Array(0))
*TsizeMinus1 is Texturesize -1.

QBcode:
HlineT (x1,x2,y,u1,u2,v1,v2,Tsize)

du! = (u2 - u1)/ (x2 - x1)
dv! = (v2 - v1)/ (x2 - x1)
u! = u1
v! = v1
TsizeMinus1 = Tsize - 1

For x = x1 to x2

'get pixel off the texture using
'direct memory read. The (+4 + TOFF)
'is used to compensate for image
'offsetting.
Tu=u! AND TsizeMinus1
Tv=v! AND TsizeMinus1
Texel = Peek(Tu*Tsize + Tv + 4 + TOFF)
Pset(x , y) , Texel
u! = u! + du!
v! = v! + dv!
next x
Now we have t o modi f y t he r ast er r i zer t o suppor t U and V
coor ds. Al l we have t o do i s i nt er pol at e bet ween al l t he coor ds
and we' r e good t o go.
1. In the sorting stuff: (You have to do this to all the IF's.
IF y2 < y1 THEN
SWAP y1, y2
SWAP x1, x2
SWAP u1, u2
SWAP v1, v2
END IF

2. Interpolate A to B; u1 to u2; v1 to v2. Do this to all
vertices.

dx1 = x2 - x1
dy1 = y2 - y1
du1 = u2 - u1
dv1 = v2 - v1
IF dy1 <> 0 THEN
Xstep1! = dx1 / dy1
Ustep1! = du1 / dy1
Vstep1! = dv1 / dy1
ELSE
Xstep1! = 0
Ustep1! = 0
Vstep1! = 0
END IF
5. Draw Top Part

Lx! = x1 'Starting coords
Rx! = x1
Lu! = u1 'Starting U
Ru! = u1
Lv! = v1 'Starting V
Rv! = v1

FOR y = y1 TO y2 - 1
HlineT Lx!, Rx!, y, Lu!, Ru!, Lv!, Rv!
Lx! = Lx! + Xstep1!
Rx! = Rx! + Xstep3!
Lu! = Lu! + Ustep1! 'U
Ru! = Ru! + Ustep3!
Lv! = Lv! + Vstep1! 'V
Rv! = Rv! + Vstep3!
NEXT y
Her e' s t he exampl e demo f or you t o l ear n f r om. Be sur e t o
check t he al go as i t uses f i xpoi nt mat h t o speed t hi ngs up qui t e
a bi t . : *)
Textri.bas

IV. Shading and Mapping Techniques

1. Lambert Shading

So you want your cube f i l l ed and l i ght sour ced, but don' t
know how t o? The answer i s Lamber t Shadi ng. And what does
Lamber t shadi ng use? The NORMAL. Yes, i t ' s t he cr oss- pr oduct
t hi ngy I was wr i t i ng about . How do we use t he nor mal you say.
Fi r st , you have a f i l l ed cube composed of t r i angl es ( Pol ys) , now
we def i ne a vect or or t hogonal t o t hat pl ane( Yep, t he Nor mal )
st i cki ng out .
How do we cal cul at e nor mal s? Easy, use t he cr oss pr oduct !

PseudoCode:
1. For each poly..
2. get poly's x, y and z coords
3. define vectors from 3 coords
4. get the cross-product(our normal to a plane)
5. Normalize your normal

QBcode:
FOR i = 1 TO UBOUND(Poly)
P1 = Poly(i).P1 'get poly vertex
P2 = Poly(i).P2
P3 = Poly(i).P3
x1 = Model(P1).x 'get coords
x2 = Model(P2).x
x3 = Model(P3).x
y1 = Model(P1).y
y2 = Model(P2).y
y3 = Model(P3).y
Z1 = Model(P1).z
Z2 = Model(P2).z
Z3 = Model(P3).z

ax! = x2 - x1 'derive vectors
bx! = x3 - x2
ay! = y2 - y1
by! = y3 - y2
az! = Z2 - Z1
bz! = Z3 - Z2

'Cross product
xnormal! = ay! * bz! - az! * by!
ynormal! = az! * bx! - ax! * bz!
znormal! = ax! * by! - ay! * bx!

'Normalize
Mag! = SQR(xnormal! ^ 2 + ynormal! ^ 2 + znormal! ^ 2)
IF Mag! <> 0 THEN
xnormal! = xnormal! / Mag!
ynormal! = ynormal! / Mag!
znormal! = znormal! / Mag!
END IF


v(i).x = xnormal! 'this is our face normal
v(i).y = ynormal!
v(i).z = znormal!

NEXT i

Q: "You expect me to do this is real-time?!!!" "That square-
root alone would make my renders slow as hell!!"
A: No. You only need to do this when setting up your renders.
ie. Only do this once, and at the top of your proggie.

Now t hat we have our nor mal , we def i ne a l i ght sour ce. Your
l i ght sour ce i s al so a vect or . Be sur e t hat bot h vect or s
ar e nor mal i zed.

i e.
Light.x\
Light.y > The light vector
Light.z/

Polynormal.x\
Polynormal.y > The Plane normal
Polynormal.z/


The angl e i n t he pi c i s t he incident angle bet ween t he l i ght
and t he pl ane nor mal . t he angle is inversely proportional to
the intensity of light. So t he l esser t he angl e, t he mor e
i nt ense t he l i ght . But how do we get t he i nt ensi t y?
For t unat el y, t her e i s an easy way t o cal cul at e t he l i ght . Al l
we have t o do i s get t he Dot pr oduct bet ween t hese vect or s! ! !
Si nce t he dot r et ur ns a scal ar val ue , Cosi ne( angl e) , we can get
t he br i ght ness f act or by j ust mul t i pl yi ng t he Dot
pr oduct by t he col or r ange! ! ! I n scr een 13: Dot *255.

QBCode:
nx! = PolyNormal.x
ny! = PolyNormal.y
nz! = PolyNormal.z
lx! = LightNormal.x
ly! = LightNormal.y
lz! = LightNormal.z
Dot! = (nx! * lx!) + (ny! * ly!) + (nz! * lz!)
IF Dot! < 0 then Dot! = 0
Clr = Dot! * 255
FlatTri x1, y1, x2, y2, x3, y3, Clr
end if


Her e' s an exampl e f i l e i n act i on:

Lambert.Bas

2. Gouraud Shading

Af t er t he l amber t shadi ng, we pr ogr ess i nt o gour aud
shadi ng. Q: But how do we f i nd a nor mal t o a poi nt ? A: You
can' t . Ther e i s no nor mal t o a poi nt . The cr oss- pr oduct i s
excl usi ve t o pl anes( 3d) so you j ust can' t . You don' t have t o
wor r y t hough, as t her e ar e ways ar ound t hi s pr obl em.
What we need t o do i s t o f i nd adj acent f aces t hat t he ver t ex
i s l ocat ed and aver age t hei r face normals. I t ' s an
appr oxi mat i on but i t wor ks!
Let : V( ) = Face nor mal ; V2( ) ver t exnor mal
QBcode:
FOR i = 1 TO Numvertex
xnormal! = 0
ynormal! = 0
znormal! = 0
FaceFound = 0
FOR j = 0 TO UBOUND(Poly)
IF Poly(j).P1 = i OR Poly(j).P2 = i OR Poly(j).P3 = i THEN
xnormal! = xnormal! + v(j).x
ynormal! = ynormal! + v(j).y
znormal! = znormal! + v(j).z
FaceFound = FaceFound + 1 'Face adjacent
END IF
NEXT j
xnormal! = xnormal! / FaceFound
ynormal! = ynormal! / FaceFound
znormal! = znormal! / FaceFound
v2(i).x = xnormal! 'Final vertex normal
v2(i).y = ynormal!
v2(i).z = znormal!
NEXT i
Now t hat you have cal cul at ed t he ver t ex nor mal s, you onl y
have t o pass t he r ot at ed ver t ex nor mal s i nt o our gour aud
f i l l er ! ! ! i e. Get t he dot pr oduct bet ween t he r ot at ed ver t ex
nor mal s and mul t i pl y i t wi t h t he col or r ange. The pr oduct i s
your col or coor di nat es.
QBcode:
IF znormal < 0 THEN
nx1! = CubeVTXNormal2(Poly(i).P1).X 'Vertex1
ny1! = CubeVTXNormal2(Poly(i).P1).Y
nz1! = CubeVTXNormal2(Poly(i).P1).Z
nx2! = CubeVTXNormal2(Poly(i).P2).X 'Vertex2
ny2! = CubeVTXNormal2(Poly(i).P2).Y
nz2! = CubeVTXNormal2(Poly(i).P2).Z
nx3! = CubeVTXNormal2(Poly(i).P3).X 'Vertex3
ny3! = CubeVTXNormal2(Poly(i).P3).Y
nz3! = CubeVTXNormal2(Poly(i).P3).Z

lx! = LightNormal.X
ly! = LightNormal.Y
lz! = LightNormal.Z

'Calculate dot-products of vertex normals
Dot1! = (nx1! * lx!) + (ny1! * ly!) + (nz1! * lz!)
IF Dot1! < 0 THEN 'Limit
Dot1! = 0
ELSEIF Dot1! > 1 THEN
Dot1! = 1
END IF
Dot2! = (nx2! * lx!) + (ny2! * ly!) + (nz2! * lz!)
IF Dot2! < 0 THEN
Dot2! = 0
ELSEIF Dot2! > 1 THEN
Dot2! = 1
END IF
Dot3! = (nx3! * lx!) + (ny3! * ly!) + (nz3! * lz!)
IF Dot3! < 0 THEN
Dot3! = 0
ELSEIF Dot3! > 1 THEN
Dot3! = 1
END IF

'multiply by color range
clr1 = Dot1! * 255
clr2 = Dot2! * 255
clr3 = Dot3! * 255

GouraudTri x1, y1, clr1, x2, y2, clr2, x3, y3, clr3
END IF
Her e' s and exampl e f i l e:
Gouraud.Bas
3. Phong Shading(Fake)
Phong shadi ng i s a shadi ng t echni que whi ch ut i l i zes
di f f use, ambi ent and specul ar l i ght i ng. The onl y way t o do Real
phong shadi ng i s on a per - pi xel basi s. Her e' s t he equat i on:
Intensity=Ambient + Diffuse * (L N) + Specular * (R V)^Ns
Wher e:
Ambient = Thi s i s t he l i ght i nt ensi t y t hat t he obj ect s r ef l ect
upon t he envi r onment . I t r eaches even i n shadows.
Diffuse = Li ght t hat scat t er s i n al l di r ect i on
Specular = Li ght i nt ensi t y t hat i s dependent on t he angl e
bet ween your eye vect or and t he r ef l ect i on vect or . As t he angl e
bet ween t hemi ncr eases, t he l ess i nt ense i t i s.
L.N = The dot pr oduct of t he Li ght ( L) vect or and t he Sur f ace
Nor mal ( N)
R.V = The dot pr oduct of t he Ref l ect i on( R) and t he Vi ew( V)
vect or .
Ns = i s t he specul ar i nt ensi t y par amet er , t he gr eat er t he val ue,
t he mor e i nt ense t he specul ar l i ght i s.
*L. N coul d be subst ut ut ed t o R. V whi ch makes our equat i on:
Intensity=Ambient + Diffuse * (L N) + Specular * (L N)^Ns
Techni cal l y, this should be done for every pixel of the
polygon. But si nce we ar e maki ng r eal - t i me engi nes and usi ng QB,
t hi s i s al most an i mpossi bi l t y. : *(
For t unat el y, t her e ar e some ways ar ound t hi s. Not as good
l ooki ng but wor ks nonet hel ess. One way i s t o make a phong
t ext ur e and use envi r onment mappi ng t o si mul at e l i ght . Anot her
way i s t o modi f y your pal et t e and use gour aud f i l l er t o do t he
j ob. How do we do i t t hen? Si mpl e! Appl y t he equat i on t o t he
RGB val ues of your pal et t e! ! !
Fi r st we need t o cal cul at e t he angl es f or ever y, col or
i ndex i n our pal . We do t hi s by i nt er pol at i ng our Normals'
angle(90 degrees) and Light vectors' angl e wi t h t he col or r ange.
PseudoCode:
Range = 255 - 0 'screen 13
Angle! = PI / 2 '90 degrees
Anglestep! = Angle!/Range 'interpolate
For Every color index...
Dot! = Cos(Angle!)
'''Apply equation
'RED
Diffuse! = RedDiffuse * Dot!
Specular! = RedSpecular + (Dot! ^Ns)
Red% = RedAmbient! + Diffuse! + Specular!
'GREEN
Diffuse! = GreenDiffuse * Dot!
Specular! = GreenSpecular + (Dot! ^Ns)
Green% = GreenAmbient! + Diffuse! + Specular!
'BLUE
Diffuse! = BlueDiffuse * Dot!
Specular! = BlueSpecular + (Dot! ^Ns)
Red% = BlueAmbient! + Diffuse! + Specular!
WriteRGB(Red%,Green%,Blue%,ColorIndex)
Angle! = AngleStep!
Loop until maxcolor
* This idea came from a Cosmox 3d demo by Bobby 3999. Thanks a
bunch!
Her e' s an exampl e f i l e:
Phong.bas

4. Texture Mapping
Text ur e mappi ng i s a t ype of f i l l t hat uses a
Text ur e( i mage) t o f i l l a pol ygon. Unl i ke our pr evi ous f i l l s,
t hi s one " pl ast er s" an i mage( t he t ext ur e) on your cube. I ' l l
st ar t by expl ai ni ng what ar e t hose U and V coor di nat es i n t he
Af f i ne mapper par t of t he ar t i cl e. The U and V coor di nat es ar e
t he Hor i zont al and ver t i cal coor di nat es of t he bi t map( our
t ext ur e) . How do we cal cul at e t hose coor di nat es? For t unat el y,
most 3d model el er s al r eady does t hi s f or us aut omat i cal l y. : *) .
However , i f you l i ke t o make your model s t he mat h way,
t hat i s gener at i ng t hemmat hemat i cal l y, you have t o cal cul at e
t hemby your sel f . What I do i s di vi de t he quad i nt o t wo
t r i angl es and bl ast t he t ext ur e coor di nat es on l oadup. Lookat
t he di agr amt o see what I mean.
*Text si ze i s t he wi dt h or hei ght of t he bi t map
QBcode:
FOR j = 1 TO UBOUND(Poly)
u1 = 0
v1 = 0
u2 = TextSize%
v2 = TextSize%
u3 = TextSize%
v3 = 0
Poly(j).u1 = u1
Poly(j).v1 = v1
Poly(j).u2 = u2
Poly(j).v2 = v2
Poly(j).u3 = u3
Poly(j).v3 = v3
j = j + 1
u1 = 0
v1 = 0
u2 = 0
v2 = TextSize%
u3 = TextSize%
v3 = TextSize%
Poly(j).u1 = u1
Poly(j).v1 = v1
Poly(j).u2 = u2
Poly(j).v2 = v2
Poly(j).u3 = u3
Poly(j).v3 = v3
NEXT j
Af t er l oadi ng t he t ext ur es, you j ust cal l t he Text ur eTr i
sub passi ng t he r i ght par amet er s and i t woul d t ext ur e your model
f or you. I t ' s a good i dea t o make a 3d map edi t or t hat l et ' s
you pass t ext ur e coor di nat es, i nst ead of cal cul at i ng i t on
l oadup. Her e' s a code sni ppet t o dr aw a t ext ur ed pol y.
QBcode:
u1 = Poly(i).u1 'Texture Coords
v1 = Poly(i).v1
u2 = Poly(i).u2
v2 = Poly(i).v2
u3 = Poly(i).u3
v3 = Poly(i).v3
TextureTri x1, y1, u1, v1, x2, y2, u2, v2, x3, y3, u3, v3, TSEG%, TOFF%
END IF
*Tseg% and Toff% are the Segment and Offset of the Bitmap.
Her e' s an exampl e f i l e:
Texture.Bas
5. Environment Mapping
Envi r onment mappi ng( al so cal l ed Ref l ect i on Mappi ng) i s a
way t o di spl ay a model as i f i t ' s r ef l ect i ng a sur f ace i n f r ont
of i t . Your model l ooks l i ke a war ped- up mi r r or ! I t l ooks so
cool , I j umped of f my chai r when I f i r st made one. : *) We
t ext ur e our model usi ng t he t ext ur e mapper passi ng a ver t ex-
nor mal modi f i ed t ext ur e coor di nat e. What does i t mean? I t
means we cal cul at e our t ext ur e coor di nat e usi ng our ver t ex
nor mal s!
Her e' s t he f or mul a:
TextureCoord = Wid/2+Vertexnormal*Hie/2
Wher e:
Wi d = Wi dt h of t he bi t map
Hei = Hei ght of t he bi t map
Now, assumi ng your t ext ur e has t he same wi dt h and hei ght :
QBcode:
Tdiv2! = Textsize% / 2
FOR i = 1 TO UBOUND(Poly)
u1! = Tdiv2! + v(Poly(i).P1).x * Tdiv2! 'Vertex1
v1! = Tdiv2! + v(Poly(i).P1).y * Tdiv2!
u2! = Tdiv2! + v(Poly(i).P2).x * Tdiv2! 'Vertex2
v2! = Tdiv2! + v(Poly(i).P2).y * Tdiv2!
u3! = Tdiv2! + v(Poly(i).P3).x * Tdiv2! 'Vertex3
v3! = Tdiv2! + v(Poly(i).P3).y * Tdiv2!
Poly(i).u1 = u1!
Poly(i).v1 = v1!
Poly(i).u2 = u2!
Poly(i).v2 = v2!
Poly(i).u3 = u3!
Poly(i).v3 = v3!
NEXT i
Af t er set t i ng up t he ver t ex nor mal s and t he t ext ur e
coor di nat es, i nsi de your r ast er i zi ng l oop:

1. Rotate Vertex normals
2. Calculate texture coordinates
3. Draw model
That ' s i t ! Your own envi r onment mapped r ot at i ng obj ect .
; *)
Her e' s a demo:
Envmap.bas
Anot her one t hat si mul at es t ext ur es wi t h phong shadi ng usi ng a
phongmapped t ext ur e.
Phong2.bas

Playing with colors!!!
6. Shading in multicolor
Our pr evi ous shadi ng t echni ques, Lamber t , gour aud, and
phong, l ooks good but you ar e l i mi t ed t o a si ngl e gr adi ent . Not
a good f act i f you want t o use col or s. But usi ng col or s i n
scr een 13 l i mi t s you t o f l at shadi ng. I bet you woul d want a
gour aud or phong shaded col or ed pol ygons r i ght ? Wel l , l o and
behol d! Ther e i s a l i t t l e way ar ound t hi s pr obl em. : *)
We use a subdi vi ded gr adi ent pal et t e! A subdi vi ded
gr adi ent pal et t e di vi des your whol e pal et t e i nt o gr adi ent s of
col or s l i mi t ed t o i t s subdi vi si on. Her e' s a l i t t l e pal et t e I
made usi ng dat a st at ement s and t he gr adcol or sub.


I f you l ook cl osel y, each l i ne st ar t s wi t h a dar k col or
and pr ogr esses t o an i nt ense col or . And i f you under st ood how
our f i l l er s wor k, you' l l get t he i dea of modi f yi ng t he f i l l er s
t o wor k wi t h t hi s pal . Okay, si nce I ' mf eel i ng good t oday, I ' l l
j ust gi ve i t t o you. Af t er you cal cul at ed t he Dot - pr oduct
bet ween t he l i ght and pol y nor mal s:
*This assumes a 16 color gradient palette. You could make it 32
or 64 if you want. Of course if you make it 32, you should
multiply by 32 instead of 16. :*)
QBcode:
Clr1 = (Dot1! * 16) + Poly(j).Clr '16 color grad
Clr2 = (Dot2! * 16) + Poly(j).Clr
Clr3 = (Dot3! * 16) + Poly(j).Clr

GouraudTri x1, y1, Clr1, x2, y2, Clr2, x3, y3, Clr3

Her e' s an exampl e:
3dColors.bas

7. Translucency
A l ot of peopl e have asked me about t he al go behi nd my
t r ansl ucent t eapot i n Mono and Disco. I t ' s not t hat har d once
you know how t o make a t r ansl ucent pi xel . Thi s i s not r eal l y
TRUE t r ansl ucency, I t ' s a gr adi ent - based bl endi ng al gor i t hm.
You make a 16 col or gr adi ent pal et t e and appl y i t t o t he col or
r ange( Same gr ad above. : *) ) .
PseudoCode:
For Every pixel in the poly...
TempC = PolyPixel and 15
BaseColor = PolyPixel - TempC
DestC = Color_Behind_Poly_Pixel and 15
C = (TempC + DestC)/2
C = C + Basecolor
Pset(x,y),C

What t hi s does f or ever y pi xel i s t o aver age t he pol ygons
col or wi t h t he col or behi nd i t ( t he scr een or buf f er ) and add i t
t o t he basecol or . The basecol or i s t he st ar t i ng col or f or each
gr adi ent . I e. ( 0- 15) : 0 i s t he base col or ; ( 16 t o 31) : 16 i s
t he base col or . Hence t he AND 15. Of cour se, you can make i t a
32 col or gr adi ent and AND i t by 31. : *)

Her e' s a l i t t l e demo of Box t r ansl ucency I made f or my Br o. Hex.
; *)
Transhex.bas
Her e' s t he 3d t r ansl ucency demo:
Transluc.Bas

Final Words:
To make good model s, use a 3d model er and i mpor t i t as an
OBJ f i l e as i t ' s easy t o r ead 3d Obj f i l es. Li ght wave3d and
Mi l kshape3d can i mpor t t hei r model s i n t he OBJ f or mat . I n f act I
made a l oader mysel f . ; *) Not e t hat some model s does not have
t ext ur es, not abl y, Shi p. l 3d, f i ght er . l 3d, et c. The onl y ones
wi t h saved t ext ur es ar e Cubet ext , Maze2, Tr i f or cT, and
Pacmaze2.
Zi pped wi t h OBJ s:
LoadObj.zip
Bas Fi l e:
LoadL3d.bas
Thi s ar t i cl e i s j ust a st eppi ng st one f or you i nt o bi gger
t hi ngs l i ke Mat r i ces, vi ewi ng syst ems and obj ect handl i ng. I
hope you l ear ned somet hi ng f r omt hi s ar t i cl e as t hi s t ook me a
whi l e t o wr i t e. Maki ng t he exampl e f i l es f el t gr eat t hough. : *)
Any quest i ons, er r or s i n t hi s doc, et c. , you can post quest i ons
at ht t p: / / f or um. qbasi cnews. com/ . Chances ar e, I woul d see i t
t her e.
Next ar t i cl e, I wi l l di scuss Mat r i ces and how t o use t hem
ef f ect i vel y on your 3d engi ne. I woul d al so di scuss pol ygon
cl i ppi ng and pr obabl y, i f space per mi t s, 3d vi ewi ng syst ems. So
bye f or now, Rel sof t , si gni ng of f . . .
ht t p: / / r el . phat code. net /
vi c_vi per ph@yahoo. com
Credits:
God for making me a little healthier. ;*)
Dr. Davidstien for all the 3d OBJs.
Plasma for SetVideoSeg
Biskbart for the Torus
Bobby 3999 for the Phong sub
CGI Joe for the original polyfillers
Blitz for the things he taught me.
Toshi for the occasional help

Matrices are your friends

Introduction

Mat r i ces ar e usef ul i n 3d gr aphi cs. Not onl y ar e
t hey f ast , but once you get used t o t hem, i t makes t hi ngs a l ot
si mpl er . Mat r i ces ar e bet t er t han st andar d equat i ons f or t hese
r easons:
1. Act i ons( t r ansf or mat i ons) such as scal i ng, r ot at i on
and t r ansl at i on can be easi l y kept t r ack because you onl y need
t o keep t r ack of t he mat r i x and f or get about your 3d
coor di nat es.
2. I t ' s a one- pass t r ansf or m. Whi ch means you can make
as many mat r i ces as you want and combi ne i t i n one si ngl e mat r i x
t o do al l t he t r ansf or mat i ons f or you. Si mpl i ci t y at i t s best ! ! !

3. You ar e not l i mi t ed t o j ust t he XYZ angl e syst emwhen
vi ewi ng your vi r t ual wor l d. You coul d make a Lookat f unct i on t o
make t hi ngs even si mpl er ! ! ! ( I ' l l get t o t hat i n anot her ar t i cl e)
For t hi s ar t i cl e, I ' mgoi ng t o di scuss mat r i ces and
t hei r appl i cat i ons. I ' mgonna st ar t wi t h t he use of mat r i ces i n
sol vi ng syst ems of l i near equat i ons, t he basi c oper at i ons on
mat r i ces and t hei r appl i cat i ons i n 3d gr aphi cs. I mi ght be abl e
t o put i n some code and al gos i n bet ween. Don' t wor r y, mat r i ces
ar e not as har d as you t hought t hey ar e. : *) . I ' mgonna be
di scussi ng t hose t hi ngs you' d need i n maki ng a 3d game engi ne
usi ng mat r i ces. Whi ch means t hat most mat r i x st uf f I ' mgoi ng t o
i ncl ude i n her e ar e t he easy ones. So wi t hout f ur t her ado. . . .
Syst ems of l i near equat i ons
Remember t he l i near equat i on. . .
ax + by = c?

No? How about t hi s?
y = mx + b?

Thi s t wo equat i ons ar e j ust t wo of t he many f or ms of
l i near equat i ons. The f i r st one( ax+by=c) i s t he "standard" f or m
and y=mx+b i s t he "slope-intercept" f or m. We' l l be di scussi ng
t he st andar d f or mwhen deal i ng wi t h mat r i ces.

Gi ven 2 equat i ons:
2x - 3y = 1
and
3x + 2y = 8
How do you get t he sol ut i on t o bot h equat i ons? The
sol ut i on i s act ual l y t he "intersection" of bot h l i nes def i ned by
t he above equat i ons. For t hose who have done some al gebr a, we
know t hat t her e ar e a number of ways t o f i nd t he sol ut i on.
They ar e:
1. Graphing
2. Substitution
3. Elimination

Solving via elimination:
2x - 3y = 1 equ 1
3x + 2y = 8 equ 2

Make t he coef i ci ent s of x t he same by mul t i pl yi ng equ 1
by 3 and equ 2 by 2 t hen subt r act .

3*[ 2x - 3y = 1] *3
2*[ 3x + 2y = 8] *2

6x - 9y = 3
6x + 4y = 16
- - - - - - - - - - - - - - - - - -
- 13y = - 13 - - - > / - 13
y = 1

Usi ng back subst i t ut i on( equ 1) :

2x - 3( 1) = 1
2x = 1 + 3 - - - >/ 2
x = 2

The sol ut i on i s ( 2, 1)
However when made i nt o code, t hi s i s ver y cumber some
and not f l exi bl e. What we need i s an al gor i t hmi c way t o sol ve
t he syst em. And t he answer i s t he mat r i x. How do we go about
sol vi ng t hi s syst emusi ng a mat r i x? Fi r st l et me di scus t he
ECHELON met hod of sol vi ng t hi s syst emas i t ' s al most par al l el t o
t he mat r i x met hod except f or t he l ast par t .

Solving via the Echelon method:

2x - 3y = 1 equ 1
3x + 2y = 8 equ 2

1. Mul t i pl y bot h si des of equ 1 by 1/ 2 so t hat x wi l l have a
coef f i ci ent of 1.
x - 3/ 2y = 1/ 2 equ 3
3x + 2y = 8

2. El i mi nat e x f r omequ 2 by addi ng ( - 3) t i mes equ 3 t o equ 2.
-3 *[ x - 3/ 2y = 1/ 2] * -3
=
- 3x + 9/ 2y = - 3/ 2
3x + 2y = 8 --> make 2y and 8 similar to 9/2 y and -3/2.
i e. 2y= 4/2y ; 8 = 16/2

- 3x + 9/ 2y = - 3/ 2
3x + 4/ 2y = 16/ 2
- - - - - - - - - - - - - - - - - - - - - -
13/ 2y = 13/ 2

y = 1 equ 4

so.
x - 3/ 2y = 1/ 2 equ 3
y = 1 equ 4

* Usi ng back subst i t ut i on i n equ 1, x = 2.
* l ook at t he coef f i ci ent s of x and y. They bot h have
coef f i ci ent s of 1 ar r anged di agonal l y. i e. .

1x +y =c
1y =c

Thi s i s cal l ed t he TRI ANGULAR or LOWECHELON f or mof t he
syst em. Be sur e t o r emember t hi s as we wel l be encount er i ng t hi s
a l ot of t i mes. And now, what you' ve been wai t i ng f or ! ! ! !

Solving the system the Matrix way!!!
RULES:
A. Any two rows may be interchanged. This is useful if one of the
equations' x-term has a coefficient of 1.
B. The Elements of any row may be multiplied by any non-zero real
number.
C. Any row may be changed b adding to its elements a multiple of the
elements of another row.

2x - 3y = 1 equ 1
3x + 2y = 8 equ 2

1. We f i r st wr i t e t he syst emi n r ows and col umns. Thi s i s cal l ed
t he AUGMENTED mat r i x. Be sur e t hat each equat i on i s i n st andar d
f or m(ax + by = c).
* Thi s i s par al l el t o t he Echel on met hod above so be sur e t o
check f r omt i me t o t i me.
2 -3 1
3 2 8
*Not e we onl y used t he numer i c coef f i ci ent s.
*2, - 3, 1 , 3, 2 and 8 ar e cal l ed t he ELEMENTS of t he mat r i x and
2 i s l ocat ed at r ow1, col 1; 8 at r ow2, col 3; and so on. . .

2. To get 1 i n r ow1, col 1 we mul t i pl y t he f i r st r ow by 1/ 2.

1 -3/2 1/2
3 2 8

3. Add ( - 3) t i mes t he el ement s of r ow1 t o r ow2.
1 -3/2 1/2
0 13/2 13/2

4. To get 1 i n r ow 2, col 2; mul t i pl y r ow 2 by t he r eci pr ocal of
13/ 2 whi ch i s 2/ 13.
1 -3/2 1/2
0 1 1

So. . .
x - 3/ 2y = 1/ 2
y = 1

See, t r i angul ar f or m! ! !
Use back subst i t ut i on t o get x.

I ' l l t est your ski l l s wi t h a 3- equat i on syst em:
x + y - z = 6
2x - y + z = - 9
x - 2y + 3z = 1


We don' t need t o change t he el ement i r 1, c1 si nce i t ' s al r eady
1.
BTW, you can i nt er change any r ows as you l i ke i f i t makes t he
sol ut i on easi er ( Rul eA) .

Augment ed mat r i x:
1 1 -1 6
2 -1 1 -9
1 -2 3 1

1. Eliminate the first element in row 2 by adding (-2) x row 1
to row 2.
1 1 -1 6
0 -3 3 -21
1 -2 3 1

2. Eliminate the first element in row 3 by adding (-1) x row 1
to row 3.
1 1 -1 6
0 -3 3 -21
0 -3 4 -5


3. To get 1 in row2,col2; Multiply row 2 by -1/3.
1 1 -1 6
0 1 -1 7
0 -3 4 7


4. Eliminate the second element in row 3 by adding (3) x row 2
to row 3.
1 1 -1 6
0 1 -1 7
0 0 1 16

5. Translating this matrix to equation form:

x + y - z = 6
y - z = 7
z = 16
(This is the triangular form of the equations)

*The met hod I di scussed above i s cal l ed t he
" GAUSSI AN REDUCTI ON" . I f you don' t know who Karl F. Gauss i s
t hen t hi s ar t i cl e i s not f or you. : *) j / k

Properties of Matrices

I t i s cust omar y t o name Mat r i ces wi t h capi t al
l et t er s. The f ol l owi ng i s Mat r i x A.

a11 a12 a13 a14
A = a21 a22 a23 a24
a31 a32 a33 a34
a41 a42 a43 a44

Wi t h t hi s not at i on, t he f i r st r ow and f i r st col umn
i s a11( r ead: " a sub one- one) .

Mat r i ces ar e cl assi f i ed accor di ng t o si ze(by the
number of rows and columns they contain). For exampl e mat r i x A
i s a 4 x 4 Mat r i x. On t he ot her hand our mat r i x sol ut i on above
i s a 2 x 3 mat r i x:
1 -3/2 1/2
0 1 1

Cer t ai n mat r i ces have speci al names l i ke a SQUARE
mat r i x as i n 3 x 3, 2 x 2, Basi cal l y t he same number of r ow and
col umns. A ROWmat r i x on t he ot her hand i s j ust a mat r i x of one
r ow. Guess what a COLUMN mat r i x i s? : *)

Operations on Matrices

A. Addi t i on of mat r i ces
To add t wo mat r i ces t oget her , add t hei r
cor r espondi ng el ement s. ONLY MATRICES OF THE SAME SIZE CAN BE
ADDED. Same goes f or subt r act i on.
5 -6
8 9
+
-4 6
8 -3

=
5+(-4) -6+6
8+8 9+(-3)

=
1 0
16 -6


B. Mul t i pl i cat i on of a Mat r i x by a scal ar val ue.

To mul t i pl y a scal ar val ue by a mat r i x, you j ust
mul t i pl y al l el ement s of t he mat r i x by t he scal ar val ue.
5 * 2 -3

=

10 -15

0 4

0 20


C. Mul t i pl i cat i on of Mat r i ces

RULE. You can only multiply matrices if A has the same number of columns as
B. ROW by COLUMN.
Ohh this is gonna be *messy*. :*)

Gi ven:
A = -3 4 2
5 0 4

6 4
B = 2 3
3 -2


1. Locate row1 of A and col1 of B, then multiply corresponding
elements and add the products.

Row 1 of A
-3 4 2
*
Column 1 of B
6 2 3
=
(-3)(-
6)
+ (4)(2) + (2)(3) = 32

2. Next Row1 of A by Col2 of B
(-3)(4) + (4)(3) + (2)(-2) = -4

+ + =

3. Row 2 of A and Col 1 of B
(5)(-6) + (0)(2) + (4)(3) = -18


4. Lastly, Row 2 of a and col 2 of B
(5)(4) + (0)(3) + (4)(-2) = 12


The pr oduct mat r i x:
32 -4
-18 12

I n gener al . . .

Cij = Ai1*B1j + Ai2*B2j ...
For Squar e mat r i ces, t her e ar e t wo ways t o mul t i pl y
as t hey have t he same number of r ows and col umns. War ni ng:
Multiplication of matrices is not commutative.

So i n t wo 4*4 mat r i ces, t he r esul t i ng mat r i x i s cal cul at ed as. . .

QBcode:

SUB Matrix.MulMatrix (M!(), TM!())

'Combines 2 matrices M!() and TM!()
'ie. Result = TM x M
'Warning matrix multiplication is not commutative.
'M x TM <> TM x M


DIM Result!(1 TO 4, 1 TO 4) 'resultant matrix to be copied to M!()

FOR i = 1 TO 4
FOR j = 1 TO 4
Result!(i, j) = 0
FOR k = 1 TO 4
Result!(i, j) = Result!(i, j) + TM!(i, k) * M!(k, j)
NEXT k
NEXT j
NEXT i


Now t hat we know how t o do st uf f wi t h mat r i ces, we
wi l l now l ear n i t s appl i cat i ons i s 3d gr aphi cs! ! ! ! Woot ! ! !

I n 3d gr aphi cs i t s of t en easi er t o make t he
or i gi n( 0, 0, 0) as your vi ewpoi nt . i e. Wher e t he l ens of your
camer a i s( The LEFT-HANDED system lends itself well with this if
you want to make a doom-like engine) . I nst ead of maki ng t he
camer a move ar ound your wor l d, you can make your wor l d move
ar ound t he camer a. Rel at i vi t y at i t s best ! ! !

Your first coordinate

Unl ess you want t o do shear i ng and some ot her
speci al ef f ect s, i t ' s conveni ent t o r epr esent your 3d
poi nt / vect or as [x y z] . I l i ke t o make t hi s vect or as a col umn
mat r i x( see col umn mat r i x above) . Modi f yi ng t he poi nt s posi t i on
i s space r equi r es anot her mat r i x. For si mpl i ci t y, I ' l l make t he
t he t r ansf omat i on mat r i x a ROWmat r i x, [A B C]. To t r ansf or ma
poi nt , you j ust mul t i pl y t he our [x,y,z] vect or wi t h t he wi t h
our ROWmat r i x. Remember our mat r i x mul t i pl i cat i on pr oper t y?
COLUMN x ROW.
x
y * A B C
z

= x*A + y*B + z*C

Now if a = 1, b=0, c=0
x*1 + y*0 + z*0 = x

If a = 0, b=1, c=0
x*0 + y*1 + z*0 = y

If a = 0, b=0, c=1
x*0 + y*0 + z*1 = z

I n mat r i x f or m:
1 0 0 - - - >x r ow vect or A
0 1 0 - - - >y r ow vect or B
0 0 1 - - - >z r ow vect or C

*Notice how it looks like the "Triangular" form of the matrix.
:*)

So t o t r ansf or mand ent i r e 3d poi nt by t he vect or
mat r i x usi ng t he mat r i x not at i on above, you j ust mul t i pl y t he
poi nt vect or by t he mat r i x.
*x',y',z' are the new points.
x m11 m12 m13 x'
y * m21 m22 m23 = y'
z m31 m32 m33 z'

=

x' = x*m11 + y*m12 + z*m13
y' = x*m21 + y*m22 + z*m23
z' = x*m31 + y*m32 + z*m33

Now as we wi l l be usi ng a 4x4 mat r i x, l et me
i nt r oduce you t o t he mat r i ces we' l l be usi ng.

1. The I DENTI TY mat r i x
Our i ni t i al "do-nothing" mat r i x. Thi s means t hat i t
wi l l pr oduce exact l y t he same val ues as was bef or e t he
t r ansf or m. We al ways begi n wi t h t hi s mat r i x.
1 0 0 0 ---> x'= x
0 1 0 0 ---> y'= y
0 0 1 0 ---> z'= z
0 0 0 1


Unl ess you' d want t o do some nast y FX l i ke
Shear i ng, et c. , t he l ast r ow i s al ways 0 0 0 1.

2. The Scal i ng mat r i x

Scal es t he mat r i x by sx, sy and sz.
sx 0 0 0 ---> x'= x * sx
0 sy 0 0 ---> y'= y *sy
0 0 sz 0 ---> z'= z * sz
0 0 0 1



3. The Tr ansl at i on mat r i x.

Tr ansl at i on means j ust t o " move" t he poi nt by Tx, Ty, Tz.
1 0 0 Tx
---> x'= x + Tx
0 1 0 Ty
---> y'= y + Ty
0 0 1 Tz
---> z'= z + Tz
0 0 0 1



4. The X- axi s r ot at i on mat r i x

Rot at es t he poi nt s i n t he x- axi s by angl e.
ca = COS(angle)
sa = SIN(angle)
1 0 0 0
---> x'= x
0 ca -sa 0
---> y'= ca * y - s*z
0 sa ca 0
---> z'= sa * y + ca * z
0 0 0 1



5. The Y- axi s r ot at i on mat r i x
ca 0 sa 0
---> x'= ca * x + sa * z
0 1 0 0
---> y'= y
-sa 0 ca 0
---> z'= -sa * x + ca * z
0 0 0 1



6. The Z- axi s r ot at i on mat r i x
ca -sa 0 0
---> x'= ca * x - sa * y
sa ca 0 0
---> y'= sa * x + ca * y
0 0 1 0
---> z'= z
0 0 0 1



Not e t hat t he axi s of r ot at i on i s NOT bei ng t r ansf or med
i n t he 3 r ot at i onal mat r i ces. Now wi t h al l t he abst r act mat h
out of t he way, t he f un par t . . . .

Appl i cat i ons

To make a 3d obj ect r ot at e ar ound space usi ng
mat r i ces, You j ust combi ne al l t he t r ansf or mat i on mat r i ces i nt o
one f i nal par ent mat r i x and use t hat mat r i x t o t r ansf or myour
poi nt s. Her e' s t he PseudoCODE:
PseudoCODE:

Matrix!() is our final combined matrix
Tmatrix!() is a temporary matrix used for transformation.
Dim Matrix!(1 to 4, 1 to 4)
Dim TMatrix!(1 to 4, 1 to 4)

1. Set Matrix! and Tmatrix as Identity matri ces.
2. Set Tmatrix! as Scaling matri x
3. Multiply Matrix! and Tmatrix!
4. Set Tmatrix! as Translate matri x
5. Multiply Matrix! and Tmatrix!
6. Set Tmatrix! as RotX matri x
7. Multiply Matrix! and Tmatrix!
8. [6] but RotY then [7]
9. [6] but ROTZ then [7]
10. For i =0 to numpoints
11. TransformPoints using Matrix
12. Project points
13. next i

*Codes 2 t o 9 can be i nt er changed i n any way you
want . I f you have nor mal s you' d l i ke t o r ot at e, you can use t he
same t r ansf or mat i on mat r i x t o r ot at e t hem. I ur ge you t o
exper i ment and pl ay wi t h t he or der of oper at i ons so t hat you may
see how i t changes t he ent i r e t r ansf or mat i on.

Her e' s t he wor ki ng QBcode f or you t o enj oy.

MatrxRot.Bas

As an excer si se, why don' t you make a gour aud f i l l ed
pol ygon usi ng mat r i ces t o r ot at e your model and nor mal s? Be sur e
t o r ot at e wi t h t he same mat r i x.
You mi ght say, " But your r ot at i on t ut or i al has some
ver y f ast r eady- made mat r i x const ant s. I t ' s al so f ai r l y f ast er
as we don' t have t o mul t i pl y mat r i ces. " Yes t hose const ant s ar e
f ast er t han t he mat r i x met hod but t hey ar e l i mi t ed. Her e ar e
some l i mi t at i ons:

1. Those const ant s have a f i xed or der of
r ot at i on( x, y and t hen z) . I f you want t o change t he or der of
r ot at i on, you need t o do t he " messy" f act or i ng I di d agai n. Wi t h
mat r i ces al l you have t o do i s change t he or der and t hat ' s i t .
Si mpl e as i t can get .

2. To t r ansl at e poi nt s f r omt he camer a, you have t o
subt r act your camer a vect or f r omyour t r ansf or med poi nt s
manual l y. The mat r i x way woul d j ust use t he t r ansl at i on mat r i x.

3. To t r ansl at e f r omt he or i gi n, you' d have t o
subt r act a t r ansl at i on vect or manual l y f r omt he or i gi nal non-
r ot at ed poi nt s whi l e wi t h mat r i ces, you j ust t r ansl at e bef or e
r ot at e. : *)

4. Those const ant s ar e l i mi t ed t o angul ar vi ewi ng
syst ems whi l e mat r i ces can handl e any vi ewi ng syst em. Most
popul ar of t hemi s t he LOOKAT transform( I ' l l get t o t hat i n t he
next ar t i cl e) .

5. The speed di f f er ence i s not appar ent consi der i ng
al l t he cal cul at i ons i n bot h met hods ar e *outside* your
r ast er i zi ng l oop. I never l ost a si ngl e f r ame mysel f . The mor e
t he poi nt s t o t r ansf or m, t he l ess di f f er ence i t makes.


Some of you may have al r eady seen Mat r i ces def i ned l i ke t hi s:

Tr ansl at i on mat r i x:
1 0 0 0
0 1 0 0
0 0 1 0
Tx Ty Tz 1

Thi s i s t he Di r ect X and OpenGL syst emof mat r i ces
wher e r ows ar e swapped wi t h t he col umns. So be sur e t o use t hi s
syst emi f you' r e codi ng vi a DX or OGL. I ' musi ng t he " st andar d"
mat h not at i on i n t hi s ar t i cl e.



Cr edi t s:
Mar k Fel dman f or hi s mat r i x doc. ( I was having problems with the rotation matrices
until I read your doc. Thanks!!!)
Pl asma f or Set Vi deoSeg
wi l dcar d f or t hi s " ser i es" i dea.
Hugo El i as f or hi s WuPi xel doc.
Toshi f or hi s ki nd comment s.
3D i ca f or t her e excel l ent doc.
And you t he r eader of t hi s doc.
Bi skbar t f or t he t or us.
Happy Codi ng! ! ! !

Ri char d Er i c M. Lope ( Rel sof t )
ht t p: / / r el . phat code. net /
vi c_vi per ph@yahoo. com

*For quest i ons and suggest i ons, I hang out at Qbasi cnews. com- - -
> f or um.

Ht t p: : / / For um. Qbasi cnews. com

3D Series Chapter 5: Lookat

by Rel (Richard Eric M. Lope)

I. Introduction
One of the hardest part in making an article is actually starting one. Here I am staring at the
monitor for 15 minutes doing nothing but listening to smashing pumpkins. Greatest band (the
coolest!!) ever. I can't say the same for zwan though, as they sound so gay. C'mon Corgan!!!
Return to your roots!!!
Okay, enough out of topic babble. This time, I'm going to discuss about 3d viewing systems. I
would like to reiterate that you should have read my previous articles in 3d before reading this
primer as this builds around those previous chapters. If not, here are the links:
Chapter 1: Entering The 3D Dimension
Chapter 2: Rotation -- The How's and Why's
Chapter 3: Vectors Are Cool!
Chapter 4: Matrices Are Your Friends
Download the first four tutorials
Genso's J unkyard (Relsoft's website)
II. What is a viewing system?
A viewing system is a way to manage your 3d renders easily with a set of rules. This time we are
going to use the left-handed system and the lookat transform. This by far is the easiest way to
handle a 3d viewing system.
III. Types of viewing systems
There are actually numerous types of viewing systems. But all of them revolve around 3 mother
systems.
1. Euler transforms
This is the pitch, yaw, roll way of viewing your world. This is what we have been using
all along. Rotation from x, y and z axes. Since it's been already discussed in previous
chapters, I won't try to delve on the subject much. This system, although much more
"natural", has some major flaws.
a. You need 3 angles and the mouse only returns a 2d ordered pair(x, y).
b. Angles are hard to visualize.
c. They are prone to "gimbal" lock where angles cancel each other out. The result is
vertigo. Although I have never experienced my engines locking, it's better to be
safe than sorry.
2. Quaternions
This my friend, is a way of representing vectors using quats. My opinion is, with you can
do with quats, you can do with vectors and matrices. Quats are extensions of Complex
numbers. Where complex =i, Quats =i, j, k. You you know how to deal with complex
numbers you'd know how to deal with quats. It's just standard algebra if you can
remember your (FOIL) technique in multiplying binomials. They're not that hard, and
lots of people use them not even knowing how to do quat arithmetic, since there are
numerous premade stuff on the net to do Quat operations. :*)
Pros:
a. Eliminates gimbal lock
b. Great in intepolation
c. Sounds cooler
Cons:
d. Probably a fad/trend
e. You still have to convert from euler angles>quats >matrices to transform points.
f. Most open domain quat operations are in C and this is a QB mag. :*)
3. The lookat transform
This is what I will be discussing in detail from this point onwards. After making
countless, looking good, running well 3d engines, I became sick of managing angles. So I
asked myself: "What if I there is a way to transform your world space using just 2
points?". The reasons being that, in the real world we only need two points to look. The
one we are looking at and the one looking (that's us).
I must admit that I didn't know what the lookat transform does back then as I only heard
it from UGL's U3d module by blitz and v1ctor (not their first names). And since only
they use it and it's not opensource, I had no way of knowing that it was what I needed. So
what I did was try to think of some ways that I could transform my points using 2
coordinates.
Since I know that transforming a point in 3d space requires 3 vectors, all I needed to do
was to find values for these vectors. Now I know my two points/coords. Say the camera
point and the point we would look at:
(cx, cy, cz) =camera(eye)
(tx, ty, tz) =target(what we are looking)
Finding the 1st(forward) and 3rd(right) vectors are easy enough. To find the vectors:
Forward =target - camera
or:
Forward.x =target.x - camera.x
Forward.y =target.y - camera.y
Forward.z =target.z - camera.z

Right =Cross(Forward x Up)
This is assuming I already know my up vector.

The problem is, how the hell do I find the up vector? At that time, I had no idea. My first
solution is to align the forward, up and right vectors with the x, y and z axes. Not good
enough since I have to use euler angles again. Next was to ask my friends at Qbasicnews
on how to find the up vector. No one was able to give me the right answer, as all the links
posted pointed to dead ends. Them I tried to "guess" the up vector with nasty results. I
was almost about to give up on the matter when I saw a code made by TOSHI HORIE on
how to find the right vector!!! After reading the code, I saw that the solution was staring
me in the face that after reading the code, I would have liked to kick myself where it
hurts a lot. :*(
The solution was actually very simple: "The up vector is your Y-AXIS!!!". Yep good ol'
(0,1,0). "Would somebody kick my ballz?" j/k. So I now know how to calculate all the
vectors, the only thing that remains is aligning all the vectors to your camera coord. This
job is handled by the vector operations:
1. Cross product
2. Dot product
3. vector projection
See, I told you to read the previous chapters. These operations are discussed in detail in
Chapter 3 of the series. So to make a matrix which transforms the points using the camera
vector:
Pseudocode:

1. Find forward vector

2. Normalize it

3. Make your up vector (0,1, 0)

4. Align your up vector into the camera origin by subtracting the vector projection of
forward from Up.

5. Get their cross product to get the right vector.

6. Smack those values in the transformation matrix and transform your points.
To align the up vector to the camera origin, we need to find the projection of U(up) to
F(forward) by dropping a perpendicular from U's head to F. This vector, which actually
lies in the direction of F is the projection of U to F. Now what good would this be? Well
we could get the Y(up) component of the Up vector be subracting the X(forward)
component thereby, aligning the Up vector with the Forward vector's origin. The
resulting vector, after Y is copied to Up is a vector perpendicular to the Forward vector.
4. Vector projection

5. Perpendicular vector after aligning

Here's the lookat function I made. Be sure to note of the up vector as we will have fun
with it later on. :*) Matrix.Setcamera is just a function to smack the lookat transform's
vector components to a matrix.
Now you only have to use the resulting matrix to transform your points and they would
orient themselves the way we wanted to.
QB code:
SUB Matrix.Lookat (M!(), Target AS Vector, Camera AS Vector) STATIC
'This sub returns a trasformation matrix defined fom 3 vectors U,F,R
'This type of viewing system is perfect for FPS's. ;*)
'I intentionally left out the roll angle since I have really no use for it.


DIM F AS Vector 'Forward vector
DIM U AS Vector 'Up vector
DIM R AS Vector 'Right vector


F.x =Target.x - Camera.x
F.y =Target.y - Camera.y
F.z =Target.z - Camera.z

Vector.Normalize F 'normalize forward vector

U.x =0
U.y =1
U.z =0


Vector.Normalize U

Dot! =Vector.Dot!(F, U)

U.x =U.x - F.x * Dot! 'Align U to F
U.y =U.y - F.y * Dot!
U.z =U.z - F.z * Dot!


Vector.Normalize U 'normalize the Up vector

Vector.Cross R, U, F 'R =normal to plane f and u

Vector.Normalize R

'Set up camera matrix
Matrix.SetCamera M!(), R, U, F

END SUB



SUB Matrix.SetCamera (M!(), R AS Vector, U AS Vector, F AS Vector)
' [ Rx Uy Fz 0 ]
' [ Rx Uy Fz 0 ]
' [ Rx Uy Fz 0 ]
' [ 0 0 0 1 ]

Matrix.SetIdentity M!()

M!(1, 1) =R.x
M!(1, 2) =R.y
M!(1, 3) =R.z

M!(2, 1) =U.x
M!(2, 2) =U.y
M!(2, 3) =U.z

M!(3, 1) =F.x
M!(3, 2) =F.y
M!(3, 3) =F.z

END SUB
Now that we know how to transform points using the lookat transform, we would need to
design a systems based on the mouse coordinates. Since the mouse has only 2d coords,
we only need 2 angles to find a point in 3d space. How do we do that? Well, if you have
read chapter 3 of the 3d series I made, it would certainly occur to you that we have to use
the spherical coordinate system. I told ya. :*) For those who have forgotten the equations
in converting spherical coordinates to rectangular coords:
CamLookAT.x =SIN(Phi!) * COS(Theta!)
CamLookAT.z =SIN(Phi!) * SIN(Theta!)
CamLookAT.y =COS(Phi!)
Where phi! =(Elevation) the angle against the horizon or your mousey and
theta!=(azimuth) is the 2d angle that you can make from the horizon or mousex (think of
a rainbow).
How do we get Phi and Theta correctly when there are 360 degrees(2PI) in one
revolution and the maximum coords of the mouse are just 319 and 199 respectively (in
screen 13)? The answer again is conversion. For those of you who have done Allegro
GFX and some Democoding you probably already have heard of angles ranging from 0 to
255 or 0 to 512 or any maxvalue which is a power of two. Don't worry we will not use
those values but we will in fact, use the same hack to interpolate our angle increments. :*)
Here's the formula:
Actualangle =2*PI/Maxangle
Where:
Actualangle =the value we would pass as an argument to the trig functions SIN and
COS.
2*PI =duh? It's one revolution
Maxangle =would either be 320 or 200. :*)
Here's the code to convert mouse coords to spherical angles. Modified a lil bit to work
seamlessly. :*)
Theta! =2 * -PI * (MouseX) / 320 'Azimuth
Phi! =PI * MouseY / 200 'elevation

CamLookAT.X =COS(Theta!) * SIN(Phi!) 'Spherical system
CamLookAT.Y =COS(Phi!)
CamLookAT.z =SIN(Theta!) * SIN(Phi!)
Movement (Translation) is just a matter of understanding vector mathematics I discussed
in Chapter 3 (This is Chapter 5 already). To move, we need our starting point (Camera
Position), the lookat vector (Camera Lookat), and the speed we would like to move.
To get the speed (Magnitude), we multiply the lookat vector by a scalar value. ie. Scalar
multiplication.:
xmove =CamLookAT.X * speed
ymove =CamLookAT.Y * speed
zmove =CamLookAT.z * speed
To walk forward, we subtract the speed of lookat vector from our camera position (Note
that speed here is 3):
Campos.X =Campos.X - CamLookAT.X * 3
Campos.Y =Campos.Y - CamLookAT.Y * 3
Campos.z =Campos.z - CamLookAT.z * 3
To move backward do the reverse:
Campos.X =Campos.X +CamLookAT.X * 3
Campos.Y =Campos.Y +CamLookAT.Y * 3
Campos.z =Campos.z +CamLookAT.z * 3
Since we translated the origin(the camera postion in world space, we also have to
translate the origin of our camera lookat vector or our render wouldn't look nice. For that
we add the camera position to our lookat vector. ie. vector addition.
CamLookAT.X =CamLookAT.X +Campos.X
CamLookAT.Y =CamLookAT.Y +Campos.Y
CamLookAT.z =CamLookAT.z +Campos.Z
Now we are ready to transform!!!
Pseudocode:
1. Calculate spherical angles using mouse coords

2. Convert spherical to rectangular coord and put the resulting values on our lookat
vector.

3. Move the camera depending on the input.

4. Translate the lookat origin to the relative to the camera origin(vector add)

5. Translate the matrix using the camera origin

6. Transform the matrix using the lookat transform

7. Transform your points.

8. Draw
That's it!!! Things to remember though is that the origin of rotation is the camera
position. What this means is that the camera is not moving but the world space is moving
relative to the camera (Einstein). ;*)
The "Puke" cam
The word puke cam came from a review of Spy Hunter on the Ps2/Xbox I saw on
TechTV. They called it puke because it would really puke you out of your lunch if you
play the game using that mode. You are racing normally but with a rotating camera. Now
if that's not gonna make you puke, I don't know what will.;*)
You might think that this mode is as useless as your worn out socks but think of a plane
doing a roll, and a car travelling on an angled road. Surely it would be nice to have a way
to roll the world around your forward vector. "No! not another boring vector operations
again!". Hardly. :*). Implementing a roll on the camera is just plain fun and plain easy.
All we have to do is change the UP vector's orientation. "But up is (0,1,0) right?". Yep,
but what if we change the up vector to any orientation we want? Well, it turns out that
doing something with out up vector permits us to roll the camera. How do we roll the
camera? Easy, use the polar to cartesian coordinate conversion.
'Calculate roll angle
ra! =RollAngle% * 3.141593 / 180
U.x =COS(ra!)
U.y =SIN(ra!)
U.z =0
Clippin' it
The clipping algo that I would introduce here is the easiest one. By easiest doesn't mean
it's sucks. Since the ASM triangle filler I used already implements scanline clipping, I
should know since I made it. :*), the only clipping we have to do is a near/far clip and 2d
x, y clip. Here's the algo.
For every poly
if all z coords are >1
if all z coords are <Farthest distance
if some x>0 or some y >0 or some x <319 or some y<199
Poly draw =True
end if
end if
end if
next

You might also like