Full Code of shaunlebron/IsometricBlocks for AI

master b448dc11f7f6 cached
9 files
44.1 KB
13.9k tokens
5 symbols
1 requests
Download .txt
Repository: shaunlebron/IsometricBlocks
Branch: master
Commit: b448dc11f7f6
Files: 9
Total size: 44.1 KB

Directory structure:
gitextract_fkjdbnmo/

├── LICENSE
├── README.md
├── index.htm
└── src/
    ├── block.js
    ├── camera.js
    ├── colors.js
    ├── main.js
    ├── painter.js
    └── sortBlocks.js

================================================
FILE CONTENTS
================================================

================================================
FILE: LICENSE
================================================
Copyright 2019 Shaun Lebron

Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.


================================================
FILE: README.md
================================================
Isometric Blocks
================

[A tutorial on how to render isometric blocks in the correct order](http://shaunlebron.github.io/IsometricBlocks)

[![preview](preview-iso.png)](http://shaunlebron.github.io/IsometricBlocks)


================================================
FILE: index.htm
================================================

<!doctype html>
<html>
<head>
	<meta charset="utf8">
	<style>
/*------------------------------------------------------------------------------
 * Open Sans
 *----------------------------------------------------------------------------*/

@font-face {
  font-family: 'Open Sans';
  font-style: normal;
  font-weight: 300;
  src: url('../fonts/opensans/OpenSans-Light.eot');
  src: local('Open Sans Light'), local('OpenSans-Light'),
    url('../fonts/opensans/OpenSans-Light.eot') format('embedded-opentype'),
    url('../fonts/opensans/OpenSans-Light.woff') format('woff');
}

@font-face {
  font-family: 'Open Sans';
  font-style: normal;
  font-weight: 400;
  src: url('../fonts/opensans/OpenSans.eot');
  src: local('Open Sans'), local('OpenSans'),
    url('../fonts/opensans/OpenSans.eot') format('embedded-opentype'),
    url('../fonts/opensans/OpenSans.woff') format('woff');
}

@font-face {
  font-family: 'Open Sans';
  font-style: normal;
  font-weight: bold;
  src: url('../fonts/opensans/OpenSans-Bold.eot');
  src: local('Open Sans Bold'), local('OpenSans-Bold'),
    url('../fonts/opensans/OpenSans-Bold.eot') format('embedded-opentype'),
    url('../fonts/opensans/OpenSans-Bold.woff') format('woff');
}

@font-face {
  font-family: 'Open Sans';
  font-style: italic;
  font-weight: 300;
  src: local('Open Sans Light Italic'), local('OpenSansLight-Italic'),
    url('../fonts/opensans/OpenSansLight-Italic.eot') format('embedded-opentype'),
    url('../fonts/opensans/OpenSansLight-Italic.woff') format('woff');
}

@font-face {
  font-family: 'Open Sans';
  font-style: italic;
  font-weight: 400;
  src: local('Open Sans Italic'), local('OpenSans-Italic'),
    url('../fonts/opensans/OpenSans-Italic.eot') format('embedded-opentype'),
    url('../fonts/opensans/OpenSans-Italic.woff') format('woff');
}

@font-face {
  font-family: 'Open Sans';
  font-style: italic;
  font-weight: bold;
  src: local('Open Sans Bold Italic'), local('OpenSans-BoldItalic'),
    url('../fonts/opensans/OpenSans-BoldItalic.eot') format('embedded-opentype'),
    url('../fonts/opensans/OpenSans-BoldItalic.woff') format('woff');
}


		hr {
			margin-top:3em;
			margin-bottom:3em;
		}
		body {
			width: 800px;
			margin-left:auto;
			margin-right:auto;
      font-family: 'Open Sans';
			font-size: 1.2em;
		}
		canvas {
			background-color: #f5f5f5;
			margin-right: 5px;
			text-align: center;
      border: 1px solid #d7d7d7;
		}
		#abstract {
			font-style: italic;
		}
		figure {
      margin: 2em 2em;
		}
		figcaption {
			font-style: italic;
			color: #555;
		}
		code.block {
			white-space: pre;
			display:block;
			margin-top:3em;
			margin-bottom:3em;
			margin-left: auto;
			margin-right: auto;
			width: 650px;
			padding: 1.5em;
			background: #f5f5f5;
		}
    h1 {
      font-size: 32px;
    }
    h1, h2, h3, h4 {
      margin-top: 3em;
      margin-bottom: -1em;
      color: #333;
      font-weight: 600;
    }
    p {
      margin: 3em 0;
      color: #555;
      line-height: 1.6em;
    }
    figcaption {
      opacity: 0.6;
    }
		p.alert{
			border-radius: 5px;
			box-shadow: 0px 0px 2px #000;
			background-color: #ef2929;
			color: white;
			padding: 1em;
		}

		/* from vim's TOhtml command for syntax highlighting code */
		.lnr { color: #ff0000; }
		.Constant { color: #ef2929; }
		.Statement { color: #3465a4; }
		.Comment { color: #4e9a06; }
		.Identifier { color: #3465a4; }
	</style>

	<script src='src/main.js'></script>
	<script src='src/colors.js'></script>
	<script src='src/block.js'></script>
	<script src='src/vector.js'></script>
	<script src='src/camera.js'></script>
	<script src='src/painter.js'></script>
	<script src='src/sortBlocks.js'></script>
</head>
<body>
<a href="https://github.com/shaunew/IsometricBlocks"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://s3.amazonaws.com/github/ribbons/forkme_right_red_aa0000.png" alt="Fork me on GitHub"></a>


	<h1>Drawing isometric boxes in the correct order</h1>

	<p>
In an <a href="http://en.wikipedia.org/wiki/Isometric_projection">isometric</a>
display, it can be tricky to draw boxes of various sizes in the correct order
to keep them appropriately in front of or behind one another.  The figure below
shows an example.  The blue box should be drawn first, then green, then red.
	</p>

	<figure>
		<canvas id='figure1a' width=350 height=200></canvas>
		<canvas id='figure1b' width=350 height=200></canvas>
		<figcaption>
Figure 1: The boxes on the left are <u>not</u> drawn in the correct order, whereas the
boxes on the right are drawn correctly.
		</figcaption>
		<script>
			var blocks = [
				new IsoBlock.Block({x:1,y:3,z:0},{x:2,y:2,z:2.5}, IsoBlock.colors.green),
				new IsoBlock.Block({x:2,y:2,z:0},{x:1,y:1,z:1.5}, IsoBlock.colors.red),
				new IsoBlock.Block({x:3,y:1,z:0},{x:1,y:4,z:1},   IsoBlock.colors.blue),
			];
			IsoBlock.makeFigure({ canvas:'figure1a', blocks: blocks, sortBlocks: false, });
			IsoBlock.makeFigure({ canvas:'figure1b', blocks: blocks, });
		</script>
	</figure>

	<p>
We will explore a simple solution for determining the correct order to draw a
given set of boxes.  But first, we must define what we mean by <em>boxes</em>.
	</p>

	<h3>What do we mean by <em>boxes</em>?</h3>

	<p>
We define boxes as <em>axis-aligned</em> and <em>non-intersecting</em>
rectangular prisms. Take a look at the above Figure 1 again.  Each box is
parallel to the <em>x</em>, <em>y</em>, and <em>z</em> axis (i.e.
axis-aligned).  Also, note that the boxes are next to each other but do not
intersect.
	</p>

	<h3>Determine if boxes overlap on screen.</h3>

	<p>
First of all, if two boxes do not overlap on the screen, then we do not have to
worry about which one is drawn first.  This is the first test we must perform,
which we explore in this section.
	</p>

	<figure>
		<canvas id='figure2a' width=350 height=200></canvas>
		<canvas id='figure2b' width=350 height=200></canvas>
		<figcaption>
Figure 2: No overlap on the left; overlap on the right.  (Note: we are talking
about overlap on screen, not intersection in space.)
		</figcaption>
		<script>
			var rightBlock =   new IsoBlock.Block({x:4,y:1,z:0},{x:2,y:2,z:2}, IsoBlock.colors.blue);
			var leftBlock =  new IsoBlock.Block({x:2,y:4,z:0},{x:2.25,y:2,z:1}, IsoBlock.colors.red);
			var rightBlockOverlap =   new IsoBlock.Block({x:3,y:2,z:0},{x:2,y:2,z:2}, IsoBlock.colors.blue);
			var leftBlockOverlap =  new IsoBlock.Block({x:2,y:4,z:0},{x:2.25,y:2,z:1}, IsoBlock.colors.green);
			var scale = function(w,h) { return h/9;};
			IsoBlock.makeFigure({ canvas:'figure2a',
				blocks: [ leftBlock, rightBlock ],
				scale: scale,
			});
			IsoBlock.makeFigure({ canvas:'figure2b',
				blocks: [ leftBlockOverlap, rightBlockOverlap ],
				scale: scale,
			});
		</script>
	</figure>

	<p>
The silhouettes of the 3D boxes become 2D hexagons in the isometric view, as seen below.  We use the
outline of these silhouettes to test for overlap.
	</p>

	<figure>
		<canvas id='figure3a' width=350 height=200></canvas>
		<canvas id='figure3b' width=350 height=200></canvas>
		<figcaption>
Figure 3: The box silhouettes in an isometric view are simple hexagons.  Note
that their sides are always parallel to the vertical and two diagonal axes.
		</figcaption>
		<script>
			IsoBlock.makeFigure({ canvas:'figure3a',
				blocks: [ leftBlock, rightBlock ],
				scale: scale,
				silhouette: true,
			});
			IsoBlock.makeFigure({ canvas:'figure3b',
				blocks: [ leftBlockOverlap, rightBlockOverlap ],
				scale: scale,
				silhouette: true,
			});
		</script>
	</figure>

	<p>
We take advantage of the fact that the hexagon sides are always parallel to
some axis.  This allows us to easily determine if the hexagons overlap by
checking for intersection of their regions on each axis.  We add an <em>h</em>
(horizontal) axis to help.
	</p>

	<figure>
		<canvas id='figure4a' width=350 height=200></canvas>
		<canvas id='figure4b' width=350 height=200></canvas>
		<figcaption>
The red and blue boxes do not overlap on the h axis, therefore they do not overlap.
The green and blue boxes do overlap since their region on every axis overlap.
		</figcaption>
		<script>
			IsoBlock.makeFigure({ canvas:'figure4a',
				blocks: [ leftBlock, rightBlock ],
				drawAxis: true,
				silhouette: true,
				scale: scale,
			});
			IsoBlock.makeFigure({ canvas:'figure4b',
				blocks: [ leftBlockOverlap, rightBlockOverlap ],
				drawAxis: true,
				silhouette: true,
				scale: scale,
			});
		</script>
	</figure>

	<p>
Now that we have outlined our concept for <em>determining if two boxes overlap
on the screen</em>, we will fill in the details necessary for implementing it.
	</p>

	<p>
The act of flattening the 3D box into a 2D hexagon involves getting rid of the
Z coordinate.  Notice that increasing a point's Z coordinate by 1 is the same
as incrementing both X and Y coordinates by 1.  Thus, we can add Z to both X
and Y and drop Z completely.  Shown below is the source code for a function
that performs this conversion.
	</p>

<code class='block'><span class="Comment">// Convert a 3D space position to a 2D isometric position.</span>
<span class="Identifier">function</span> spaceToIso(spacePos) <span class="Identifier">{</span>

    <span class="Comment">// New XY position simply adds Z to X and Y.</span>
    <span class="Identifier">var</span> isoX = spacePos.x + spacePos.z;
    <span class="Identifier">var</span> isoY = spacePos.y + spacePos.z;

    <span class="Statement">return</span> <span class="Identifier">{</span>
        x: isoX,
        y: isoY,

        <span class="Comment">// Compute horizontal distance from origin.</span>
        h: (isoX - isoY) * Math.cos(Math.PI/6),

        <span class="Comment">// Compute vertical distance from origin.</span>
        v: (isoX + isoY) / 2;
    <span class="Identifier">}</span>;
<span class="Identifier">}</span></code>

	<p>
And finally, after determining the bounds of each hexagon, we can determine if
they overlap by using the source code below.
	</p>

<code class='block'><span class="Identifier">function</span> doHexagonsOverlap(hex1, hex2) <span class="Identifier">{</span>
    <span class="Comment">// Hexagons overlap if and only if all axis regions overlap.</span>
    <span class="Statement">return</span> (

        <span class="Comment">// test if x regions intersect.</span>
        !(hex1.xmin &gt;= hex2.xmax || hex2.xmin &gt;= hex1.xmax) &amp;&amp;

        <span class="Comment">// test if y regions intersect.</span>
        !(hex1.ymin &gt;= hex2.ymax || hex2.ymin &gt;= hex1.ymax) &amp;&amp;

        <span class="Comment">// test if h regions intersect.</span>
        !(hex1.hmin &gt;= hex2.hmax || hex2.hmin &gt;= hex1.hmax));
<span class="Identifier">}</span></code>

	<p>
Now that we have determined if two boxes overlap on the screen, we can begin exploring how to determine which box is in front of the other.
	</p>

	<h3>Determine which box is in front.</h3>

	<p>
Recall that our boxes do not intersect each other. we can visualize their separation
as a thin plane between them (see Figure 5 below).  After identifying this
plane, we can determine which box is in front by selecting the one on the
correct side of this plane.
	</p>

	<figure>
		<canvas id='figure5a' width=230 height=200></canvas>
		<canvas id='figure5b' width=230 height=200></canvas>
		<canvas id='figure5c' width=230 height=200></canvas>
		<figcaption>
Figure 5: A pair of blocks can be separated in one of three ways shown here.
The dark glass illustrates this separation.
		</figcaption>
		<script>
			var refBlock =   new IsoBlock.Block({x:3,y:2,z:0},{x:2,y:2,z:2}, IsoBlock.colors.blue);
			var leftBlock =  new IsoBlock.Block({x:2,y:4,z:0},{x:2.25,y:2,z:1}, IsoBlock.colors.red);
			var topBlock =   new IsoBlock.Block({x:4,y:2,z:2},{x:1.25,y:2,z:1}, IsoBlock.colors.orange);
			var frontBlock = new IsoBlock.Block({x:1,y:1,z:0},{x:2,y:2,z:1}, IsoBlock.colors.green);
			IsoBlock.makeFigure({ canvas:'figure5a', drawPlane: true,
				blocks: [ refBlock, leftBlock ],
			});
			IsoBlock.makeFigure({ canvas:'figure5b', drawPlane: true,
				blocks: [ refBlock, topBlock ],
			});
			IsoBlock.makeFigure({ canvas:'figure5c', drawPlane: true,
				blocks: [ refBlock, frontBlock ],
			});
		</script>
	</figure>

	<p>
We can find this plane of separation by looking at each axis individually.  In
particular, we look for an axis which has non-intersecting box ranges (see
Figure 6 below).
	</p>

	<figure>
		<canvas id='figure6a' width=350 height=200></canvas>
		<canvas id='figure6b' width=350 height=200></canvas>
		<figcaption>
Figure 6: On the left, the blocks are separated on the y-axis.  On the right,
the blocks are separated on the x-axis. (The z-axis is omitted for simplicity.)
		</figcaption>
		<script>
			IsoBlock.makeFigure({ canvas:'figure6a',
				blocks: [ refBlock, leftBlock ],
				drawAxis: true,
			});
			IsoBlock.makeFigure({ canvas:'figure6b',
				blocks: [ refBlock, frontBlock ],
				drawAxis: true,
			});
		</script>
	</figure>

	<p>
In Figure 6 above, we have chosen a coordinate system which make lesser values
of <em>x</em> and <em>y</em> to be closer to the camera.  Though not shown, the
<em>z</em> axis is positive in the up direction, so a greater value makes it
closer to the camera.
	</p>

	<p>
The following is a javascript function for determining if the first block is in
front of the second:
	</p>

	<code class='block'><span class="Identifier">function</span> isBoxInFront(box1, box2) <span class="Identifier">{</span>

    <span class="Comment">// test for intersection x-axis</span>
    <span class="Comment">// (lower x value is in front)</span>
    <span class="Statement">if</span> (box1.xmin &gt;= box2.xmax) <span class="Identifier">{</span> <span class="Statement">return</span> <span class="Constant">false</span>; <span class="Identifier">}</span>
    <span class="Statement">else</span> <span class="Statement">if</span> (box2.xmin &gt;= box1.xmax) <span class="Identifier">{</span> <span class="Statement">return</span> <span class="Constant">true</span>; <span class="Identifier">}</span>

    <span class="Comment">// test for intersection y-axis</span>
    <span class="Comment">// (lower y value is in front)</span>
    <span class="Statement">if</span> (box1.ymin &gt;= box2.ymax) <span class="Identifier">{</span> <span class="Statement">return</span> <span class="Constant">false</span>; <span class="Identifier">}</span>
    <span class="Statement">else</span> <span class="Statement">if</span> (box2.ymin &gt;= box1.ymax) <span class="Identifier">{</span> <span class="Statement">return</span> <span class="Constant">true</span>; <span class="Identifier">}</span>

    <span class="Comment">// test for intersection z-axis</span>
    <span class="Comment">// (higher z value is in front)</span>
    <span class="Statement">if</span> (box1.zmin &gt;= box2.zmax) <span class="Identifier">{</span> <span class="Statement">return</span> <span class="Constant">true</span>; <span class="Identifier">}</span>
    <span class="Statement">else</span> <span class="Statement">if</span> (box2.zmin &gt;= box1.zmax) <span class="Identifier">{</span> <span class="Statement">return</span> <span class="Constant">false</span>; <span class="Identifier">}</span>

<span class="Identifier">}</span></code>

	<h3>Draw boxes in the correct order.</h3>

	<p>
In general, <u>a box should not be drawn until all the ones behind it are
drawn</u>.  Thus, we begin by drawing the boxes that have nothing behind them.
Then, we can draw the boxes that are only in front of those that are already
drawn. This process continues until all boxes are drawn. (See Figure 4 below
for an example.)
	</p>

	<figure>
		<canvas id='figure7' width=650 height=200></canvas>
		<figcaption>
Figure 4: (1) Nothing is behind blue, so draw it first. (2) Draw green next
since blue was the only one behind it and is already drawn.  (3) Then draw red,
since both blocks that were behind it have been drawn.
		</figcaption>
		<script>
			var blocks = [
				new IsoBlock.Block({x:1,y:3,z:0},{x:2,y:2,z:2.5}, IsoBlock.colors.green),
				new IsoBlock.Block({x:2,y:2,z:0},{x:1,y:1,z:1.5}, IsoBlock.colors.red),
				new IsoBlock.Block({x:3,y:1,z:0},{x:1,y:4,z:1},   IsoBlock.colors.blue),
			];
			IsoBlock.makeFigure({ canvas:'figure7', blocks: blocks, scale: function(w,h) { return h/7; }});
		</script>
	</figure>

	<p>
To implement this algorithm, each box must know exactly which boxes are behind
it.  We have already determined how to do this in the last section.  A search
must be implemented so that each box has a list of boxes behind it.
	</p>

	<p>
You are now armed with everything you need to know to render isometric boxes in
the correct order.
	</p>

	<h3>A conundrum</h3>

	<p>
It is possible to have a situation seen in the figure below.  The aforementioned drawing
methods dictate that we first draw the box with nothing behind it, but this example illustrates
a case where this cannot be done.
	</p>

	<figure>
		<canvas id='figure8' width=650 height=200></canvas>
		<figcaption>
Here are three boxes intertwined in a way such that one is always behind
another.  This prevents us from drawing a first box.
		</figcaption>
		<script>
		var blocks = [
			new IsoBlock.Block({x:1,y:1,z:0},{x:2,y:1,z:1}, IsoBlock.colors.purple),
			new IsoBlock.Block({x:2,y:1,z:1},{x:1,y:2,z:1}, IsoBlock.colors.red),
			new IsoBlock.Block({x:1,y:2,z:0},{x:1,y:1,z:1}, IsoBlock.colors.orange),
			new IsoBlock.Block({x:1,y:2,z:1},{x:1,y:1,z:1}, IsoBlock.colors.orange),
		];
		IsoBlock.makeFigure({ canvas:'figure8', blocks: blocks, scale: function(w,h) { return h/6;} });
		</script>
	</figure>

	<p>
The figure above cheats by segmenting the orange box into two.
This is one method of breaking this type of cycle.
	</p>

	<p>
There are formal methods used for detecting
such cycles mentioned in the appendix.  After detection of a cycle, the blocks in that cycle
could be drawn with special clipping regions to respect front boxes or to segment a block or blocks
that will break the cycle.  These are solutions that I will be exploring and updating this article as
my experiments progress.
	</p>

	<hr>
	<h2>Appendix</h2>

	<h4>A formal description of the solution</h4>

	<p>
This is a special case of the <a href="https://en.wikipedia.org/wiki/Painter%27s_algorithm">Painter's Algorithm</a>,
which handles occlusion by drawing back-to-front.
	</p>

	<p>
For those who are interested, our method for determining if hexagons and boxes
are overlapping is a result of the <a href="http://en.wikipedia.org/wiki/Hyperplane_separation_theorem">hyperplane separation theorem</a>.
	</p>

	<p>
Also, the way in which we determined the drawing order of the boxes is known in graph theory as a <a
href="http://en.wikipedia.org/wiki/Topological_sorting">topological sort</a>,
which is essentially a depth-first search of a directed graph.
	</p>

	<p>
You can build a directed graph of the <em>boxes</em>, with directed edges to
the boxes that are behind it.  Topologically sorting this graph will produce an
ordered list of boxes that can be drawn in that exact order.
	</p>

	<p>
Mathematicians will recognize this directed graph as a <a
href="http://en.wikipedia.org/wiki/Partially_ordered_set">partially ordered
set</a>.
	</p>

	<p>
Finally, to prevent the aforementioned cycle conundrum, we can use <a href="">Tarjan's
strongly connection components</a> algorithm.  After computing these cycles,
one could either split a block to prevent a cycle, or to use a clipping region
to prevent drawing over any blocks that are supposed to be in front of it.
	</p>

	<h4>Alternative Solutions</h4>

	<p>
You may be able to just use <a href="https://en.wikipedia.org/wiki/Z-buffering">Z-buffering</a>,
though drawing order is still important for transparent sprites.  Also, if all
bounding boxes are unit cubes, sorting is much simpler.
	</p>

	<h4>Full example of working code</h4>

	<p>
All the diagrams above were created using a simple isometric box renderer
written in Javascript, which applies all the techniques described in this
article.  You can study the fully annotated source code on <a
href="https://github.com/shaunew/IsometricBlocks">IsometricBlocks project on
GitHub</a>.
	</p>

	<h4>Real game examples</h4>

	<p>
	<ul>
		<li><a href="http://andrewrussell.net/2016/06/how-2-5d-sorting-works-in-river-city-ransom-underground/">How 2.5D Sorting works in River City Ransom: Underground</a> - allowing bounding boxes to intersect by specifying heightmaps within them (<a href="https://news.ycombinator.com/item?id=12313271">summary</a>)</li>
		<li><a href="http://bannalia.blogspot.co.uk/2008/02/filmation-math.html">Filmation engine on the ZX Spectrum</a></li>
	</ul>
	</p>

	<h4>Thanks</h4>

	<p>
Thanks to Ted Suzman at <a href="http://playbuildy.com/">buildy</a> for
introducing this problem and solution to me.  And thanks to adamhayek for <a
href="http://www.reddit.com/r/gamedev/comments/18222r/how_to_determine_the_draw_order_for_an_isometric/c8ayzby">further
insight</a> on a general solution. And thanks to <a href="http://www.reddit.com/r/gamedev/comments/18bg95/tutorial_how_to_render_isometric_blocks_correctly/c8dfx51">Slime0 at reddit</a> for pointing out errors in this article by illustrating the cycle example shown in this article, and for illustrating why we cannot deduce relative drawing order between two non-overlapping boxes.
Thanks to <a href="https://lobste.rs/s/bengjo/drawing_isometric_boxes_correct_order/comments/rzgvnc#c_rzgvnc">Mark Nelson</a> for extra context on painter's algorithm and z-buffering.
	</p>

	<hr>

	<figure>
		<canvas id='figure5' width=700 height=200></canvas>
		<script>
			var blocks = [
				new IsoBlock.Block({x:1,y:3,z:0},{x:2,y:2,z:2.5}, IsoBlock.colors.green),
				new IsoBlock.Block({x:2,y:2,z:0},{x:1,y:1,z:1.5}, IsoBlock.colors.red),
				new IsoBlock.Block({x:3,y:1,z:0},{x:1,y:4,z:1},   IsoBlock.colors.blue),
				new IsoBlock.Block({x:0.5,y:5,z:0},{x:2,y:1.5,z:1},   IsoBlock.colors.orange),
				new IsoBlock.Block({x:3,y:3,z:1},{x:1,y:1,z:2.25},   IsoBlock.colors.black),
				new IsoBlock.Block({x:2,y:7,z:0},{x:1,y:1,z:1},   IsoBlock.colors.white),
				new IsoBlock.Block({x:5,y:1.5,z:0},{x:2,y:2,z:1.5}, IsoBlock.colors.purple),
			];
			IsoBlock.makeFigure({
				canvas:'figure5',
				blocks: blocks,
				drawAxis:true,
				axisLen: 12,
			});
		</script>
	</figure>

</body>
</html>


================================================
FILE: src/block.js
================================================

//
IsoBlock.Block = function(pos,size,color) {

	// position in 3d space (obj with attrs x,y,z)
	this.pos = pos;

	// size of each dimension (obj with attrs x,y,z)
	this.size = size;

	// an array of 3 color shades (light,medium,dark - see colors.js)
	// (used for pseudo lighting)
	this.color = color || IsoBlock.colors.red;
};

IsoBlock.Block.prototype = {
	getBounds: function() {
		var p = this.pos;
		var s = this.size;
		return {
			xmin: p.x,
			xmax: p.x + s.x,
			ymin: p.y,
			ymax: p.y + s.y,
			zmin: p.z,
			zmax: p.z + s.z,
		};
	},
};


================================================
FILE: src/camera.js
================================================

IsoBlock.Camera = function(origin,scale) {

	// the pixel location of the isometric origin.
	this.origin = origin;

	// number of pixels per isometric unit.
	this.scale = scale;

};

/*

We have three separate coordinate systems used for different things:

1. Space (3D)

	We apply the usual 3D coordinates to define the boxes using x,y,z.

2. Isometric (2D)

	When the 3D space is flattened into an isometric view, we use oblique x and y
	axes separated by 120 degrees.

	All this does is treat all 3d coordinates as if they are at z=0.

	For example, if use have a box at (0,0,0) and we raised it to (0,0,1), it would
	look to be in the exact same position as a box at (1,1,0), so the 2d isometric
	coordinates are (1,1).  This is a side effect of the isometric perspective.  So
	the isometric 2D coordinates gets the "apparent" coordinates for all boxes if
	they were at z=0.

	This is accomplished by adding z to x and y.  That is all.

	(Isometric coordinates are useful for determining when boxes overlap on the
	screen.)

3. Screen (2D)

	Before drawing, we convert the isometric coordinates to the usual x,y screen
	coordinates.

	This is done by multiplying each isometric 2D coordinate by its respective
	oblique axis vector and taking the sum.

	We then multiply this position by "scale" value to implement zoom in/out
	features for the camera.

	Then we add to an "origin" to implement panning features for the camera.

*/

IsoBlock.Camera.prototype = {

	// Determine if the given ranges are disjoint (i.e. do not overlap).
	// For determining drawing order, this camera considers two
	// ranges to be disjoint even if they share an endpoint.
	// Thus, we use less-or-equal (<=) instead of strictly less (<).
	areRangesDisjoint: function(amin,amax,bmin,bmax) {
		return (amax <= bmin || bmax <= amin);
	},

	// Convert 3D space coordinates to flattened 2D isometric coordinates.
	// x and y coordinates are oblique axes separated by 120 degrees.
	// h,v are the horizontal and vertical distances from the origin.
	spaceToIso: function(spacePos) {
		var z = (spacePos.z == undefined) ? 0 : spacePos.z;

		var x = spacePos.x + z;
		var y = spacePos.y + z;

		return {
			x: x,
			y: y,
			h: (x-y)*Math.sqrt(3)/2, // Math.cos(Math.PI/6)
			v: (x+y)/2,              // Math.sin(Math.PI/6)
		};
	},

	// Convert the given 2D isometric coordinates to 2D screen coordinates.
	isoToScreen: function(isoPos) {
		return {
			x: isoPos.h * this.scale + this.origin.x,
			y: -isoPos.v * this.scale + this.origin.y,
		};
	},

	// Convert the given 3D space coordinates to 2D screen coordinates.
	spaceToScreen: function(spacePos) {
		return this.isoToScreen(this.spaceToIso(spacePos));
	},
	
	// Get a block's vertices with helpful aliases.
	// Each vertex is named from its apparent position in an isometric view.
	getIsoNamedSpaceVerts: function(block) {
		var p = block.pos;
		var s = block.size;
		
		return {
			rightDown: {x:p.x+s.x, y:p.y,     z:p.z},
			leftDown:  {x:p.x,     y:p.y+s.y, z:p.z},
			backDown:  {x:p.x+s.x, y:p.y+s.y, z:p.z},
			frontDown: {x:p.x,     y:p.y,     z:p.z},
			rightUp:   {x:p.x+s.x, y:p.y,     z:p.z+s.z},
			leftUp:    {x:p.x,     y:p.y+s.y, z:p.z+s.z},
			backUp:    {x:p.x+s.x, y:p.y+s.y, z:p.z+s.z},
			frontUp:   {x:p.x,     y:p.y,     z:p.z+s.z},
		};
	},

	// Get the given block's vertices in flattened 2D isometric coordinates.
	getIsoVerts: function(block) {
		var verts = this.getIsoNamedSpaceVerts(block);
		return {
			leftDown:  this.spaceToIso(verts.leftDown),
			rightDown: this.spaceToIso(verts.rightDown),
			backDown:  this.spaceToIso(verts.backDown),
			frontDown: this.spaceToIso(verts.frontDown),
			leftUp:    this.spaceToIso(verts.leftUp),
			rightUp:   this.spaceToIso(verts.rightUp),
			backUp:    this.spaceToIso(verts.backUp),
			frontUp:   this.spaceToIso(verts.frontUp),
		};
	},

	// For the given block, get the min and max values on each isometric axis.
	getIsoBounds: function(block) {
		var verts = this.getIsoVerts(block);
		return {
			xmin: verts.frontDown.x,
			xmax: verts.backUp.x,
			ymin: verts.frontDown.y,
			ymax: verts.backUp.y,
			hmin: verts.leftDown.h,
			hmax: verts.rightDown.h,
		};
	},

	// Try to find an axis in 2D isometric that separates the two given blocks.
	// This helps identify if the the two blocks are overlap on the screen.
	getIsoSepAxis: function(block_a, block_b) {
		var a = this.getIsoBounds(block_a);
		var b = this.getIsoBounds(block_b);

		var sepAxis = null;
		if (this.areRangesDisjoint(a.xmin,a.xmax,b.xmin,b.xmax)) {
			sepAxis = 'x';
		}
		if (this.areRangesDisjoint(a.ymin,a.ymax,b.ymin,b.ymax)) {
			sepAxis = 'y';
		}
		if (this.areRangesDisjoint(a.hmin,a.hmax,b.hmin,b.hmax)) {
			sepAxis = 'h';
		}
		return sepAxis;
	},

	// Try to find an axis in 3D space that separates the two given blocks.
	// This helps identify which block is in front of the other.
	getSpaceSepAxis: function(block_a, block_b) {

		var sepAxis = null;

		var a = block_a.getBounds();
		var b = block_b.getBounds();

		if (this.areRangesDisjoint(a.xmin,a.xmax,b.xmin,b.xmax)) {
			sepAxis = 'x';
		}
		else if (this.areRangesDisjoint(a.ymin,a.ymax,b.ymin,b.ymax)) {
			sepAxis = 'y';
		}
		else if (this.areRangesDisjoint(a.zmin,a.zmax,b.zmin,b.zmax)) {
			sepAxis = 'z';
		}
		return sepAxis;
	},

	// In an isometric perspective of the two given blocks, determine
	// if they will overlap each other on the screen. If they do, then return
	// the block that will appear in front.
	getFrontBlock: function(block_a, block_b) {

		// If no isometric separation axis is found,
		// then the two blocks do not overlap on the screen.
		// This means there is no "front" block to identify.
		if (this.getIsoSepAxis(block_a, block_b)) {
			return null;
		}

		// Find a 3D separation axis, and use it to determine
		// which block is in front of the other.
		var a = block_a.getBounds();
		var b = block_b.getBounds();
		switch(this.getSpaceSepAxis(block_a, block_b)) {
			case 'x': return (a.xmin < b.xmin) ? block_a : block_b;
			case 'y': return (a.ymin < b.ymin) ? block_a : block_b;
			case 'z': return (a.zmin < b.zmin) ? block_b : block_a;
			default: throw "blocks must be non-intersecting";
		}
	},
};


================================================
FILE: src/colors.js
================================================

// Tango Color Palette
// http://en.wikipedia.org/wiki/Tango_Desktop_Project#Palette
IsoBlock.colors = {
	yellow: {light:"#fce94f", medium:"#edd400", dark:"#c4a000"},
	orange: {light:"#fcaf3e", medium:"#f57900", dark:"#ce5c00"},
	brown:  {light:"#e9b96e", medium:"#c17d11", dark:"#8f5902"},
	green:  {light:"#8ae234", medium:"#73d216", dark:"#4e9a06"},
	blue:   {light:"#729fcf", medium:"#3465a4", dark:"#204a87"},
	purple: {light:"#ad7fa8", medium:"#75507b", dark:"#5c3566"},
	red:    {light:"#ef2929", medium:"#cc0000", dark:"#a40000"},
	white:  {light:"#eeeeec", medium:"#d3d7cf", dark:"#babdb6"},
	black:  {light:"#888a85", medium:"#555753", dark:"#2e3436"},
};

// from David at http://stackoverflow.com/a/11508164/142317
function hexToRgb(hex) {

	// strip out "#" if present.
	if (hex[0] == "#") {
		hex = hex.substring(1);
	}

    var bigint = parseInt(hex, 16);
    var r = (bigint >> 16) & 255;
    var g = (bigint >> 8) & 255;
    var b = bigint & 255;

    return r + "," + g + "," + b;
}


================================================
FILE: src/main.js
================================================

var IsoBlock = IsoBlock || {};

IsoBlock.makeFigure = function(options) {

	// extract options
	var canvasId = options.canvas;
	var blocks = options.blocks;
	var shouldSortBlocks = (options.sortBlocks == undefined) ? true : options.sortBlocks;
	var shouldDrawAxes = options.drawAxis;
	var shouldDrawPlane = options.drawPlane;
	var axisLen = options.axisLen;
	var silhouette = options.silhouette;

	// set canvas and context.
	var canvas = document.getElementById(canvasId);
	var ctx = canvas.getContext('2d');

	// extract scale and origin (camera attributes)
	var scale = (options.scale && options.scale(canvas.width,canvas.height)) || (canvas.height / 8);
	var origin = (options.origin && options.origin(canvas.width,canvas.height)) || {x: canvas.width/2, y: canvas.height };

	// compute appropriate axis length (assuming origin is horizontally centered)
	if (!axisLen) {
		// make sure the axis extends to the edge of the canvas
		axisLen = Math.floor((canvas.width - origin.x) / scale / Math.cos(Math.PI/6)) - 0.5;
	}

	// Get horizontal axis' vertical displacement from origin.
	var hAxisV = origin.y/scale - 1;

	// create camera and painter.
	var camera = new IsoBlock.Camera(origin, scale);
	var painter = new IsoBlock.Painter(camera);

	// draw the xy grid
	function drawGrid() {

		// grid step
		var step = 1;

		// grid range
		var maxx = 15;
		var maxy = 15;

		// plot x lines
		ctx.beginPath();
		for (x=-maxx; x<=maxx; x+=step) {
			painter.moveTo(ctx, {x:x, y:-maxy});
			painter.lineTo(ctx, {x:x, y:maxy});
		}

		// plot y lines
		for (y=-maxy; y<=maxy; y+=step) {
			painter.moveTo(ctx, {x:-maxx, y:y});
			painter.lineTo(ctx, {x:maxx, y:y});
		}

		// draw grid lines
		ctx.strokeStyle = "#d7d7d7";
		ctx.lineWidth = 1;
		ctx.stroke();

	};

	// draw the xy axes and range bars for each block.
	function drawAxes() {

		var axisColor = "#444";
		ctx.lineWidth = 1;
		ctx.strokeStyle = axisColor;
		ctx.fillStyle = axisColor;
		var arrowSize = 0.3;

		// draw x,y axes (and h axis if silhouette)
		var xAxisStart = camera.spaceToIso({x:-axisLen, y:0});
		var xAxisEnd = camera.spaceToIso({x:axisLen, y:0});
		var yAxisStart = camera.spaceToIso({x:0, y:-axisLen});
		var yAxisEnd = camera.spaceToIso({x:0, y:axisLen});
		var hAxisStart = {h:yAxisEnd.h, v:hAxisV};
		var hAxisEnd = {h:xAxisEnd.h, v:hAxisV};
		ctx.beginPath();
		painter.moveTo(ctx, xAxisStart);
		painter.lineTo(ctx, xAxisEnd);
		painter.moveTo(ctx, yAxisStart);
		painter.lineTo(ctx, yAxisEnd);
		if (silhouette) {
			painter.moveTo(ctx, hAxisStart);
			painter.lineTo(ctx, hAxisEnd);
		}
		ctx.stroke();

		// draw x-axis arrow
		ctx.beginPath();
		painter.moveTo(ctx, {x:axisLen, y:0});
		painter.lineTo(ctx, {x:axisLen-arrowSize, y:-arrowSize});
		painter.lineTo(ctx, {x:axisLen-arrowSize, y:arrowSize});
		ctx.closePath();
		ctx.fill();

		// draw y-axis arrow
		ctx.beginPath();
		painter.moveTo(ctx, {y:axisLen, x:0});
		painter.lineTo(ctx, {y:axisLen-arrowSize, x:-arrowSize});
		painter.lineTo(ctx, {y:axisLen-arrowSize, x:arrowSize});
		ctx.closePath();
		ctx.fill();

		// draw h-axis arrow
		if (silhouette) {
			ctx.beginPath();
			painter.moveTo(ctx, hAxisStart);
			painter.lineTo(ctx, {h:hAxisStart.h+arrowSize, v:hAxisV+arrowSize});
			painter.lineTo(ctx, {h:hAxisStart.h+arrowSize, v:hAxisV-arrowSize});
			ctx.closePath();
			ctx.fill();
			ctx.beginPath();
			painter.moveTo(ctx, hAxisEnd);
			painter.lineTo(ctx, {h:hAxisEnd.h-arrowSize, v:hAxisV+arrowSize});
			painter.lineTo(ctx, {h:hAxisEnd.h-arrowSize, v:hAxisV-arrowSize});
			ctx.closePath();
			ctx.fill();
		}

		// draw axis labels
		var p = painter.transform({x:axisLen-1, y:-1});
		ctx.font = "italic 1em serif";
		ctx.textBaseline='middle';
		ctx.textAlign='right';
		ctx.fillText("x",p.x,p.y);
		p = painter.transform({x:-1, y:axisLen-1});
		ctx.textAlign='left';
		ctx.fillText("y",p.x,p.y);
		if (silhouette) {
			p = painter.transform({h:hAxisEnd.h, v:hAxisV-1});
			ctx.textAlign='right';
			ctx.fillText("h",p.x,p.y);
		}
		
		// draw axis ranges for each block
		var i,len,bounds,color,rgb,minp,maxp;
		var s = 0.25;
		for (i=0, len=blocks.length; i<len; i++) {
			bounds = silhouette ? camera.getIsoBounds(blocks[i]) : blocks[i].getBounds();
			color = blocks[i].color.medium;
			rgb = hexToRgb(color);
			tcolor = "rgba("+rgb+",0.7)";

			// alternate which side of the axis the range bar is on.
			s*=-1;

			// draw x axis range
			painter.fillQuad(ctx,
				{x:bounds.xmin, y:0},
				{x:bounds.xmin, y:s},
				{x:bounds.xmax, y:s},
				{x:bounds.xmax, y:0},
				tcolor
			);

			// draw y axis range
			painter.fillQuad(ctx,
				{x:0, y:bounds.ymin},
				{x:s, y:bounds.ymin},
				{x:s, y:bounds.ymax},
				{x:0, y:bounds.ymax},
				tcolor
			);

			if (silhouette) {
				painter.fillQuad(ctx,
					{h:bounds.hmin, v:hAxisV+s},
					{h:bounds.hmax, v:hAxisV+s},
					{h:bounds.hmax, v:hAxisV},
					{h:bounds.hmin, v:hAxisV},
					tcolor
				);
			}
		}
	}

	// draw a pseudo-shaded isometric block.
	function drawBlock(block) {

		var color = block.color;

		// get aliases for each of the block's vertices relative to camera's perspective.
		var b = camera.getIsoNamedSpaceVerts(block);

		if (silhouette) {
			var rgb = hexToRgb(color.medium);
			var tcolor = "rgba("+rgb+",0.7)";
			ctx.beginPath();
			painter.moveTo(ctx, b.frontDown);
			painter.lineTo(ctx, b.leftDown);
			painter.lineTo(ctx, b.leftUp);
			painter.lineTo(ctx, b.backUp);
			painter.lineTo(ctx, b.rightUp);
			painter.lineTo(ctx, b.rightDown);
			ctx.fillStyle = tcolor;
			ctx.fill();
		}
		else {

			// fill in the grout for the inside edges
			var lineWidth = 1;
			var groutColor = color.medium;
			painter.line(ctx, b.leftUp, b.frontUp, groutColor, lineWidth);
			painter.line(ctx, b.rightUp, b.frontUp, groutColor, lineWidth);
			painter.line(ctx, b.frontDown, b.frontUp, groutColor, lineWidth);

			// Do not add line width when filling faces.
			// This prevents a perimeter padding around the hexagon.
			// Nonzero line width could cause the perimeter of another box
			// to bleed over the edge of a box in front of it.
			lineWidth = 0;

			// fill each visible face of the block.

			// left face
			painter.fillQuad(ctx, b.frontDown, b.leftDown, b.leftUp, b.frontUp, !silhouette ? color.dark : color.medium, lineWidth);

			// top face
			painter.fillQuad(ctx, b.frontUp, b.leftUp, b.backUp, b.rightUp, !silhouette ? color.light : color.medium, lineWidth);

			// right face
			painter.fillQuad(ctx, b.frontDown, b.frontUp, b.rightUp, b.rightDown, color.medium, lineWidth);
		}
	};

	// draw a plane to separate two isometric blocks.
	function drawSeparationPlane(frontBlock, backBlock) {

		// exit if back plane is not present
		if (!backBlock) {
			return;
		}

		var bounds = frontBlock.getBounds();

		// get axis of separation
		var aAxis = camera.getSpaceSepAxis(frontBlock, backBlock);
		var bAxis,cAxis;

		// aAxis, bAxis, cAxis are either 'x', 'y', or 'z'
		// a, b, c are the values of its respective axis.

		// determine what our abstract axes correspond to.
		if (aAxis == 'x') {
			a = bounds.xmax;
			bAxis = 'y';
			cAxis = 'z';
		}
		else if (aAxis == 'y') {
			a = bounds.ymax;
			bAxis = 'x';
			cAxis = 'z';
		}
		else if (aAxis == 'z') {
			a = bounds.zmin;
			bAxis = 'x';
			cAxis = 'y';
		}

		// the radius (read margin) of the separation plane).
		var r = 0.7;

		// the points of the separation plane in abstract coords.
		var pts = [
			{ a:a, b: bounds[bAxis+"min"]-r, c: bounds[cAxis+"min"]-r },
			{ a:a, b: bounds[bAxis+"min"]-r, c: bounds[cAxis+"max"]+r },
			{ a:a, b: bounds[bAxis+"max"]+r, c: bounds[cAxis+"max"]+r },
			{ a:a, b: bounds[bAxis+"max"]+r, c: bounds[cAxis+"min"]-r },
		];

		// convert abstract coords to the real coords for this block.
		var i;
		var finalPts = [];
		for (i=0; i<4; i++) {
			var p = {};
			p[aAxis] = pts[i].a;
			p[bAxis] = pts[i].b;
			p[cAxis] = pts[i].c;
			finalPts.push(p);
		}

		// draw separation plane.
		painter.fillQuad(ctx, finalPts[0], finalPts[1], finalPts[2], finalPts[3], "rgba(0,0,0,0.35)");
		painter.strokeQuad(ctx, finalPts[0], finalPts[1], finalPts[2], finalPts[3], "rgba(0,0,0,0.9)", 1);
	};

	// draw grid
	drawGrid();

	// draw axes
	if (shouldDrawAxes) {
		drawAxes();
	}

	// sort blocks in drawing order.
	if (shouldSortBlocks) {
		blocks = IsoBlock.sortBlocks(blocks, camera);
	}

	// draw blocks and a separation plane if applicable.
	var i,len;
	for(i=0,len=blocks.length; i<len; i++) {

		// only draw a separation plane for the last block
		// and only if there is a block behind it.
		if (shouldDrawPlane && i>0 && i==len-1) {
			drawSeparationPlane(blocks[i], blocks[i-1]);
		}

		// draw block
		drawBlock(blocks[i]);
	}

};



================================================
FILE: src/painter.js
================================================

// Allows us to paint shapes using isometric coordinates transformed by a given camera.
// It's basically a wrapper for the canvas context.
IsoBlock.Painter = function(camera) {
	this.camera = camera;
};

IsoBlock.Painter.prototype = {

	// This function allows us to draw using different coordinate systems.
	// It accepts a nondescript position vector and tries to detect
	// what coordinate system it is in by looking at its properties.
	//		(x,y,z)   <- treated as a space coordinate
	//		(x,y)     <- treated as a space coordinate at z=0
	//                   (same as 2D isometric XY)
	//		(h,v)     <- treated as a special 2D isometric coordinate
	//                   (with horizontal and vertical distance from origin)
	transform: function(pos) {
		var x,y,z;
		if (pos.x != undefined && pos.y != undefined) {
			x = pos.x;
			y = pos.y;
			z = (pos.z == undefined) ? 0 : pos.z;
			return this.camera.spaceToScreen({x:x, y:y, z:z});
		}
		else if (pos.h != undefined && pos.v != undefined) {
			return this.camera.isoToScreen(pos);
		}
		else {
			console.log("x",pos.x,"y",pos.y,"z",pos.z,"h",pos.h,"v",pos.v);
			throw "painter.transform: Unable to detect coordinate system of given vector";
		}
	},
	moveTo: function(ctx, pos) {
		var v = this.transform(pos);
		ctx.moveTo(v.x,v.y);
	},
	lineTo: function(ctx, pos) {
		var v = this.transform(pos);
		ctx.lineTo(v.x,v.y);
	},
	quad: function(ctx, p1, p2, p3, p4) {
		this.moveTo(ctx, p1);
		this.lineTo(ctx, p2);
		this.lineTo(ctx, p3);
		this.lineTo(ctx, p4);
	},
	fillQuad: function(ctx, p1, p2, p3, p4, color, lineWidth) {
		ctx.beginPath();
		this.quad(ctx,p1,p2,p3,p4);
		ctx.closePath();
		ctx.fillStyle = color;
		ctx.fill();
		if (lineWidth) {
			ctx.lineWidth = lineWidth;
			ctx.strokeStyle = color;
			ctx.stroke();
		}
	},
	fillQuadGradient: function(ctx, p1, p2, p3, p4, color1, color2) {
		var v1 = this.transform(p1);
		var v4 = this.transform(p4);
		var v2 = this.transform(p2);
		var dx = v4.x-v1.x;
		var dy = v4.y-v1.y;
		var dist = Math.sqrt(dx*dx+dy*dy);
		dx /= dist;
		dy /= dist;
		var dx2 = v2.x-v1.x;
		var dy2 = v2.y-v1.y;
		dist = Math.sqrt(dx2*dx2+dy2*dy2);
		dx *= dist;
		dy *= dist;
		
		
		//var grad = ctx.createLinearGradient(v1.x, v1.y, v2.x, v2.y);
		var grad = ctx.createLinearGradient(v1.x,v1.y, v1.x-dy, v1.y+dx);
		grad.addColorStop(0, color1);
		grad.addColorStop(1, color2);
		this.fillQuad(ctx, p1,p2,p3,p4, grad);
	},
	strokeQuad: function(ctx, p1, p2, p3, p4, color, lineWidth) {
		ctx.beginPath();
		this.quad(ctx,p1,p2,p3,p4);
		ctx.closePath();
		ctx.strokeStyle = color;
		ctx.lineWidth = lineWidth;
		ctx.lineJoin = "round";
		ctx.stroke();
	},
	line: function(ctx, p1, p2, color, lineWidth) {
		ctx.beginPath();
		this.moveTo(ctx, p1);
		this.lineTo(ctx, p2);
		ctx.strokeStyle = color;
		ctx.lineCap = 'butt';
		ctx.lineWidth = lineWidth;
		ctx.stroke();
	},
	fillCircle: function(ctx, p1, radius, color) {
		var v = this.transform(p1);
		ctx.beginPath();
		ctx.arc(v.x,v.y,radius,0,2*Math.PI);
		ctx.fillStyle = color;
		ctx.fill();
	},
	strokeCircle: function(ctx, p1, radius, color) {
		var v = this.transform(p1);
		ctx.beginPath();
		ctx.arc(v.x,v.y,radius,0,2*Math.PI);
		ctx.fillStyle = color;
		ctx.fill();
	},
};


================================================
FILE: src/sortBlocks.js
================================================
// From kennebec at http://stackoverflow.com/a/3955096/142317
// Add a remove value function to the Array class.
Array.prototype.remove = function() {
    var what, a = arguments, L = a.length, ax;
    while (L && this.length) {
        what = a[--L];
        while ((ax = this.indexOf(what)) !== -1) {
            this.splice(ax, 1);
        }
    }
    return this;
};

// Sort blocks in the order that they should be drawn for the given camera.
IsoBlock.sortBlocks = function(blocks, camera) {

	var i, j, numBlocks=blocks.length;

	// Initialize the list of blocks that each block is behind.
	for (i=0; i<numBlocks; i++) {
		blocks[i].blocksBehind = [];
		blocks[i].blocksInFront = [];
	}

	// For each pair of blocks, determine which is in front and behind.
	var a,b,frontBlock;
	for (i=0; i<numBlocks; i++) {
		a = blocks[i];
		for (j=i+1; j<numBlocks; j++) {
			b = blocks[j];
			frontBlock = camera.getFrontBlock(a,b);
			if (frontBlock) {
				if (a == frontBlock) {
					a.blocksBehind.push(b);
					b.blocksInFront.push(a);
				}
				else {
					b.blocksBehind.push(a);
					a.blocksInFront.push(b);
				}
			}
		}
	}

	// Get list of blocks we can safely draw right now.
	// These are the blocks with nothing behind them.
	var blocksToDraw = [];
	for (i=0; i<numBlocks; i++) {
		if (blocks[i].blocksBehind.length == 0) {
			blocksToDraw.push(blocks[i]);
		}
	}

	// While there are still blocks we can draw...
	var blocksDrawn = [];
	while (blocksToDraw.length > 0) {

		// Draw block by removing one from "to draw" and adding
		// it to the end of our "drawn" list.
		var block = blocksToDraw.pop();
		blocksDrawn.push(block);

		// Tell blocks in front of the one we just drew
		// that they can stop waiting on it.
		for (j=0; j<block.blocksInFront.length; j++) {
			var frontBlock = block.blocksInFront[j];

			// Add this front block to our "to draw" list if there's
			// nothing else behind it waiting to be drawn.
			frontBlock.blocksBehind.remove(block);
			if (frontBlock.blocksBehind.length == 0) {
				blocksToDraw.push(frontBlock);
			}
		}
	}

	return blocksDrawn;
};
Download .txt
gitextract_fkjdbnmo/

├── LICENSE
├── README.md
├── index.htm
└── src/
    ├── block.js
    ├── camera.js
    ├── colors.js
    ├── main.js
    ├── painter.js
    └── sortBlocks.js
Download .txt
SYMBOL INDEX (5 symbols across 2 files)

FILE: src/colors.js
  function hexToRgb (line 17) | function hexToRgb(hex) {

FILE: src/main.js
  function drawGrid (line 37) | function drawGrid() {
  function drawAxes (line 67) | function drawAxes() {
  function drawBlock (line 183) | function drawBlock(block) {
  function drawSeparationPlane (line 232) | function drawSeparationPlane(frontBlock, backBlock) {
Condensed preview — 9 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (49K chars).
[
  {
    "path": "LICENSE",
    "chars": 726,
    "preview": "Copyright 2019 Shaun Lebron\n\nPermission to use, copy, modify, and/or distribute this software for any purpose with or wi"
  },
  {
    "path": "README.md",
    "chars": 226,
    "preview": "Isometric Blocks\n================\n\n[A tutorial on how to render isometric blocks in the correct order](http://shaunlebro"
  },
  {
    "path": "index.htm",
    "chars": 22414,
    "preview": "\n<!doctype html>\n<html>\n<head>\n\t<meta charset=\"utf8\">\n\t<style>\n/*-------------------------------------------------------"
  },
  {
    "path": "src/block.js",
    "chars": 551,
    "preview": "\n//\nIsoBlock.Block = function(pos,size,color) {\n\n\t// position in 3d space (obj with attrs x,y,z)\n\tthis.pos = pos;\n\n\t// s"
  },
  {
    "path": "src/camera.js",
    "chars": 6203,
    "preview": "\nIsoBlock.Camera = function(origin,scale) {\n\n\t// the pixel location of the isometric origin.\n\tthis.origin = origin;\n\n\t//"
  },
  {
    "path": "src/colors.js",
    "chars": 1002,
    "preview": "\n// Tango Color Palette\n// http://en.wikipedia.org/wiki/Tango_Desktop_Project#Palette\nIsoBlock.colors = {\n\tyellow: {ligh"
  },
  {
    "path": "src/main.js",
    "chars": 8704,
    "preview": "\nvar IsoBlock = IsoBlock || {};\n\nIsoBlock.makeFigure = function(options) {\n\n\t// extract options\n\tvar canvasId = options."
  },
  {
    "path": "src/painter.js",
    "chars": 3237,
    "preview": "\n// Allows us to paint shapes using isometric coordinates transformed by a given camera.\n// It's basically a wrapper for"
  },
  {
    "path": "src/sortBlocks.js",
    "chars": 2093,
    "preview": "// From kennebec at http://stackoverflow.com/a/3955096/142317\n// Add a remove value function to the Array class.\nArray.p"
  }
]

About this extraction

This page contains the full source code of the shaunlebron/IsometricBlocks GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 9 files (44.1 KB), approximately 13.9k tokens, and a symbol index with 5 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!