# 3D Clipping in Homogeneous Coordinates.

Recently I got an Arduboy, and I thought it’d be an interesting exercise to blow the dust off my computer graphics knowledge and put a simple 3D vector drawing system together. After all, while by today’s standards a 16 MHz doesn’t sound like a lot, back when I was learning Computer Graphics at Caltech in the 1980’s in Jim Blinn’s computer graphics class, that was quite a bit of computational power.

A limiting factor on the Arduboy is available RAM; after you factor in the off-screen bitmap for drawing, you only have perhaps 1250 bytes left–not a lot for a polygonal renderer. But when a 4×4 transformation matrix fits into 64 bytes, that’s plenty of space for a vector graphics pipeline.

First step in building a vector graphics pipeline, of course, is building a 3D line clipping system; you want to be able to clip lines not just to the left and right, top and bottom, but also to the near and far clipping planes. And you do want to clip before you draw the lines; on the Arduboy, line drawing coordinates are represented as 16-bit signed integers, and with a 3D rendering system it would be very easy to blow those limits.

Sadly, however, I was unable to find a concise description of the homogeneous coordinate system clipping algorithm that I used when I was at Caltech. It’d been 30 years, and I had a vague memory of how we did it–how we combined the Cohen-Sutherland algorithm with Clipping using homogeneous coordinates and some general observations made during class to build an efficient 3D line clipper. And an Internet search yielded very little.

So I thought I’d write an article here, in case in another 20 years I need to dip back into the archives to build yet another line clipping system.

If you want to skip the math and get to the algorithm, scroll down to the section marked “Algorithm.”

Some preliminaries, before we get started.

In Computer Graphics, it is advantageous to represent 3D points using homogeneous coordinates. That is, for any point in 3D space (x,y,z), you add an additional term w, giving (x,y,z,w).

To convert from a homogeneous coordinate (x,y,z,w), you use the following relationship:

Typically when we convert a point from 3D space to a homogeneous coordinates we simply tack a 1 at the end. There are special cases where you may want to do something simple (such as representing stars plotted infinitely far away, but typically you simply tack a 1 on:

The purpose of this extra parameter is to simplify coordinate transformation through transformation matrices. This extra 1 term, for example, allows us to represent translation (that is, moving a point from one location to another) as a simple matrix multiplication. So if we are moving the points in our system over by (5,3,2), we can create a 4×4 translation matrix:

and a point (x,y,z) would be translated through multiplication:

One nice thing about using homogeneous coordinates is that we can represent perspective through a matrix multiplication. I’ll save you the diagrams you see on other countless web sites by noting that to represent point perspective, you divide the location (x,y) by the distance z; objects far away appear smaller and closer objects appear larger.

If we use a perspective matrix which adjusts the size (x,y) to fit our screen (so objects to the far left are at x = -1, objects to the far top are at y = -1, right and bottom are at +1 respectively), then a point at (x,y,z) would map in our perspective transform:

(Side note: we use a right hand rule for coordinates. This means if up is +y and right is +x, then distance is -z. Which brings me to a rule of thumb with computer graphics: if the image looks wrong, look for an incorrect minus sign. While writing this article and testing the code below, I encountered at least 4 places where I had the wrong minus sign somewhere.)

Now if we convert our coordinates using the homogeneous coordinate to 3D point transformation above:

That is, our 3D point (in what we call “screen space”) has the point perspective transformation baked in, and points in 3D space at (x,y,z) show up with perspective on our 2D screen: we just drop the third term and plot points on our screen at the location (ax/-nz,by/-nz).

Notice that we’ve set our boundaries for screen space with the screen space rectangle (-1,-1)-(1,1). It is advantageous for us to clip our drawings at those boundaries, and (for reasons I’ll skip here), it helps to also clip Z coordinates at a near clipping plane (generally z=-1), and a far clipping plane (z=-∞).

The rest of this article will describe in concrete steps how to do this clipping in homogeneous coordinates, using the two articles cited at the start of this article.

First, let us note that to clip in the screen space x/w >= -1, in homogeneous coordinates we really are clipping at x >= -w.

Second, let us define what we mean by clipping. When we say we are clipping a line, what we’re doing is finding the point where a line intersects our clipping plane x >= -w. We then shorten the line at that new point, drawing only the segment that is visible.

So, given two points A and B, we want to find the point C where C intersects the plane x = -w, or rather, where x + w = 0:

We can do this by observing that the dot product of a point and a vector is the distance that point is along the vector, and that our clipping plane x + w = 0 can also be defined as the set of points P where

So to find our point C, we calculate the distance along the vector (1,0,0,1) (that is, x = -w) for the points A and B, and linearly interpolate to find the location C.

There are some other useful observations we can make about the set of relationships above.

First, if x is greater than -w — that is, if we are on the inside of the clipping plane x/w >= -1, then the dot product A(1,0,0,1) will be greater than or equal to 0.

Second, if both A(1,0,0,1) and B(1,0,0,1) are both negative, then trivially our line is not visible, because both endpoints of the line are not visible.

And we can repeat this operation for all the relationships: for x >= -w, x <= w, y >= -w, y <= w, and z >= -w.

The far clipping plane can also be taken care of, by observing that our far clipping plane at infinity is reached as z/w approaches infinity; that is, as w approaches zero. So our far clipping plane would be the relationship z <= 0.

This gives us the following normal vectors representing our 6 clipping planes:

Note that the vectors are set up so that when we are outside of the clipping plane, the value of the dot product is negative: that is, if the relationship x <= w holds, then 0 < w – x, and our clipping plane for that relationship is (-1 0 0 1).

The algorithm

This allows us to start sketching our solution.

Note our definition of a 3D vector is a homogeneous vector:

```struct Vector3D
{
double x,y,z,w;
}```

First, we need a method to calculate all our clipping dot products. Note that because we’ve transformed our process into clipping against a set of vectors, the routine below could be generalized to add additional clipping planes. (For example, you may want to create a renderer that only renders the stuff in front of a wall in your game.)

```static double Dot(int clipPlane, const Vector3D &v)
{
switch (clipPlane) {
case 0:
return v.x + v.w;        /* v * (1 0 0 1) */
case 1:
return - v.x + v.w;      /* v * (-1 0 0 1) */
case 2:
return v.y + v.w;        /* v * (0 1 0 1) */
case 3:
return - v.y + v.w;      /* v * (0 -1 0 1) */
case 4:
return v.z + v.w;        /* v * (0 0 1 1) */
case 5:
return - v.z;            /* v * (0 0 -1 0) */
}
return 0; /* Huh? */
}```

Now we borrow from the Cohen-Sutherland algorithm, and create a method which generates an “outcode”; this is a bitmap with 6 bits, each bit is set if a point is “outside” our clipping plane–that is, if the dot product for the given coordinate is negative.

```static uint8_t OutCode(const Vector3D &v)
{
uint8_t outcode = 0;
for (int i = 0; i < 6; ++i) {
if (Dot(i,v) < 0) outcode |= (1 << i);
}
return outcode;
}```

(Note that we could easily optimize this method by using direct compares rather than by calling into our Dot method. We can also generalize it if the dot product method above is generalized.)

A nice feature about our OutCodes is that if we have the outcodes for points A and B, the following relationships are true:

• if ((a_outcode & b_outcode) != 0) then both points are on the wrong side of at least one edge, and we can trivially reject this line.
• if ((a_outcode | b_outcode) == 0) then both points are inside our viewing area, and we can trivially accept this line.

Now if it turns out both relationships are true, then we must clip our line A – B. And we can do that by calculating the alpha coordinates along A and B–if A is outside, we track the alpha on the A side of the line, and if B is outside, we track an alpha along B. And if the two flip–then we have a case like the one shown below:

This allows us to set up our final clipping algorithm.

First, we track the last point that was added, and the out code for that point:

```static Vector3D oldPos;      // The last point we moved or draw to
static uint8_t oldOutCode;   // The last outcode for the old point.```

We also rely on a drawing routine which actually draws in screen space. This should take the 3D homogeneous point provided, transform (using the transformation to 3D space noted above) to a 3D point, drop the Z component, convert the (x,y) components from the rectangle (-1,-1) – (1,1) to screen pixels, and draw the line as appropriate:

`void MoveDrawScreen(bool draw, const Vector3D &v);`

One last method we need is a utility method that, given a start point and an end point, and an alpha, calculates the linear interpolation between the start and end points.

```static void Lerp(const Vector3D &a, const Vector3D &b, float alpha, Vector3D &out)
{
float a1 = 1.0f - alpha;
out.x = a1 * a.x + alpha * b.x;
out.y = a1 * a.y + alpha * b.y;
out.z = a1 * a.z + alpha * b.z;
out.w = a1 * a.w + alpha * b.w;
}```

Now our method declaration takes a new point and a flag that is true if we’re drawing a line, or false if we are moving to the point:

```void MoveDrawClipping(bool draw, const Vector3D &v)
{
Vector3D lerp;
float aold;
float anew;
float alpha;
float olda,newa;
uint8_t m;
uint8_t i;
uint8_t newOutCode;

/*
*    Calculate the new outcode
*/

newOutCode = OutCode(v);```

In the above we calculate the outcode for our new point v. This allows us to quickly determine if the point is inside or outside our visible area. This is useful when we want to just move to a point rather than draw to a line:

```    /*
*  If we are not drawing, and the point we're moving to is visible,
*  pass the location upwards.
*/

if (!draw) {
if (newOutCode == 0) {
MoveDrawScreen(draw,v);
}
} else {```

If draw is true, then we’re drawing a line, and so we get to the meat of our clipping algorithm. Note that our old out code and old points (stored in the globals above) have already been initialized. (Or rather, we assume they have been with an initial move call.)

So we can borrow from the Cohen-Sutherland algorithm and quickly determine if our line is entirely clipped or entirely visible:

```        /*
*  Fast accept/reject, from the Cohen-Sutherland algorithm.
*/

if (0 == (newOutCode & oldOutCode)) {
/*
*  The AND product is zero, which means the line may be
*  visible. Calculate the OR product for fast accept.
*  We also use the mask to quickly ignore those clipping
*  planes which do not intersect our line
*/

/*
*  Fast accept. Just draw the line. Note that our
*  code is set up so that the previous visible line has
*/

MoveDrawScreen(true,v);
} else {```

If we get to the code below, this means we have a value for mask which indicates the clipping planes that we intersect with. So now we want to interate through all the clipping planes, calculating the dot product for only those planes we intersect with:

```                /*
*  At this point mask contains a 1 bit for every clipping
*  plane we're clipping against. Calculate C alpha to find
*  C, and adjust the endpoints A alpha (aold) and B alpha
*  (anew)
*/

aold = 0;            /* (1 - alpha) * old + alpha * new = pt */
anew = 0;            /* so alpha = 0 == old, alpha = 1 == new */
m = 1;
for (i = 0; i < 6; ++i) {

/* Calculate alpha; the intersection along the line */
/* vector intersecting the specified edge */

olda = Dot(i,oldPos);
newa = Dot(i,v);
alpha = olda/(olda-newa);```

And next we need to bring in the side of the line which we know has clipped against the clipping plane. Meaning if A is outside our visible area and B is inside, we want to adjust Aα to the new value calculated in alpha; but if A is inside and B outside, we want to adjust Bα instead.

```                        /* Now adjust the aold/anew endpoints according to */
/* which side (old or v) is outside. */
if (oldOutCode & m) {
if (aold < alpha) aold = alpha;
} else {
if (anew > alpha) anew = alpha;
}```

And finally if somehow the edges cross, we have the circumstance above where the line is not visible but crosses two clipping planes. So we quickly reject that case:

```                        if (aold > anew) {
/*
*  Our line is not visible, so reject.
*/
break;
}```

The rest simply closes our loop:

```                    }
m <<= 1;
}```

At this point if we have iterated through all six planes, we have a line which is visible. If our starting point in oldPos was not visible, then we need to move to the place where our starting point intersects with the clipping boundaries of our view space:

```                if (i >= 6) {
/* Ran all clipping edges. */
if (oldOutCode) {
/* Old line coming into view */
Lerp(oldPos,v,aold,lerp);
MoveDrawScreen(false,lerp);
}```

And if our destination point is visible, we draw to it; otherwise, we draw to the point on the line we’re drawing to which intersects our clipping boundaries:

```                    /* Draw to the new point */
if (newOutCode) {
Lerp(oldPos,v,anew,lerp);
mdl2(true,lerp);
} else {
mdl2(true,v);
}```

Our clipping is done; all that is left is to close up the loops and conditionals, and store away in our globals the outcode for the point we just moved to, as well as the location of that point:

```                }
}
}
}

/*
*    Now update the old point to what we just moved to
*/

oldOutCode = newOutCode;
oldPos = v;
}```

There are a number of optimizations that can take place with the clipping code above. For example, we can also track an array of dot products so we’re not repeatedly calculating the same dot product over and over again. We could replace our outcode routine with simple compare operations. We could also extend the above routine to handle additional clipping planes.

But this gives us a vector line drawing clipping system that clips in homogeneous coordinates, complete with source code that can be compiled and executed.

What is old is new again; what started as a powerful desktop computer has now appeared as an embedded processor. So it’s good to remember the old techniques as we see more and more microcontrollers show up in the products we use.

# On Memory Leaks in Java and in Android.

Just because it’s a garbage collected language doesn’t mean you can’t leak memory or run out of it. Especially on Android where you get so little to begin with.

Now of course sometimes the answer is that you just need more memory. If your program is a Java command line program to load the entire road map of the United States to do some network algorithms, you probably need more than the default JVM configurations give you.

Sometimes it’s not even a full-on leak, but a large chunk of memory isn’t being released in time as a consequence of some holder object that isn’t being released in time.

There are some tools that can help. With Android, you can use DDMS to get an idea what’s going on, and you can even dump a snapshot of the heap by using the Dump HPROF File option. (You can also programmatically capture uncaught exceptions on startup of your application or activity and dump an hprof file within the exception handler like so:

```public void onCreate(Bundle savedInstanceState)
{
...
{
@Override
{
try {
File f = new File(Environment.getExternalStorageDirectory(),"error.hprof");
String path = f.getAbsolutePath();
Debug.dumpHprofData(path);
Log.d("error", "HREF dumped to " + path);
}
catch (IOException e) {
Log.d("error","Huh?",e);
}
}
});
...
}
```

Of course once you have an .hprof file from Android you have to convert it to something that can be used by an application such as the Eclipse Memory Analyzer tool using the hprof-conv command line application included as part of the Android SDK; there is more information on how to do this and how to use the MAT tool here: Attacking memory problems on Android.

One place where I’ve been running into issues is with a clever little bit of code which loads images from a separate thread from a remote resource, and puts them into a custom view that replaces the ImageView class. This little bit of code creates a background thread which is used to talk to a remote server to download images; once the image is loaded, a callback causes the custom view to redraw itself with the correct contents. A snippet of that code is below:

```/*  Cache.java
*
*  Created on May 15, 2011 by William Edward Woody
*/

package com.chaosinmotion.android.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.HashSet;
import java.util.Map.Entry;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;

public class Cache
{
/**
* Our callback interface
*/
public interface Callback
{
void failure(String url, Throwable th);
}

/**
* Item in the queue which is waiting to be processed by our network thread(s)
*/
private static class QueueItem
{
String url;
Callback callback;

QueueItem(String u, Callback c)
{
url = u;
callback = c;
}
}

private Handler fHandler;
/// The event queue
/// The global cache object, which will be created by the class loader on load.
/// Because this is normally called from our UI objects, this means our Handler
/// will be created on our UI thread
public static Cache gCache = new Cache();

/**
*/
{
public void run()
{
// Start HTTP Client
HttpClient httpClient = new DefaultHttpClient();

for (;;) {
/*
* Dequeue next request
*/
QueueItem q;

synchronized(fQueue) {
while (fQueue.isEmpty()) {
try {
fQueue.wait();
}
catch (InterruptedException e) {
}
break;
}

/*
* Get the next item
*/
q = fQueue.removeLast();
}

/*
*/

try {
/*
* Set up the request and get the response
*/
HttpGet get = new HttpGet(q.url);
HttpResponse response = httpClient.execute(get);
HttpEntity entity = response.getEntity();

/*
* Get the bitmap from the URL response
*/
InputStream is = entity.getContent();
final Bitmap bmap = BitmapFactory.decodeStream(is);
is.close();

entity.consumeContent();

/*
*/
final QueueItem qq = q;
fHandler.post(new Runnable() {
public void run()
{
}
});
}
catch (final Throwable ex) {
final QueueItem qq = q;
fHandler.post(new Runnable() {
public void run()
{
qq.callback.failure(qq.url,ex);
}
});
}
}

//            httpClient.getConnectionManager().shutdown();
}
}

/**
* Start up this object
*/
private Cache()
{
fHandler = new Handler();
th.setDaemon(true);
th.start();
}

/**
* Get the singleton cache object
*/
public static Cache get()
{
return gCache;
}

/**
* Get the image from the remote service. This will call the callback once the
* @param url
* @param callback
*/
public void getImage(String url, Callback callback)
{
synchronized(fQueue) {
fQueue.notify();
}
}
}
```

Now what this does is rather simple: we have a queue of items which are put into a linked list, and our background thread loads those items, one at a time. Once the item is loaded, we call our callback so the image can then be handled by whatever is using the service to load images from a network connection.

Of course we can make this far more sophisticated; we can save the loaded files to a cache, we can collapse multiple requests for the same image so we don’t try to load it repeatedly. We can also make the management of the threads more sophisticated by creating a thread group of multiple threads all handling network loading.

We can then use this with a custom view class to draw the image, drawing a temporary image showing the real image hasn’t been loaded yet:

```/*  RemoteImageView.java
*
*  Created on May 15, 2011 by William Edward Woody
*/

package com.chaosinmotion.android.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.View;

public class RemoteImageView extends View
{
private Paint fPaint;
private Bitmap fBitmap;
private String fURL;

public RemoteImageView(Context context)
{
super(context);
// TODO Auto-generated constructor stub
}

public void setImageURL(String url)
{
fBitmap = null;
fURL = url;

Cache.get().getImage(fURL, new Cache.Callback() {
public void loaded(String url, Bitmap bitmap)
{
fBitmap = bitmap;
invalidate();
}

public void failure(String url, Throwable th)
{
// Ignoring for now. Could display broken link image
}
});
}

@Override
protected void onDraw(Canvas canvas)
{
if (fPaint == null) fPaint = new Paint();

canvas.drawColor(Color.BLACK);
if (fBitmap == null) return;        // could display "not loaded" image
canvas.drawBitmap(fBitmap, 0, 0, fPaint);
}
}
```

This is a very simple example of our using the Cache object to load images from a background thread. We can make this far more sophisticated; we can (for example) display a “loading” image and a “image link broken” image. We can also alter the reported size during onMeasure to return the size of the bitmap, or we can center the displayed bitmap or scale the bitmap to fit. But at it’s core, we have a simple mechanism for displaying the loaded image in our system.

Can you spot the leak?

I didn’t, at first.

Here’s a hint: Avoiding Memory Leaks

Here’s another: the RemoteImageView, being a child of the View class, holds a reference to it’s parent, and up the line until we get to the top level activity, which holds a reference to–well–just about everything.

No?

Okay, here goes.

So when we call:

```        Cache.get().getImage(fURL, new Cache.Callback() { ... });
```

The anonymous inner class we create when we create our callback holds a reference to the RemoteImageView. And that inner class doesn’t go away until after the image is loaded. So if we have a few dozen of these and a very slow connection, the user switches from one activity to another–and we can’t let the activity go, because we’re still waiting for the images to load and be copied into the image view.

So while it’s not exactly a memory leak, the class can’t be let go of, nor can all the associated resources, until our connection completes or times out. In theory it’s not a leak, exactly, because eventually the memory will be released–but it won’t be released soon enough for our purposes. And so we crash.

So how do we fix this?

Well, we need to add two things. First, we need to somehow disassociate our view from the anonymous inner class so that, when our view no longer exists, the callback class no longer holds a reference to the view. That way, the activity can be reclaimed by the garbage collector even though our callback continues to exist. Second, we can remove the unprocessed callbacks so they don’t make a network call to load an image that is no longer needed.

To do the first, we change our anonymous inner class to a static class (that way it doesn’t hold a virtual reference to ‘this’), and explicitly pass a pointer to our outer class to it, one that can then be removed:

```/*  RemoteImageView.java
*
*  Created on May 15, 2011 by William Edward Woody
*/

package com.chaosinmotion.android.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.View;

public class RemoteImageView extends View
{
private Paint fPaint;
private Bitmap fBitmap;
private String fURL;
private OurCallback fCallback;

public RemoteImageView(Context context)
{
super(context);
// TODO Auto-generated constructor stub
}

private static class OurCallback implements Cache.Callback
{
private RemoteImageView pThis;

OurCallback(RemoteImageView r)
{
pThis = r;
}

public void loaded(String url, Bitmap bitmap)
{
if (pThis != null) {
pThis.fBitmap = bitmap;
pThis.invalidate();
pThis.fCallback = null; // our callback ended; remove reference
}
}

public void failure(String url, Throwable th)
{
// Ignoring for now. Could display broken link image
if (pThis != null) {
pThis.fCallback = null; // our callback ended; remove reference
}
}
}

public void setImageURL(String url)
{
fBitmap = null;
fURL = url;

fCallback = new OurCallback(this);
Cache.get().getImage(fURL, fCallback);
}

@Override
protected void onDraw(Canvas canvas)
{
if (fPaint == null) fPaint = new Paint();

canvas.drawColor(Color.BLACK);
if (fBitmap == null) return;        // could display "not loaded" image
canvas.drawBitmap(fBitmap, 0, 0, fPaint);
}

@Override
protected void onDetachedFromWindow()
{
// Detach us from our callback
if (fCallback != null) fCallback.pThis = null;

super.onDetachedFromWindow();
}
}
```

The two biggest changes is to create a new static OurCallback class which holds a reference to the view being acted on. We then hold a reference to the callback that is zeroed out when the callback completes, either on failure or on success. Then on the onDetachedFromWindow callback, if we have a request outstanding (because fCallback is not null), we detach the view from the callback. Note that because all the calls in the callback are done on the UI thread we don’t need to synchronize access.

This will now detach the view from the callback when the view goes away, so the activity that contains the view can be reclaimed by the memory manager.

Our second change is to remove the request from the queue, so we don’t use unnecessary resources. While not strictly necessary for memory management purposes, it helps our network performance. The change here is to explicitly remove our callback from the queue.

First, we change our onDetachedFromWindow() call to remove us (by callback) from the cache:

```    @Override
protected void onDetachedFromWindow()
{
// Detach us from our callback
if (fCallback != null) {
fCallback.pThis = null;
Cache.get().removeCallback(fCallback);
}

super.onDetachedFromWindow();
}
```

Second, we add a method to the cache to look for all instances of requests with the same callback, and delete the request from the queue. If it isn’t in the queue, it’s probably because the request is now being acted upon by our networking thread. (If we were particularly clever we could signal our networking thread to stop the network request, but I’m not going to do that here.)

So our method added to the Cache is:

```    /**
* Remove from the queue all requests with the specified callback. Done when the
* result is no longer needed because the view is going away.
* @param callback
*/
public void removeCallback(Callback callback)
{
synchronized(fQueue) {
Iterator iter = fQueue.iterator();
while (iter.hasNext()) {
QueueItem i = iter.next();
if (i.callback == callback) {
iter.remove();
}
}
}
}
```

This iterates through the queue, removing entries that match the callback.

I’ve noted this on my list of things not to forget because this (and variations of this) comes up, with holding references to Android View objects in a thread that can survive the destruction of an activity.

The basic model is when the view goes away (which we can detect with a callback to onDetachedFromWindow), to disassociate the callback from the view and (preferably) to kill the background thread so the view object (and the activity associated with that view) can be garbage collected in a timely fashion.

# Some observations on the polygon intersection algorithm in Chapter 2 of Computational Geometry: Algorithms and Applications.

I’m building a CSG library because eventually I’d like to have a native Macintosh editor drive my MakerBot. Building a CSG algorithm that uses BSP trees to handle the 3 dimensional math is pretty trivial; the algorithm I’m using came from the paper “Improved Binary Space Partition Merging” by Lysenko et.al., which itself uses the convex hull algorithm outlined in “Linear Programming and Convex Hulls Made Easy” by Seidel.

The problem is, once you have a BSP representation of your object, you need to turn it back into a collection of polygons. And that means a good 2D polygon manipulation engine. (I’m converting directly from a BSP tree to polygons; the way this works is to define a cube bounding the entire BSP tree (by picking one that is “big enough”), then recursing down the BSP tree structure, splitting that cube as you go. At the bottom, you throw away or return the split cube, and “glue it back together” as you come back up the tree. This implies that on return you have to glue arbitrary polygon shapes on both sides of a split plane together–and on the polygon surface, that means doing a 2 dimensional XOR operation on the polygons there.)

So I’ve been going through the book “Computational Geometry” trying to implement the intersection algorithm outlined in Chapter 2 there.

And I have a few observations.

(1) The exposition of the algorithm is geared more towards a general discussion of the algorithm rather than providing a complete description of the algorithm in a way that is suitable for implementation. That means implementing the algorithm requires a fundamental understanding of what’s going on; you can’t just look at the outline of the algorithm and convert it to code. And you need to discover using various data sets the gaps in your implementation and find where things go south.

(2) The algorithm fundamentally relies on the data structure in section 2.2, which uses half-edges to represent each ring. The half edges must be complete: that is, if you have just a naked polygon sitting in an otherwise empty space, you need both the inner ring representing the inside, and an outer ring of edges which represent the outer boundary. You can’t get away with unpaired half-edges and easily make this thing work. No shortcuts.

(That’s because when two half edges intersect (figure 2.5, section 2.3), you need to tie together the half edges that meet at the point–and sometimes an inner edge pairs with an outer edge and visa-versa. Imagine two polygons intersecting: the outer edges of the two polygons form the inner edges of the penetrating part of the two outer polygons of the intersection.)

You can be excused, by the way, in thinking the half planes could be naked and not have a matching half-edge for an outer defined polygon, given the discussion of monotone polygons and polygon triangulation in Chapter 3 works with naked half-edge polygon rings.

(3) The algorithm itself also relies on a sorted tree structure that you can search by edge or by point. In C++ or Objective C, that means some additional work. Fortunately the number of polygons are small enough that it’s not worth the overhead of using a balanced tree structure.

(4) The algorithm goes south when two edges are coincident. The trick appears to be throwing away identical half edges that are from S1 and from S2 in Algorithm MapOverlay in section 2.3, at step 1, creating the new doubly-connected edge list D. (In practice you can do this by dropping duplicate edges in step 2, when initializing the event queue Q: as each edge is added to each event in Q, determine if there is already an identical edge already in that event.)

Also, when computing the intersections, if an intersection test creates a new intersection edge that is identical to an existing edge (because the two intersecting edges were coincident but without the same start or end points), throw away the newly constructed edge intersection if they already exist. This means in practice if, while updating the event in Q in algorithm HandleEventPoint in section 2.1 as a result of finding an intersecting edge, when inserting the found segments, verify they aren’t already in the event in FindNewEvent.

(5) The “final step” referred to in the paragraph preceding MapOverlay, discovering which polygon in one overlay subdivision contains the vertices of the other, can be determined by using a sweep algorithm, sweeping on the vertices in both subdivisions S1 and S2, storing the edges of each in their own tree list. At each point, you can then determine which edge of one subdivision is to the left of the point in the other; that leftmost edge determines which polygon contains our vertex.

I’m sure you could probably also do this during the sweep in step 2 of MapOverlay; in fact, we do capture the half edge to the left of the event point, though that half edge is of D, which is the combination of S1 and S2. So it may be a matter of continuing the leftward walk to find representatives of both sets, or simply maintaining two other tree structures at the same time so you can get the leftward edges for D, S1 and S2 at the same time.

At some point, after I successfully get an implementation of my XOR algorithm going correctly, I’m going to write an exposition of this algorithm that isn’t so damned obtuse and which can be more easily implemented as code. Because this article (along with the article describing triangulation of a polygon) feels like it was written by a professor who intuitively knew the algorithms, but was not working from a functional example of the algorithms he was describing when writing the paper.

That’s because the gaps and holes in the exposition are big enough to drive a truck through. (For example, in the description FindNewEvent in section 2.1, we have the values L(p), U(p) and C(p) defined; however, from the description of FindNewEvent it’s unclear what we do at step 2: “Insert the event point as an event into Q.” Given an event contains L(p), U(p) and C(p), what is the event we insert when we insert the event point? And let’s skip by the “However, we won’t explain this final step here. It’s a good exercise to test your understanding of the plane sweep approach to design the algorithm yourself” comment later in the chapter.)

So if you were trying to implement a polygon mesh intersection from this discussion and decided you were just dumb, well, no you’re not: I’ve wasted a couple of months of my spare time trying to sort all this out, and I can tell you: you’re not dumb. The description is incomplete.

# On Memory and Memory Management

This will be a bit of an introductory article on memory, written in part for my wife and for anyone else who may find such an introduction useful.

# In The Beginning…

In the beginning there was RAM, random access memory. A microprocessor which could execute instructions would be attached to that RAM, which could be accessed by special instructions which operated on the contents of that memory.

Some microprocessors (for example, the Z-80) used special instructions which would use two 8-bit integer registers (such as register D and E) to form a 16-bit address into RAM, or would use special registers (the IX and IY index registers) to access memory. Others (such as the 68000 CPU) would have a bank of dedicated address registers which are used to access memory.

Writing software in this era was simple: you would define the location of various objects that would be stored in memory, and you would use those locations to access the stored data.

In today’s modern parlance all objects are fixed and global. There is no allocating objects or releasing those; that came later. Instead, there is just picking the size of the records (or structures) stored in memory, and making sure there is enough space left in RAM for your stack.

Since early microprocessors only had a very small and limited amount of memory, this is fine. Embedded development with toolchains such as the Small Device C Compiler, which can compile code for the HC08 series of CPUs, don’t generally provide any way to allocate memory; instead, you declare all of your objects as global structures.

As an example, a program I’ve been tinkering with on the Arduino platform (and I really believe every high school student who wants to get into programming needs one) emulates a calculator with no memory. The memory declaration looks something like:

```/*  Calculator Storage in RAM */
Double GDisplay;
Double GInput;
Double GScratch;
boolean GIsInput;
boolean GIsClear;
```

When compiled it will compile into an assembler statement that may look something like:

```.EQU GDisplay = 0x0100
.EQU GInput = 0x0108
.EQU GScratch = 0x0110
.EQU GIsInput = 0x0118
.EQU GIsClear = 0x0119
```

Fixed allocation of memory structures also makes sense with certain types of game development, where performance and reliability of the code path is essential. For example, a 3D game such as the early game Descent could store for each level the size of the rendering map and the maximum number of records needed to process and render a level regardless of your location in the maze. Then, when the level loads, the proper amount of memory can be obtained using a function call similar to sbrk, which tells the operating system that you need a fixed amount of RAM, then partition the contents up yourself.

Various compiled games also use this technique, where the game is specified by a specialized game specification language. By being able to walk through all potential states in a game, it would be possible to determine the maximum memory footprint for that game, then request the fixed amount of memory for storage. This technique is used by Zork, amongst other things.

Fixed allocation of memory can also be used for certain high-performance applications where accuracy and speed and stability are paramount. For example, software handling incoming click requests in a search advertising system may wind up handing millions (or even billions) of click requests per minute–given that each click request can be designed as a fixed-sized record (or a record with a maximum known size), click requests can be accumulated into a fixed size array with certain summary data accumulated in global variables during store. Then, when a maximum time (or a maximum number) is reached, the formatted buffer and summary data can be spilled into a single write request into upstream systems which may only need the summary data.

# Then Came The Heap.

Not all programs work well with the fixed allocation of objects. Sometimes you need a linked list of objects, or a heap list, or other more complex data structures where you cannot know a priori the number of records you will be handling.

Heap processing more or less works the same regardless of the programming language: there is a mechanism by which you can request a chunk of memory at a given size, and another call to release that memory. Sometimes there is a call that allows you to resize that memory block; resizing a memory block can be handled by releasing the old block and allocating a new one, copying the contents from one location to another.

Heap allocation works by using a large chunk of RAM dedicated to that heap, and, on a request for a chunk of memory, reserves it in RAM. There are many ways this can be done; the easiest to explain is the greedy algorithm, which reserves the first chunk of memory that can be found.

Allocated memory requires some bookkeeping information so the memory allocation code can know how to handle this chunk of memory: is it allocated, how big is the chunk that is reserved. So when you allocate memory, generally additional space is reserved prior to the address pointer with bookkeeping data; this is then used to resize memory (if resizing is allowed), and to know how much memory to mark as free when the free routine is called.

## A simple malloc() and free()

We can easily implement a simple malloc and free routine to illustrate how a typical heap may work. We’ll make two assumptions, which are common to today’s modern processors. First, all allocated memory will be aligned (for efficiency sake) on a 16-byte boundary. (Some processors address things on 16-byte boundaries far more efficiently.) Second, we will use a four byte bookkeeping object which gives the size of the memory allocated, along with a 1 bit flag indicating if the area of memory is free or still allocated. Because we know all memory is aligned on a 16 byte boundary we know the least significant bit of the 32-bit length will never be used, so we use that bit for the free flag; this way we only need to use 4 bytes for our bookkeeping data.

By sketching out the code for a simple malloc() and free() we can also illustrate some of the interesting bugs that can come up while using the heap, such as accidentally using memory that was freed previously.

Footnote: We use ‘uint8_t’ to refer to 8-bit bytes, and ‘uint32_t’ to refer to 32-bit bytes. Because on most modern operating systems, memory can be addressed on a byte boundary, we can add or subtract from an address pointer by converting that pointer to a pointer to a byte object. For example:

```a = (uint32_t *)(((uint8_t *)a) + 3);
```

The expression above will add 3 to the address register in ‘a’, pointing three bytes in from where it was pointing before.

Notice if we were doing this for a microprocessor with 16-bit addresses, we could use a uint16_t, or 2 byte integer, for the bookkeeping area instead.

Before we can use the memory, we must initialize the memory heap area to note that the entire heap is free. This means we need to set up a bookkeeping header that indicates that all of memory (minus the area for bookkeeping) is free. We also need to make sure the free memory itself is aligned on a 16 byte boundary–which means we must waste the first 12 bytes of memory. More advanced memory allocation schemes may make use of that area for other bookkeeping information, but for now we simply waste the memory.

When initialized our RAM area will look like:

Our initialization routine will look like:

```/*	initialize_ram
*
*		Given the block of ram memory, we mark the entire
*	block as free. We do this by setting up free block 16
*	bytes in; we do this so that the first allocated block
*	will be aligned on a 16 byte boundary. This wastes the
*	bottom 12 bytes of memory which could, for a more
*	sophisticated system, be used for other stuff.
*
*		We have GRam point to the first byte of RAM, and
*	RAMSIZE is the size of the RAM area being managed.
*/

void initialize_ram()
{
/* Find the location of the bookkeeping block for this.
* The address is 12 bytes in; 16 bytes for alignment
* minus 4 bytes for the bookeeping area
*/

uint32_t *bookkeeping = (uint32_t *)(((uint8_t *)GRam) + 12);

/*
*	Now mark the memory as free. The free size is 16
*	bytes smaller than the max ram size, and mark it
*	as free. We assume RAMSIZE is divisible by 16.
*/

*bookkeeping = (RAMSIZE - 16) | 1;

/*
*	And finally mark the end bookkeeing block. Because of the way
*	we allocate memory, the top 4 bytes must be specially
*	marked as a reserved block. That's so we know we have
*	hit the top.
*/

bookkeeping = (uint32_t *)(((uint8_t *)GRam) + RAMSIZE - 4);
*bookkeeping = 4;		// marked as reserved 4 bytes.
}
```

Free is simple. Because our convention is that a block of memory is considered free if the least significant bit of the 32-bit bookkeeping area is set, free simply sets that bit.

```/*	free
*
*		Free memory. This works by finding the bookkeeping block
*	that is 4 bytes before the current pointer, and marking the
*	free bit.
*/

void free(void *ptr)
{
/*
*	Subtract 4 bytes from the current pointer to get the
*	address of the bookkeeping memory
*/

uint32_t *bookkeeping = (uint32_t *)(((uint8_t *)ptr) - 4);

/*
*	Mark the memory as free by setting the lowest bit
*/

*bookkeeping |= 1;
}
```

Most of the meat of our memory management system will be in the alloc call. This has to scan through all the free blocks, finding the first chunk of memory that can be reserved. We also, by convention, return NULL if there is no memory left that can be allocated.

The first thing our allocation routine does is find out how big a chunk of memory we need to reserve. Because we must guarantee everything is aligned on a 16-byte boundary, this means a request for 2 bytes must reserve 16 bytes; that way, the next allocation request will also be aligned correctly. (More sophisticated memory management systems may know enough to subdivide memory for smaller allocation requests; we don’t do that here.)

So we must calculate the size, including the extra 4 bytes needed for our bookkeeping block:

```	/*
*	Step 1: Change the size of the allocation to align
*	to 16 bytes, and add in the bookkeeping chunk that
*	we allocate. Our pointer will return the first
*	byte past the bookkeeping memory.
*/

size = size + 4;		// Add bookkeeping
if (0 != (size % 16)) size += 16 - (size % 16);	// align
```

Next, we need to scan through memory from the first block in memory, searching for a collection of free blocks which are big enough for us to reserve for our requested block.

```	/*
*	Step 2: scan to find a space where this will fit.
*	Notice that we may have to piece together multiple
*	free blocks, since our free doesn't glue together
*	free blocks.
*/

ptr = (uint32_t *)(((uint8_t *)GRam) + 12);
end = (uint32_t *)(((uint8_t *)GRam) + RAMSIZE);
while (ptr < end) {
if (0 == (1 & *ptr)) {
/* Lowest bit is clear; this is allocated memory. */
/* The bookkeeping area holds the total size of the */
/* the next block by adding the bookkeeping area */
/* to the current block. */
ptr = (uint32_t *)(((uint8_t *)ptr) + *ptr);
} else {
/*
*	This area is free. Note that this is found, then
*	start scanning free areas until we piece together
*	something big enough to fit my request
*/

found = ptr;
asize = *ptr & ~1UL;		// Get the size, clearing free bit
ptr = (uint32_t *)(((uint8_t *)ptr) + (*ptr & ~1UL));	// next block
while ((asize < size) && (ptr < end)) {
if (0 == (1 & *ptr)) {
/* We bumped against an allocated block of memory */
/* Exit this loop and continue scanning */
break;
}

/* Block is free. Add it up to this block and continue */
asize += *ptr & ~1UL;
ptr = (uint32_t *)(((uint8_t *)ptr) + (*ptr & ~1UL));	// next block
}
if (asize = end) return NULL;		// Could not find free space
```

This gets a bit complicated.

First, we set ptr and end to point to the start block and the end of memory, respectively. Next, we walk through while our pointer has not reached the end, looking for free memory.

Now our free() routine simply marks the memory as free; it doesn’t gather up blocks of free memory and glue them together. So our allocation routine has to do the job. When we first encounter a free block, we note how much memory the free block represents in asize, and we put the start of that free block in found. We then continue to scan forward until we either piece enough memory together to satisfy the size we need, or until we find a reserved block which prevents us from using this chunk of free memory.

If we run out of memory: that is, if the pointer ptr goes past end, then we can’t satisfy this request, so we return NULL.

Now that we’ve found a chunk of memory that satisfies our request, we piece together the free blocks, breaking the last free block in the list of free blocks if needed.

When this chunk of code is reached, found points to the start of our free memory, and ptr points to the last free block in the list of free blocks that may need to be split.

We write the correct bookkeeping data to mark the memory as allocated, and if that is shy of the end of the free blocks, we then write a free block bookkeeping mark:

```	/*
*	Step 3: mark the block as allocated, and split the last free block
*	if needed
*/

*found = size;						// mark the size we've allocated.
if (size < asize) {
/* We have more than enough memory. Split the free block */
/* First, find the pointer to where the free block should go */
ptr = (uint32_t *)(((uint8_t *)found) + size);

/* Next, mark this as a free block */
ptr = (asize - size) | 1;
}
```

This works correctly because asize is the total size of the range of free blocks we just glued together, so (uint8_t *)found + asize will point to the next block of memory past the free memory we just found.

Now that we’ve peeled off a chunk of memory, we need to return the memory itself. Up until now our pointers have been pointing at the first byte of the 4-byte bookkeeping record; the memory we’re allocating is just past that 4 byte record. So we need to return the first byte of our allocated memory itself:

```
/*
*	The found pointer points to the bookkeeping block. We need to
*	return the free memory itself, which starts with the first byte
*	past the bookkeeping mark.
*/

return (void *)(((uint8_t *)found) + 4);
```

Putting our alloc routine together we get:

```/*	alloc
*
*		Allocate the requested memory by scanning the heap
*	of free blocks until we find something that will fit.
*	We then split the free blocks and return the allocated
*	memory.
*
*		If we are out of memory, we return NULL.
*/

void *alloc(uint32_t size)
{
uint32_t *ptr;
uint32_t *end;
uint32_t *found;
uint32_t asize;

/*
*	Step 1: Change the size of the allocation to align
*	to 16 bytes, and add in the bookkeeping chunk that
*	we allocate. Our pointer will return the first
*	byte past the bookkeeping memory.
*/

size = size + 4;		// Add bookkeeping
if (0 != (size % 16)) size += 16 - (size % 16);	// align

/*
*	Step 2: scan to find a space where this will fit.
*	Notice that we may have to piece together multiple
*	free blocks, since our free doesn't glue together
*	free blocks.
*/

ptr = (uint32_t *)(((uint8_t *)GRam) + 12);
end = (uint32_t *)(((uint8_t *)GRam) + RAMSIZE);
while (ptr < end) {
if (0 == (1 & *ptr)) {
/* Lowest bit is clear; this is allocated memory. */
/* The bookkeeping area holds the total size of the */
/* the next block by adding the bookkeeping area */
/* to the current block. */
ptr = (uint32_t *)(((uint8_t *)ptr) + *ptr);
} else {
/*
*	This area is free. Note that this is found, then
*	start scanning free areas until we piece together
*	something big enough to fit my request
*/

found = ptr;
asize = *ptr & ~1UL;		// Get the size, clearing free bit
ptr = (uint32_t *)(((uint8_t *)ptr) + (*ptr & ~1UL));	// next block
while ((asize < size) && (ptr < end)) {
if (0 == (1 & *ptr)) {
/* We bumped against an allocated block of memory */
/* Exit this loop and continue scanning */
break;
}

/* Block is free. Add it up to this block and continue */
asize += *ptr & ~1UL;
ptr = (uint32_t *)(((uint8_t *)ptr) + (*ptr & ~1UL));	// next block
}
if (asize = end) return NULL;		// Could not find free space

/*
*	Step 3: mark the block as allocated, and split the last free block
*	if needed
*/

*found = size;						// mark the size we've allocated.
if (size < asize) {
/* We have more than enough memory. Split the free block */
/* First, find the pointer to where the free block should go */
ptr = (uint32_t *)(((uint8_t *)found) + size);

/* Next, mark this as a free block */
ptr = (asize - size) | 1;
}

/*
*	The found pointer points to the bookkeeping block. We need to
*	return the free memory itself, which starts with the first byte
*	past the bookkeeping mark.
*/

return (void *)(((uint8_t *)found) + 4);
}
```

We can now use this code to illustrate some interesting things about heap memory allocation.

First, notice how free() simply marks the memory as free, but without overwriting the memory. This is why the following code, while quite illegal, can still work:

```int error1()
{
/* Allocate some memory and initialize it */
int *someWord = (int *)alloc(sizeof(int));
*someWord = 5;

/* Free the memory */
free(someWord);

/* Now access the freed memory */
return *someWord;
}
```

This is not guaranteed to work. Far from it, it’s illegal to access memory that was released after it was released–you don’t know what is going to happen to that chunk of memory. But in most cases, it’s simply marked as no longer reserved–but the values are still there in memory.

And this becomes a problem if the memory is reallocated to some other pointer which does something else with the memory:

```int error2()
{
/* Allocate some memory and initialize it */
int *someWord = (int *)alloc(sizeof(int));
*someWord = 5;

/* Free the memory */
free(someWord);

/* Allocate some other memory */
int *someOtherWord = (int *)alloc(sizeof(int));
*someOtherWord = 6;

/* Now access the freed memory */
return *someWord;
}
```

What makes bugs like this very frustrating to find is that, in general, the patterns of allocs and frees are not quite so uniform. It can be quite unpredictable; for example, while the above probably will cause 6 to be returned using our version of alloc and free, the following may or may return 5 or 6 or even some other value, depending on how memory has been fragmented in the past:

```int error3()
{
/* Allocate some memory and initialize it */
int *someWord = (int *)alloc(sizeof(int));
*someWord = 5;

/* Free the memory */
free(someWord);

/* Allocate some other memory */
int *someOtherWord = (int *)alloc(sizeof(28));
*someOtherWord = 6;

/* Now access the freed memory */
return *someWord;
}
```

Because the size of the second allocation is different than the first, it may or may not use the previously allocated memory.

Second, over time memory can fragment. Fragmentation can cause things to slow down over time, and they can even put you in the situation where after doing a bunch of small allocations and frees, you may still have plenty of memory left–but no block is large enough to put your request.

Different memory management methods attempt to resolve this problem using various techniques, of course–and on most modern operating systems there is plenty of memory so fragmentation is unlikely.

As an aside, sometimes it is useful to allocate a whole bunch of tiny little objects and release them all at once. For example, a 3D rendering program may dynamically allocate a whole bunch of objects during rendering–but free them only after the entire image is drawn on the screen.

To do this you can allocate large chunks of memory, then subdivide the memory as needed, keeping the large allocated chunks of memory in a linked list, so when it comes time to free all of memory, the free operation can be done in one call.

Another interesting thing to point out is that memory has to be explicitly allocated or freed. We are just one step above address registers in the microprocessor; our heap is something we must manually maintain. If we set a pointer to a new address, and we don’t free the memory that our pointer used to be pointing to, the free() routine has no idea that our memory must be freed.

In C and C++ this is the status quo: you must explicitly allocate or free memory. C++ adds the concept of ‘new’ and ‘delete’ which call a class constructor after the memory is allocated and the class destructor before the memory is freed; however, memory must still be explicitly allocated or freed.

In a world where there is only global memory, auto (stack-based) memory and heap memory this works okay. But once we start talking about object-oriented programming it is natural for us to talk about two pointers pointing to the same object in memory. And knowing when that object should be freed() becomes far more complicated than in the traditional procedural-based allocation scheme where we guarantee by convention that only one pointer holds onto a chunk of memory at a time.

And there are two ways we can solve this problem: resource counting and garbage collection.

# Garbage Collection

Garbage collection is a technique whereby the operating system will automatically find memory that is no longer being used. The advantage of garbage collection is that you don’t have to remember to call free(). The disadvantage is that garbage collection can be computationally expensive and hard to get right.

There are several ways to handle garbage collection. The technique I’ll outline here is the simple mark and sweep technique to find (and mark) all memory that is currently being used, then sweeping through and freeing memory that is not marked.

Essentially it works like this.

With each allocated chunk of memory, we also reserve a bit used to mark that memory. From our allocator above, we could use the second to least significant bit to represent marking. We need a mark routine to mark the memory as such:

```/*	mark
*
*		This marks memory. This marks the pointer by flipping the mark
*	bit
*/

void mark(void *ptr)
{
if (ptr == NULL) return;

/*
*	Subtract 4 bytes from the current pointer to get the
*	address of the bookkeeping memory
*/

uint32_t *bookkeeping = (uint32_t *)(((uint8_t *)ptr) - 4);

/*
*	Mark the memory by setting the second lowest bit
*/

*bookkeeping |= 2;
}
```

The first step to garbage collection is to do the mark phase: to mark all of the memory that is currently referred to by other chunks of memory in our system. To do this we use a ptr variable which points at the current block; as we sweep forward across all the blocks in the system, if we find a block that is marked, we then try to find all the pointers in that block, and mark them. This repeated marking continues until we no longer have any new memory blocks that need to be marked.

After we’ve done this marking, we sweep, freeing all blocks of memory that is not marked.

The hard part of any memory collection mechanism is to know in global memory and on the stack which are the address pointers and which are not. Languages such as Java keep class information around to allow the garbage collector to know exactly which things in memory refer to address pointers. Other languages, such as C, do not maintain this information–and so the garbage collector effectively “guesses.”

We assume in our code we have three methods: one which will mark all pointers in global memory and on the stack, another which returns the number of pointers inside an allocated memory object, and a third which returns the pointers in an allocated memory object.

```/*	allocGC
*
*		Allocate but with a garbage collector. We do the mark/sweep phase
*	on memory. We rely upon two other calls: a call to mark all pointers in
*	global memory and on the stack, and a call which can tell us within an
*	allocated chunk of memory which are the pointers by marking them.
*
*		In both cases we assume the mark routine will call mark() above
*	to mark the memory as in use
*/

void *allocGC(uint32_t allocLen)
{
uint32_t *ptr;
uint32_t *end;
uint32_t *tmp;
uint32_t *tmp2;
uint16_t len,i;

/*
*	Try to allocate
*/

ptr = alloc(allocLen);

/*
*	Out of memory?
*/

if (ptr == NULL) {
/*
*	Out of memory; do garbage collection. First, clear the mark
*	bits for allocated memory
*/

ptr = (uint32_t *)(((uint8_t *)GRam) + 12);
end = (uint32_t *)(((uint8_t *)GRam) + RAMSIZE);
while (ptr < end) {
*ptr &= ~2UL;		// clear second least bit
// move to next block in memory
ptr = (uint32_t *)(((uint8_t *)ptr) + (*ptr & ~1UL));
}

/*
*	Now ask to mark memory on the stack and in global heap space
*/

markGlobalStack();

/*
*	Run through and mark all references. We rely upon the
*	routines numPointersInAllocBlock and pointerInAllocBlock
*	to return the pointers inside a block
*/

ptr = (uint32_t *)(((uint8_t *)GRam) + 12);
while (ptr < end) {
/*
*	If this pointer is marked, then find all the pointers that
*	are inside this pointer, and mark them, moving the pointer
*	backwards to the earliest unmarked object
*/

if (0 != (*ptr & 2)) {
/*
*	Memory marked. Find all the pointers inside
*/

tmp2 = ptr;
len = numPointersInAllocBlock(ptr);
for (i = 0; i  tmp2) tmp2 = tmp;
*tmp &= 2;
}
}

/*
*	We may have moved tmp2 before ptr; this means we need
*	to pick up sweeping from tmp2, since we have a pointer
*	pointing backwards in memory
*/

ptr = tmp2;
}

/*
*	Move to next block
*/

ptr = (uint32_t *)(((uint8_t *)ptr) + (*ptr & ~1UL));
}

/*
*	Now that we've gotten here, we need to free all allocated memory
*	that is not marked
*/

ptr = (uint32_t *)(((uint8_t *)GRam) + 12);
while (ptr < end) {
if (0 == (0x3 & *ptr)) {		// allocated, unmarked?
*ptr |= 1;					// mark as freed
}
/*
*	Move to next block
*/

ptr = (uint32_t *)(((uint8_t *)ptr) + (*ptr & ~1UL));
}

/*
*	Now try again
*/

ptr = alloc(allocLen);
}
return ptr;
}
```

Essentially our garbage collector starts by sweeping all memory and clearing the mark bit.

We start by marking all the objects (using markGlobalState) that are pointed to by objects on the stack, or by objects in global memory:

Now we start in the loop to run through the blocks. Our ptr routine searches for the next marked block of memory, and then marks all the blocks that object points to:

We continue to mark foward, moving the pointer backwards only if we encounter a pointer to an earlier block in memory that is currently unmarked. This rewinding of the pointer is necessary to handle backwards pointing references without having to rewalk all of the blocks from the start of the heap:

(Because this pointer refers to something before the previous pointer, we move our pointer backwards:)

Once we’re done–and this is guaranteed to complete because there is only a finite number of objects, and we only rewind the pointer when something is unmarked–we then sweep through all of memory, marking as free objects we were unable to reach. We know these objects are freed because we could not reach them:

# Reference Counting

Garbage collection is very difficult to do correctly. You need to have a method, no matter in what state you’re in, to know where the pointers are, and what they point to. And you have to have a way to look inside of every object and know what chunks of memory in the heap are pointers, in order to correctly mark things.

In other words, you need to provide markGlobalState, numPointersInAllocBlock, and pointerInAllocBlock or the equivalent.

An easier way to track the pointers pointing to an object is by tracking a reference count associated with each object. This requires some work on the part of the developer; in fact, it requires that you explicitly call routines similar to alloc and free to keep track of the reference count to a collection of objects. On the other hand, it doesn’t require a lot of work to get working correctly. And this technique has been adopted by Microsoft’s COM system and Apple’s Objective-C on the Macintosh or iOS operating systems.

(Yes, I know the latest versions of Objective C on the Macintosh provide garbage collection. However, you can still do reference counting, and you must do reference counting on iOS.)

Reference counting is extremely easy to do. Essentially it involves having the objects you want managed via reference counting internally store a reference count. Newly allocated objects set the reference count to 1, and if the reference count reaches zero, the object frees itself.

In C++ we can easily declare a base object for reference counting:

```class BaseObject
{
public:
BaseObject();

void			Retain();
void			Release();

protected:
virtual		~BaseObject();

private:
uint32_t		fRefCount;
};
```

Our base class stores a reference count, called fRefCount. When we allocate our object, we first set the reference count to 1:

```BaseObject::BaseObject()
{
fRefCount = 1;
}
```

We then need to mark something as retained: meaning there is a new pointer pointing to the same object. The retain method can be written:

```void BaseObject::Retain()
{
++fRefCount;
}
```

Releasing the object then decrements the count, and if the count reaches zero, frees the object:

```void BaseObject::Release()
{
if (0 == --fRefCount) {
delete this;
}
}
```

In Objective C (but not on Microsoft COM) we have an additional method, called “autorelease”, which adds the object to an NSAutoreleasePool, which automatically calls release when the pool is drained, either explicitly or implicitly at the end of each event loop. In C++ we can do something similar by extending our base class by adding an array of object pointers:

```class BaseObject
{
public:
BaseObject();

void			Retain();
void			Release();
void			AutoRelease();

static void	Drain();

protected:
virtual		~BaseObject();

private:
uint32_t		fRefCount;
static std::vector gPool;
};
```

We then add an AutoRelease and a Drain methods:

```void BaseObject::AutoRelease()
{
gPool.push_back(this);
}

void BaseObject::Drain()
{
/* Run through our array of objects */
int i,len = gPool.size();
for (i = 0; i Release();
}
/* Now erase the array */
gPool.clear();
}
```

Notice that simple assignment of pointers doesn’t actually call Retain or Release anymore than it automatically called alloc() and free() described earlier. Instead, we must use a coding convention to know when we should Retain, when we should Release, and (if present) when we should AutoRelease.

The Microsoft COM rules are quite simple: if a function call returns a pointer, you must release that pointer in your routine when you are no longer using it. So, for example, suppose we have a routine GetThing() which returns a BaseObject:

```BaseObject *GetThing()
{
return new BaseObject();
}
```

Then a caller must in turn release the value:

```void UseBaseThing()
{
BaseObject *obj = GetThing();

/* Do some stuff to this */

obj->Release();
}
```

Now if the routine GetThing is returning a reference to an object that it is storing in memory, then when the object is returned, the routine’s return value “owns” the reference to that global object, but the ownership must continue to be held locally. So you would use Retain:

```BaseObject *gPtr;

BaseObject *GetThing()
{
gPtr->Retain();
return gPtr;
}
```

And similarly, if the caller function wants to hold onto the pointer (say, by storing it in a global variable), rather than call retain we simply keep ownership of the pointer:

```BaseObject *gPtr2;

void UseBaseThing()
{
BaseObject *obj = GetThing();
/* Store object; don't release it--we still own the reference. */
gPtr2 = obj;
}
```

The rule is quite simple: if a pointer is returned, the pointer must be released. But it adds complexity: it means you must constantly be calling the ‘Release’ method all the time, and that can become quite cumbersome.

On the other hand, and the key point to all of this, is that the retain and release rules are simple–and they are local: you don’t need to know how any other module in the system works, you only need to know what to do locally.

Apple gets around the problem of constantly having to release objects (and retain objects that are held locally) by introducing the -autorelease method.

On the Macintosh (and iOS), the rules are given on Apple’s web site. The two rules are:

(1) You gain ownership of an object only if you create it (using -alloc or any method that starts with ‘new’, or contains ‘copy’), or if you explicitly retain the object.

(2) You release or autorelease the object when you no longer need to hold ownership of the object.

Using these two rules, we wind up writing less code–but things can get a little more complicated. In our example above, our ‘GetThing’ routine, because it does not start with ‘new’, would simply return the object:

```BaseObject *gPtr;
+ (BaseObject *)getThing
{
return gPtr;
}
```

If we were allocating this object (as in our first example), we would, because of the naming convention either rename our method to ‘newThing’:

```+ (BaseObject *)newThing
{
return [[BaseObject alloc] init];
}
```

Or we would need to make sure that ownership is not passed up by marking the object as autorelease:

```+ (BaseObject *)getThing
{
return [[[BaseObject alloc] init] autorelease];
}
```

In fact, this pattern is so common you’ll find yourself typing “alloc] init] autorelease]” nearly on autopilot.

The call “UseBaseThing” is similarly changed, depending on how we’re using it. If we don’t hold onto a reference to the object, we would not need to call ‘release’ because we aren’t hanging onto the object:

```+ (void)useBaseThing
{
BaseObject *obj = [BaseObject getThing];

/* Do some stuff to this */
/* Notice we don't release this object */
}
```

And if we are hanging onto the object, we must retain the object:

```+ (void)useBaseThing
{
BaseObject *obj = [BaseObject getThing];
gPtr2 = [obj retain];
}
```

Likewise, if we are calling newThing, we’d be getting ownership back from the call–so we would need to release it as appropriate. So, our examples would be:

```+ (void)useBaseThing
{
BaseObject *obj = [BaseObject newThing];

/* Do some stuff to this */

[obj release];
}
```

And, if holding the object, we already have ownership, so we don’t need to release it:

```+ (void)useBaseThing
{
BaseObject *obj = [BaseObject getThing];
gPtr2 = obj;
}
```

Notice in all of the above, simply assigning or copying pointers around in a pointer doesn’t actually do anything on its own. A pointer is simply like an integer, but with the integer referring to an address in memory. In all of this evolution from fixed locations in RAM to garbage collection and object reference counting, we have never changed the immutable fact that simply copying or adding values to an address doesn’t affect how heap memory is handled. Garbage collection takes place after an object is no longer pointed to–and sometimes objects that are no longer referenced by a pointer can live for a very long time.

There are other subtleties that can take place here: different versions of memory management tools may do different things when a chunk of memory is allocated or freed. Some test tools may even store the location in a program where an object is allocated, so if there is an unbalanced alloc/free cycle, the line of code in error can be discovered easily. And there are many flavors of garbage collection out there which each behave differently, though ultimately result in the same end.

Further, with reference counting, cycles of objects can easily be created which cause the objects to linger long after those objects are no longer actually in use. It’s why it is important to think about cycles of pointers, especially when developing UIView objects which may hold references to other UIViews to perform certain operations.

In fact, a very common bug is to create one UIView that refers to another:

```@class BView;
@interface AView : UIView
{
BView *view;
}

@property (retain) BView *view;
@end

@interface BView : UIView
{
AView *view;
}

@property (retain) AView *view;
@end
```

The problem here is that if AView and BView are part of the same view hierarchy, and are assigned to each other, then when the view hierarchy is released, AView and BView retain each other–preventing the memory from being reclaimed even though it is no longer being used.

In cases like this, when a third object holds two others which refer to each other–in this case, implicitly, by the UIWindow holding all of the views in the view hierarchy–it is better if only an unretained reference is held to these objects instead:

```@class BView;
@interface AView : UIView
{
BView *view;
}

@property (assign) BView *view;
@end

@interface BView : UIView
{
AView *view;
}

@property (assign) AView *view;
@end
```

Assignment is not ownership, and when the window is released, AView and BView will both be released successfully.

Hopefully this brief overview of memory management, from setting fixed locations in RAM to heaps to garbage collection and reference counting, will give you a good idea of how memory management actually works–and what the pitfalls are.

The key takeaways should be:

(1) Assigning pointers is not ownership. Simply writing Pointer *a = b; doesn’t actually grant ownership to ‘a’ when it points to ‘b’. You must, unless in a garbage collection environment, explicitly ask for and release ownership.

(2) If not using reference counting, the assumption is that only one pointer actually “owns” an object. For object-oriented programming this is too strict a restriction, and thus we must either introduce garbage collection or establish reference counting and conventions on how references are counted.

(3) For reference counting systems, there are (to my knowledge) two conventions for reference counting: the Microsoft COM convention, and the Apple Objective-C convention. You must also be aware of cyclical ownership references: if you accidentally grant ownership that turns into a cycle or ring of ownership, objects may leak because they mutually refer to each other, without actually being used anywhere else.

# I love Wikipedia.

The other day I had to hook up some code via JSON. Having no idea what JSON is, I looked on Wikipedia. Basic data types, examples, syntax, and a link to RFC 4627 later, and I was set. Cool!

I wanted to implement a hash map, but I wasn’t sure if I wanted to do what I’ve done in the past, which is to represent each hash bucket with a linked list, or if I wanted to use a list. Unsure of the pros and cons, I looked up Hash tables on Wikipedia and got a reasonable overview discussion.

I’m finding there is a lot on Wikipedia that provides a good cursory overview of different protocols and algorithms, and more importantly, points me to the relevant research, descriptions or RFCs which describe the thing in greater detail. And while I tend to take Wikipedia with a grain of salt (you never know if the guy who wrote the article knew what he was talking about, or if the page was vandalized), the cursory overview (even inaccurate) combined with pointers to scholarly research or published standards makes a great reference.

I know this is old news: however, in the past few days I’ve found myself using Wikipedia as a starting point for a lot of CS related searches.

# Computer Languages and Entry Points

Every computer language has what I would call an “entry point”: a set of things which you need to ‘grok’ in order to understand that computer language. They’re fundamental assumptions made about the shape of the universe which is just “off” enough that you’ll forever be confused if you don’t get them. (Or at least they’re things that confused me until I got them.)

Here are a few languages I spent time learning and the ‘pivot points’ around those languages.

LISP
* It’s all about recursion. Learn to live by, and love, recursion.
* Because there is no real natural ‘syntax’ per se, pick a ‘pretty print’ style and stick with it.
* There is no such thing as a single “program”; applications just sort of ‘jell’. This is unlike C or Pascal programs, which definitely have a beginning, middle, and end to development. (This fact made me wonder why, besides Paul Graham, no-one used LISP for web development.)

Pascal and C
* The heap is your friend. Understand it, appreciate it, love it.
* The heap is your enemy; it is a mechanism designed to kill your program at every opportunity if given a chance.

C++
* Objects are your friends. Instead of telling the program the steps to accomplish something, you describe the objects which are doing things. To someone who is used to thinking procedurally, this is a really fantastic brain fuck.
* While a->foo() looks like a pointer to a method, it is really a reference to a vtable which happens to hold a pointer to a method with an invisible argument. If you’re used to thinking about C as a glorified portable assembly language (and can even remember which form of a++ for a pointer a translates into a single assembly instruction on a 680×0 processor), vtables help bridge the gap from “talking to bare metal” to “abstract object oriented programming.”
* Resource Acquisition Is Initialization.

Java
* The package hierarchy is like a parallel “code-space” file system.
* When learning Java, also learn the run-time library. Love it or hate it, but you should first learn the java.lang package, followed by java.util, java.io, and then java.net. All the rest is icing.

Objective C
* Learn to love the Smalltalk-like syntax. For someone who cut their eye-teeth on LISP, C++ and Java, the Smalltalk-like syntax leaves you wondering what to call a method; after all, every language except Smalltalk has just one name for a function and like any good language based on math, the name prefixes the parameters. Not Smalltalk, nor Objective-C.
* If you cut your eye-teeth on the rules for addRef()/release() in Microsoft’s COM environment, the retain/release rules are fucking odd. With Microsoft, the rule was simple: if something hands you a pointer to an object, you own it; you release it. If you pass a pointer to an object, you must increment the reference count on the object because you pass the object means you’re passing ownership.

Not Objective C, which in adding ‘autorelease’ has made the rules a little bit more complicated. Now the rules seem to be:

(1) If you are handed a pointer to an object, you must explicitly retain it if you are holding it.
(2) If you pass an object to another object, it will retain it, so you need to do nothing.
(3) If you create an object out of thin air, you own it–and if you don’t need to hold it, you must autorelease it so it gets released.

Now (3) gets real tricky: basically, there is a naming convention which tells you if you ‘created an object out of thin air.’ Basically, if the name of the method you called starts with ‘alloc’ or ‘new’ or contains the word ‘copy’, you own it, and you have to let it go with autorelease. (Why not ‘release’ instead? Because ‘release’ causes it to go away now, while autorelease causes it to go away “eventually.”)

I long for the simplicity of COM, even though it creates additional verbage in your code. Though I’d much rather have the garbage collection of Java or LISP: just drop the damned thing, and it’ll go away on its own.

While not strictly a language, it does impose its own rules on the universe, and there are a few key things to ‘grok’ to get it:

And that’s it.

Anything else is a bug waiting to be discovered.

* If you need to create a re-entrant data structure that is more complicated than a semaphore-protected object, you really really need to remember to avoid deadlocks by making sure you use a consistent locking order.

* Oh, and it is quite helpful to create a semaphore object or a locking object wrapper, for testing purposes, which times out (and fails noisily) after some set period, such as five minutes. Preferably blowing up by killing all threads waiting on this object with a complete stack trace.

# Cheap Two Factor Authentication

Security authentication relies upon three factors: what you know, what you are, and what you have.

What you know: the canonical example of this is a password. It’s something you know: something you’ve memorized and, when asked, you can repeat it. This is a PIN number on an ATM card, or the answer to things like “your mother’s maiden name”.

What you are: this is some physical attribute about yourself. Your fingerprint, your eye color or the pattern of veins at the back of your eye–or the relative length of the fingers on your hand: these are all attributes which are things that you are.

What you have: this is a physical object that is in your possession. The perfect example of this is the key to your house: it is a physical object that allows you to get into your home.

The idea of two-factor authentication is simple: by having two of the three items above, you can then prove that you’re ‘you’ so you can get access to your account, your money, or your property. A perfect example of two-factor authentication is using your ATM card to withdraw money: you cannot withdraw money unless you can show you have something (the card) and you know something (the PIN number). The strength of two-factor authentication relies upon the relative strength of each factor of authentication: in a sense, the overall strength of two-factor authentication is the strength of the first times the strength of the second.

Which is why ATMs are secure even though passwords (a 4 to 6 digit number) are so bloody weak: even though the password itself is extremely weak, you also need to have something in order to withdraw money. Having something times knowing something is stronger than just knowing something by itself–even if the thing you know can be easily guessed.

This also illustrates the danger of some types of two-factor authentication: they can easily collapse into one-factor authentication (thus making it extremely easy to steal your money) through a simple act. In the case of an ATM card, two-factor authentication becomes one-factor authentication if you write your PIN number on your ATM card. Now anyone who has your ATM card can withdraw money–and they don’t have to know your PIN, they can just read it off your card.

Another example of two-factor which collapses into one-factor authentication would be a pre-printed card with a random number: you can memorize the random number on the card–essentially turning your ‘two-factor’ authentication into a memorized one-factor authentication. Not that this is bad: generally longer passwords are more secure than shorter passwords, and banks are missing out on a bet when they limit ATM passwords to 4 to 8 numbers. Even so, this really is no longer two-factor authentication–which is why there are devices out there (such as key fobs) which randomly generate a number on a synchronized clock: the number constantly changes in a seemingly random way, forcing you to have the device on your possession so you can enter the randomly generated number.

Banks have been required for the past year to come up with two-factor authentication for on-line accounts–and they have failed dismally at this, as illustrated here: Wish-It-Was Two-Factor, where banks essentially require you to pick essentially three passwords rather than one: a real password, a ‘question’ and an ‘answer’. It’s not really two-factor authentication: it’s simply a much longer (and harder to remember) password which frustrates people. And again, while having a longer password is generally more secure, it’s not two-factor authentication.

It struck me one cheap way that banks can create two-factor authentication by something you know and by something you have. It’s easy, really: when you open an account with the bank, they send you a piece of paper with a table of fifty random numbers or words or phrases, all numbered on the paper. So, for example, on that page you’d see:

`1: 148191     2: 381912    3: 108910`

and so forth.