Line of Sight - Tobias Downer

This article describes my observation of existing line of sight
systems in roguelike games, and details the method I adopted for my
own experimental engine.

Early LOS (Moria)
-=-=-=-=-=-=-=-=-=-

When I first played Moria on my friends Amiga in 1990, I was instantly
hooked on roguelikes. Dungeon exploration was one of the main 'hook
factors'. As the player moved around the dungeon, a new part would
light up revealing a little bit more. You really didn't know what
would be around the next corner, or how the dungeon terrain would turn
out.

Compared to more recent roguelikes, Moria uses very simple line of
sight determination. The players light source can only extend 1 grid
square around the player. When a player enters a room that is lit,
the entire room appears and is memorised by the player. Determining
whether a monster is visible is handled by tracing a line from the
monster to the player. If a line can be traced without intersecting
any wall grids, the monster is visible.

There is one rather large bottleneck in this system. It is required
that for each monster that _may_ be visible, that a line is traced.
For a map with high concentrations of monsters (such as spawning
worms), this leads to poor performance.

For most cases however, the line of sight system in Moria is fast and
effective. Moria was written in the second half of the 80's so it
needed to be. With the increase of processor speeds and compiler
technology, newer roguelikes have refined the LOS process further to
create more realistic engines.

A more realistic LOS (Angband)
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

In most recent roguelikes, the line of sight code has extended to
encompass a 'field of view'. An easy way to visualise this, is to
imagine a light source emitting rays of light up tp a given radius.
Every grid that is hit by a ray from the light is flagged as visible.
However some grid squares may be in shadow of the light source. The
diagram below shows a simple example of this.

There are several advantages to implementing such a system. If a grid
'knows' about any monsters that are standing on it, as well as
flagging grids as visible, we can also flag all the monsters that are
in line of sight of the player. We no longer need to do an expensive
line trace between monster and player to determine monster visibility.
It also allows us to incorporate nice visual effects such as fading
out the areas of the map that are in the players memory but not
directly visible.

How do we go about writing such as routine?
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

For simplicity, lets say we have a field of view with a radius of 6
grids. One approach would be to trace a line between the light to
every edge of the field of view. If we simplify this process a
little, lets say our field of view is a square with the light source
at coordinates (0, 0). The diagrams below shows the first three
iterations of this method.

If any line trace hits a wall then the trace is finished and a new
trace is started. Every grid that the line intersects is marked as
visible.

Implementing such a routine is very easy. I won't go into how to
walk along a line here. Look up existing line drawing routines or
work it out yourself. One thing to avoid is using floating point
numbers - keep all calculations in the inner loop as integers.

One point to note here. When you are tracing a line, you must be
careful that you are checking _every_ grid that the line is going
through. This is a little more involved than you may at first
realise. Consider the following diagram.

The line travels through grids (0, 1), (1, 1), (1, 2) and (2, 2).
It we were to walk the line at intervals of 1 unit along the y axis,
we would miss the intersection with grid (0, 1) and (2, 2). To solve
this, we actually need to walk the line at intervals of .5 units.

This simple method outlines the basic approach for achieving line of
sight determination. However if you were to use it, you will find the
performance very poor. Let me explain the reasons why. Say we have a
radius of 25 grids. A walk from the centre to the field of view edge,
assuming no wall intersections, will take 50 iterations (walking at .5
units). There are a total of 50 grids on each of the 4 edges therefore
the total number of iterations will be (50 * 4) * 50 = 10000 assuming
no wall intersections. There are a total of 2600 grids (not including
the centre grid) in our field of view. That means the algorithm is
checking almost four times as many grids as there are in the field of
view!

Obviously, we need to find a way to optimise the performance so that
a smaller number of grids need to be checked. For my own experimental
engine, I used the following method. It is almost identical to the
algorithm first suggested and implemented in Angband 2.8.3.

The most obvious way of optimising the performance is to subdivide the
field of view and concentrate our optimisation on just one section.
We can then mirror the process in all the other sections. If we
subdivide the field of view into eight, we create 8 octant triangles
as shown in the diagram below. For simplicity, I'm assuming a square
field of view. The octants are numbered 0 to 7 and proceed clockwise
around the light source. Each octant has shared edges with two other
octants.

If we optimise our algorithm to work only for octant 0, we can easily
swap x and y, and change the signs of the terms to reflect on any of
the other 7 octants. For example, walking through x in octant 0 is
the same as walking across -x in octant 3 or 4, across -y in octant 5
or 6, and across y in octant 1 or 2.

The second rule of optimisation is to pre-compute as much as you can
and that memory allows. Since we only need to process 1/8th of our
field of view, we have decreased the amount of memory required to
store our lookup tables.

Remember we used the analogy of a light source emitting rays of light?
If we pre-calculated every ray of light that travels through the
octant, and also find the rays of light that are blocked if a given
grid is a wall. At runtime, we can scan through the octant grid,
moving away from the light source, lighting up the grids that have at
least one ray of light hitting them. Any grids that represent a wall
will flag the rays that hit the grid as blocked, thereby putting
others in shadow. The following diagram (hopefully) demonstrates
this principle.

The diagram shows the pre-computation of 6 rays of light where each
line (except 1) intersects the grid at (2, 1). Lines 2 and 6 'brush'
past the corners of the grid, and lines 3, 4 and 5 travel through the
middle of the grid. Because there is a wall at grid (2, 1), lines
3, 4 and 5 would be flagged as 'blocked'. This means no rays are
able to hit grid (3, 2) or (4, 2) thus putting them in shadow.

If we pre-calculate each line to every grid corner in an octant
discarding any identical lines, and sort into a list, we produce a
list of all unique lines sorted from the horizontal to the diagonal of
the octant. We can then pre-calculate a lookup table for each grid
square in the octant, and store the range of rays that are blocked if
the given grid is a wall. For example, in the above diagram the grid
at (2, 1) would block all rays between 2 and 6. The grid at (4, 1)
would block all rays between 1 and 4.

We can store the list of rays in a bit vector, or boolean array. If a
wall grid is found, we simply flag the bits between the outer bounds
of the given grid as blocked. A similar test can be used to determine
if an unblocked ray hits a grid. Simply test each bit in the vector
between the two outer corners, if an unblocked bit is found then the
grid is visible.

This method is very fast since it requires most grids to be scanned
only once. The exception is along the horizontal, vertical and
diagonal which are shared between two octants. These grids need to
be scanned twice, once by each shared octant.

It is easy to adapt the algorithm to produce a circular field of view
as opposed to a square field of view. Simply use the Pythagorean
theorem to determine if a given coordinate (x, y) is within the
radius;

(x * x) + (y * y) < (radius * radius)

Angband uses an octagonal field of view;

max(x, y) + (min(x, y) / 2) <= radius

We could also use this algorithm to determine if a given grid is
visible from another. There are two ways of doing this. Find the
octant the destination grid is in relative to the source. Then do
the 'blocking ray' method described above. When we reach the
destination grid, if no rays are hitting it, its not visible. The
second method is to find the destination grid, and for each ray that
intersects the grid, trace a line from the source. If one of the
traced rays hits the grid without intersecting a wall, the grid is
visible.

Performance
=-=-=-=-=-=-=

I implemented this algorithm in Java and used a radius of 25 grids
with a circular field of view. It performed particularly well when
there were only a few wall grids, or if the source was enclosed by
many wall grids. It didn't perform so well between these extremes.
However on my P120, the worse case tested speed was 5 ms (200 a
second).

Acknowledgments
=-=-=-=-=-=-=-=-=

For a more detailed description of this method, download the Angband
2.8.3 source and look in the file 'cave.c'. Thanks go to Mat
Hostetter and Ben Harrison for developing and implementing the
algorithm.

If you have any questions about this article, feel free to email me
at geoffd@iglou.com.

This article describes the basics of representing and using Magick Spells in roguelikes.
The general techniques are very similar to those used in my article on Object
representation.

For starts, we need a class to hold the information for a specific spell.

class Spell {
public:

OK. Now, let's give the spell a name.

char *Name;

There. Now, every magick spell costs Mana Points (well, if you're using a magick system
similar to most others). So we need to define the spell's cost in MP.

int MPCost;

Also, every spell has a level: how difficult a spell it is. Only more powerful casters can
use more powerful spells.

int Level;

There. Now all we need to know is what in Gehenna the spell does. We'll make a
sub-class called Effect to store this information.

class Effect: {
friend Spell;

OK, so what does a specific spell do? We'll make a simple int to describe what a specific
Effect describes.

int Type;

So what does Type mean? We'll use some #define's to specify.

#define HEAL 0
#define SCORCH 1
#define TICKLE 2
#define CREATE_OBJ 3

You can of course add as many as you want. Now, we know what an Effect does, but
that's not enough. For example, for a HEAL Effect, how much HP does it heal? We
could base everything of level (making a rigid and uniform magick system, which may
be what you want: predictability), or we could give each Effect a set of arguments to
define in more detial what it does. We'll do this through the use of 5 int's.

int Args[5];

What do the fields of Args mean? That's based on what Type is equal to. For an Effect
with Type HEAL, we might say that:

Args[0] is Number of Dice
Args[1] is Sides per Die
Args[3] is Roll Mod

Anyways, we can close of the Effect class. We want each Spell to have 5 Effect's (so
every spell can have lots of flexibility).

} Effects[5];

We can now close of the Spell class.

};

So that's all there is to a basic magick class.

Casting the spell is just as simple. Make a function called Cast or whatever (I used an
object method inside the Spell class, since I'm a C++ OOP freak). The function would
take as arguments the spell to cast, the target, etc.

void Cast ( Spell *SpellToCast, int TX, int TY );

Then we go with a big, evil, switch statement based on effect. This actually works
VERY well. The flexibility is astounding...

Of course, how each spell takes effect is based on how you've programmed the rest
of your roguelike. Because of the OO nature of WotR, I found it very easy to create
simple object Methods for spell effects.

For the HEAL Spell Effect Type, you might to do something as simple as loop through
all the Characters (NPC's and Players) in the target loc (defined by TX and TY), and
heal them based on the arguments listed above... 2d6+2, or whatever.

Anyways, this is just the basics. The advanced stuff all depends on your magick
system and how you programmed the rest of the game.

Hey, I noticed that both Angband and NetHack users have their own
GeekCode. Why not us? ;). This is the first draft, and it\'s realy
RLDev specific. I think that a Roguelike Dev Code will be especialy
useful, because it may make us more aware of the others ideas. I\'m
open to all new ideas, or corrections. In all project specific
questions answer about your current project. A sample of the code is
on the bottom of the document.

I encourage to at least post your code once, so someone can collect
them and post somewhere :).

E+++ I\'m a professional programmer
E++ I program as a part time job
E+ I program quite well, as a hobby
E- I\'ve read a few books and made some programs
E-- I\'ve made a few simple programs
E--- I\'m learning while I write a roguelike

!E I\'m just a designer ;)
?E What do I need programming for?

\"T\": Time invested in rl-development. Choose the most true one :).

T+++ Every minute of my spare time!
T++ Most of my free time
T+ Regulary
T- From time to time
T-- As a recreation
T--- Rarely

!T I don\'t write yet!

\"R\": Rewrites. A rewrite is writing your code from scratch, using only
old libraries, and fragments of the old code.

R+++ more than 5
R++ 3-4 rewrites
R+ 1-2 rewrites
R- not yet
R-- I\'ve just started
R--- I do not program yet

P+++ My game will be ported to most known platforms
P++ Linux and DOS/Win
P+ I try to keep the code portable.
P- Why the hell? I write only for Linux/DOS (you may recompile it
though)
P-- DOS/WIN only
P--- Windows only!

!P I use Java (or something similar)

\"D\": Importance of design before programming

D+++ I had a detailed DesignDoc before I started programming
D++ I had many notes and information before I started coding
D+ I keep my designdoc ahead of the project, but update it regulary
D- I had a few notes before I started coding
D-- I had a general image of what I\'m trying to do

!D Who the hell needs a DesignDoc? I make everything on the fly!
?D What\'s a DesignDoc?

\"G\": The generic engine, that is, how generic your game will be.

G+++ You will be able to make a hard-sci-fi game out of my engine, by
just changing the info-files!
G++ My engine is very generic -- you will be able to make a
different game by changing the info files
G+ I have info files for maps, monsters, items and dungeon
generators
G- I have a few general info files
G-- I keep everything in the code

RL+++ A roguelike MUST be ASCII, MUST be a dungeon crawl, and MUST be
based on a system similar to AD&D, and MUST be permadeath.
RL++ A roguelike has to be ASCII, has to be random, and have
experience levels, and permadeath.
RL+ A roguelike has to be ASCII or use tiles, must have dungeons,
and focus on killing things for experience. It has to be permadeath
too.
RL- A roguelike may have graphics but has to be rather dungeon
themed permadeath game.
RL-- A roguelike is a game that focuses on randomness, and features
permadeath.
RL--- A roguelike is a game inspired by other roguelike games.

!RL This is completely unimportant
?RL What is a roguelike actually?

\"RLA\": Roguelike community activity

RLA+++ I\'ve created a popular game, or host one of the main roguelike
sites on the web.
RLA++ I\'ve created a roguelike dedicated webpage (focusing not only
on my game)
RLA+ I\'m a FAQ maintainer, or wrote a roguelike article, or created
a roguelike document
RLA- I play roguelikes and post on a few roguelike newsgroups
RLA-- I post on one roguelike newsgroup

Q+++ The plot is the master! You will have random interesting quests
in my game.
Q++ I will add many pre-written quests.
Q+ I will add a few quest for flavor, or even ToME-like random
quests.
Q- Maybe a few quests for flavor
Q-- Kill Sauron. Kill Morgoth.
Q--- No quests -- just Hack\'n\'slash.

!Q Who the hell needs quests?
?Q What is a quest?

\"AI\": Approach to AI in your project

AI+++ AI is the key! The creatures will behave diablo inteligently and
talk to you with Bot-generated messages. They will use military
tactics, recognize dangers, and create traps.
AI++ The NPCs will behave quite reasonable, will flee, band together,
pickup and use items.
AI+ The creatures will use items like wands, staves and the like.
AI- The creatures will be able to pickup and equip items.
AI-- No monster-inventory -- just Hack\'n\'Slash
AI--- Kill player. Kill player.

\"GFX\": Approach to graphics

GFX+++ The game will be graphical with nice graphics
GFX++ The hame will have tiled graphics
GFX+ Some popular freeware tiles
GFX- Somewhere in the future I plan to add graphics
GFX-- I\'d like graphics, but I\'m a poor artist

!GFX Pure ASCII rulez!

\"SFX\": Approach to sound

SFX+++ Digitalized Speech and Music is my aim
SFX++ I will add many wave files and maybe some music
SFX+ Just a few Sound-Effects
SFX- Maybe in the future
SFX-- I\'d like sound, but I\'m a poor at that

!SFX A roguelike with sound? Buhahahaha...

\"RN\": Approach to randomness in your project

RN++++ The whole world will be random, random quests, random dialogs,
random plot
RN+++ Same as above, but the plot will be fixed
RN++ The world will be fixed, but there will be random quests,
dungeons and items and monsters
RN+ Random dungeons+items+monster placement
RN- Just the dungeons and monster placement
RN-- I plan to make everything fixed

\"PO\": Popularity of current project

PO+++ I have fan-sites of my playable roguelike (reserved for ToME,
NetHack, ADoM, Angband and the like :)
PO++ I have a playable version on the web that can be enjoyed
PO+ I have a playable version on the web that can be looked at
PO- I have a designer version on the web (dungeon+items+npcs and
the like)
PO-- I have a few design programs (map-view, dungeon generator)
PO--- I haven\'t published anything

!PO I didn\'t do anything yet!

\"Hp\": Hitpoint treatment in the roguelike

Hp+++ A 1-st level character has a few hitpoints, a 50th level
character has a few hundred...
Hp++ I keep the hitpoints rather lower.
Hp+ The player rarely recieves hit-points, I don\'t use a level
system.
Hp- Fully skillbased
Hp-- Fully skillbased and advancement doesn\'t make you realy
powerfull

!Hp I don\'t use hitpoints!

\"Re\": Realism in the roguelike

Re+++ You can die because of disease, rusty weapon wounds, or the
after-effects of an out-dated portion of speed
Re++ Each fight is dangerous
Re+ I\'d rather not let the player kill hordes of monsters
Re- I like to keep things real as in NetHack
Re-- I like to keep things real as in Angband
Re--- Who needs realism? It\'s the hack\'n\'slash that counts!

\"S\": Seriousness of the world

S+++ THE GAME. You think it\'s funny? You\'re talking to me?
S++ The game has to be serious. I want to make an atmosphere...
S+ (ADoM) From time to time a funny in-game situation is fun
S- I like to keep the world rather not gloomy
S-- (ZAngband) Lets keep it easy, sometimes a Barney, or Bull Gates
is fun to kill
S--- (NetHack) Why the hell? Let\'s have nuclear scientists, tourists,
photo-cameras and sinks in a dark dungeon

Okay. Basically, what works well as of the current version is map
generation, line of sight (everything not in LOS is greyed out) and config
file for key setup. The player, item and inventory structs and functions
have been started. Spells, monsters and combat are just stubs.

- Map generation is by far the most complex part of this. The GenerateRoom
routine (in map-internal.c) creates weird cave-looking rooms by a
conceptually simple method:

- creature.c allocates the correct amount of memory for a creature, but
does nothing more as of yet.

- pl_item.c and item.c is in its infancy. It has a demo item defined, and
allocates it to the player, and successfully displays it in the player's
inventory. Fragile. But item.h is quite well-developed, and ought to give
anyone ideas...

- map.c ... Map_Scanfor was designed to scan for any interesting parameter
inside maps, but are currently not used for much besides finding a good
place for a corridor. map.c contains all routines that should be visible
outside map generation. GenerateCorridor currently uses a hit-and-miss
approach (copy map to temp_map -> run generatecorridor -> if grind to a
halt, try again -> if not copy temp_map to map) and can be improved much,
I suppose.

- I'm currently undecided on what's the best approach: Defining "id" in
all object structures or defining it in the "node" structure. It must be
defined in any case, so we can find a specific object that we don't have a
pointer to by some FindObject routine (to avoid passing a million pointers
around). (started, see FindWindow in output.c)

- writing colored strings to the screen is currently accomplished by
calling WriteStr as usual, with strings of the format "<White>Bob
<Yellow>the Big" ... WriteStr does not do %s and such expansion, so
sprintf() ing a string before passing it to WriteStr is a good thing. Look
to the bottom of player.c for an example.