1. Code
  2. Coding Fundamentals
  3. Game Development

Building a Dynamic Shadow Casting Engine in AS3

Scroll to top

Dynamic shadows give game developers a way to recreate real life experience with lights and shadows. Every time we move, we cast shadows according to the position of the light sources around us. Dynamic shadows are no different than that. Our goal is to transfer this experience to the virtual world by creating an engine that will be able to cast these shadows.

These are common in 3D games. You have probably played a 3D game or watched a gameplay video and noticed that the shadows in most of them are dynamic. However, due to the complexity of the code, 2D games lack a good implementation of shadows, and often end up using a static alternative. The objective of this tutorial is to implement dynamic shadows in a 2D environment.


What Will You Need?

These two .swc files are used in this tutorial, so it's better to grab them now!

Light ball

Texture


Step 1: Defining Terms

During this tutorial we will use some terms that might not be common in your vocabulary, so here's a quick explanation of all of them:

  • Light source: any object that will create light. It will be represented by a single point and will have the following properties: range (radius of the circle created by the light), color (of the light), intensity (amount of light in the middle of the circle) and fall off (the amount of light that will still be present at the edges of the circle).
  • Light ball: if stated in the engine that they must be shown, the light ball will be in the center of a light source's circle and will represent the light source.
  • Solid object: any object that will cast shadows when illuminated by a light source. Will be defined by its vertices (defined in the counter-clockwise direction) and can have any shape you want, as long as it's a convex shape.
  • Display area: the area in which all the lights and objects are contained.
  • Light map: the sprite in which we will draw all the lights and shadows of the display area.
  • Objects map: the sprite in which we will draw all the objects of the display area.
  • Ambient light: it acts like sunlight, except that it can have any color you want. It will be applied to the entire light map, independant of the presence of lights and/or objects.

Important: Please note that the solid objects must be convex shapes and their vertices are defined in the counter-clockwise direction. This is very important and you may get different results if you don't do it (the reason for that will be explained later in the tutorial).


Step 2: An Example of Static Shadow

Static shadows are not what we want, but they are shown here to explain how they are done and in which cases having them isn't a problem.


Description: the circles below the characters are static shadows that only give the impression of a light source from the sky, like the sun.

Static shadows are simple circles with a radial alpha gradient (the most advanced ones have the shape of the object, for example) that lie below a character or an object. Sometimes their radii change if a character jumps or an object gets more distant from the gound, but they will always have a defined shape. Shadows like that are used when the light source is very distant from the objects, giving the impression that the shadows don't change. This is common in platform games or flying games, but not what we want to achieve here.


Step 3: Creating the Classes

Let's begin the code! First of all, we must set up all the classes that we will work with. For this tutorial, we will need three initial classes: ShadowEngine, Light and SolidObject. They must be created this way:


The classes don't need to extend any other class.


Step 4: Defining the Light

We will now start adding code to the classes. The first one will be the light. Here's the basic code:

1
 
2
package lightning 
3
{ 
4
	import flash.display.Sprite; 
5
	import flash.geom.Point; 
6
	 
7
	public class Light 
8
	{ 
9
		protected var _color:uint; 
10
		protected var _intensity:Number; 
11
		protected var _range:Number; 
12
		protected var _fallOff:Number; 
13
		 
14
		protected var _x:Number; 
15
		protected var _y:Number; 
16
		 
17
		protected var _drawingArea:Sprite; 
18
		 
19
		protected var _shadowArea:Sprite; 
20
		 
21
		public function Light(initialPosition:Point, color:uint, range:Number, intensity:Number = 1, fallOff:Number = 0) 
22
		{ 
23
			_x = initialPosition.x; 
24
			_y = initialPosition.y; 
25
			 
26
			_color = color; 
27
			_range = range; 
28
			_intensity = intensity; 
29
			_fallOff = fallOff; 
30
			 
31
			initializeDrawingArea(); 
32
		} 
33
		 
34
		private function initializeDrawingArea():void 
35
		{ 
36
			_drawingArea = new Sprite(); 
37
			 
38
			_shadowArea = new Sprite(); 
39
		} 
40
		 
41
		public function get x():Number 
42
		{ 
43
			return _x; 
44
		} 
45
		 
46
		public function set x(value:Number):void 
47
		{ 
48
			_x = value; 
49
		} 
50
		 
51
		public function get y():Number 
52
		{ 
53
			return _y; 
54
		} 
55
		 
56
		public function set y(value:Number):void 
57
		{ 
58
			_y = value; 
59
		} 
60
		 
61
		public function get drawingArea():Sprite 
62
		{ 
63
			return _drawingArea; 
64
		} 
65
		 
66
		public function get shadowArea():Sprite 
67
		{ 
68
			return _shadowArea; 
69
		} 
70
	} 
71
}

We defined the _x and _y properties of the light, the _color, _range, _intensity and _fallOff. Since we will need to access the x and y properties, we created getter and setter functions for them. They might look useless, but we will add more content in the functions as we start giving more "life" to our engine. The drawing area is a Sprite in which the light will be drawn, and the shadow area is the sprite in which all the shadows related to that light will be drawn. The drawing area and shadow area will blend together later. The initializeDrawingArea() function sets the drawing area and shadow area up for drawing. More will be added into that function later.


Step 5: Defining the Solid Object

Now we must define the SolidObject class. This contains a Vector of all the vertices (corners) that make up a solid object:

1
 
2
package objects 
3
{ 
4
	import flash.display.Sprite; 
5
	import flash.geom.Point; 
6
	 
7
	public class SolidObject 
8
	{ 
9
		protected var _vertices:Vector.<Point>; 
10
		protected var _numberOfVertices:int; 
11
		 
12
		protected var _x:Number; 
13
		protected var _y:Number; 
14
		 
15
		protected var _drawingArea:Sprite; 
16
		 
17
		public function SolidObject(initialPosition:Point, vertices:Vector.<Point>)  
18
		{ 
19
			// Getting a clean "version" of the vertices vector 
20
			_vertices = vertices.concat(); 
21
			 
22
			_numberOfVertices = _vertices.length; 
23
			 
24
			_x = initialPosition.x; 
25
			_y = initialPosition.y; 
26
			 
27
			initializeDrawingArea(); 
28
		} 
29
		 
30
		private function initializeDrawingArea():void 
31
		{ 
32
			_drawingArea = new Sprite(); 
33
		} 
34
		 
35
		public function get x():Number 
36
		{ 
37
			return _x; 
38
		} 
39
		 
40
		public function set x(value:Number):void 
41
		{ 
42
			_x = value; 
43
		} 
44
		 
45
		public function get y():Number 
46
		{ 
47
			return _y; 
48
		} 
49
		 
50
		public function set y(value:Number):void 
51
		{ 
52
			_y = value; 
53
		} 
54
		 
55
		public function get drawingArea():Sprite 
56
		{ 
57
			return _drawingArea; 
58
		} 
59
	} 
60
}

As we did with the light, the getter and setter functions for the _x and _y properties will have more content as we keep adding more things in the tutorial. You must notice line 19, which is highlighted; in this line we call the concat() function of the vertices argument passed to the constructor in order to provide a new Vector of points to our class. This way, our class can make changes to this Vector without changing the original one, which is the Vector passed as an argument. The drawing area of our solid object will be the Sprite in which we draw its image.


Step 6: Starting the Shadow Engine

We must now start coding the mechanics behind displaying the objects and lights! Here is the code for it:

1
 
2
package 
3
{ 
4
	import flash.display.Sprite; 
5
	 
6
	public class ShadowEngine 
7
	{ 
8
		public static var WIDTH:int; 
9
		public static var HEIGHT:int; 
10
		 
11
		private var _ambientLight:uint; 
12
		private var _ambientLightAlpha:Number; 
13
		 
14
		private var _drawBalls:Boolean; 
15
		 
16
		private var _drawingArea:Sprite; 
17
		 
18
		public function ShadowEngine(width:int, height:int, ambientLight:uint, ambientLightAlpha:Number, drawBalls:Boolean = true)  
19
		{ 
20
			// These will be accessed later by many parts of the code 
21
			ShadowEngine.WIDTH = width; 
22
			ShadowEngine.HEIGHT = height; 
23
			 
24
			_ambientLight = ambientLight; 
25
			_ambientLightAlpha = ambientLightAlpha; 
26
			 
27
			_drawBalls = drawBalls; 
28
			 
29
			_drawingArea = new Sprite(); 
30
			 
31
			trace("Shadow engine instantiated with success!"); 
32
			trace("Working on a rectangle " + ShadowEngine.WIDTH + " pixels wide and " + ShadowEngine.HEIGHT + " pixels high."); 
33
		} 
34
		 
35
		public function get drawingArea():Sprite 
36
		{ 
37
			return _drawingArea; 
38
		} 
39
	} 
40
}

The _ambientLight and _ambientLightAlpha properties will be used for applying the ambient light in the light map. The _drawBalls property indicates to the engine whether or not to draw the light sources' balls (that is, whether to render instances of the LightBall class, contained in the SWC you downloaded earlier). The WIDTH and HEIGHT properties are the width and height of the display area of the engine. They are created as "public static" properties because they will be later accessed in our other classes. The drawing area is what all the maps will be added to.

If we head to the Main class and create a new instance of the shadow engine, we will see the nice message in the output window!

1
 
2
private var _shadowEngine:ShadowEngine; 
3
 
4
private function init(e:Event):void  
5
{ 
6
	_shadowEngine = new ShadowEngine(640, 480, 0x000000, 0.6, true); 
7
	 
8
	addChild(_shadowEngine.drawingArea); 
9
}

Note that we already added the engine's drawing area to Main's child list. This is the part of the code responsible for displaying everything in the screen.



Step 7: Adding and Removing Objects and Lights

Now we need to make our engine recognize objects and lights. This code will go into the ShadowEngine class:

1
 
2
private var _objects:Vector.<SolidObject>; 
3
private var _lights:Vector.<Light>; 
4
 
5
private var _objectMap:Sprite; 
6
private var _lightMap:Sprite; 
7
private var _ballsMap:Sprite; 
8
 
9
private var _numberOfObjects:int; 
10
private var _numberOfLights:int; 
11
 
12
private function createObjectMap():void 
13
{ 
14
	_objects = new Vector.<SolidObject>(); 
15
	 
16
	_objectMap = new Sprite(); 
17
	 
18
	// Creates a scroll rect to render only what is on the screen 
19
	_objectMap.scrollRect = new Rectangle(0, 0, ShadowEngine.WIDTH, ShadowEngine.HEIGHT); 
20
	 
21
	_drawingArea.addChild(_objectMap); 
22
	 
23
	trace("Object map created with success!"); 
24
} 
25
 
26
private function createLightMap():void 
27
{ 
28
	_lights = new Vector.<Light>(); 
29
	 
30
	_lightMap = new Sprite(); 
31
	 
32
	// Creates a scroll rect to render only what is on the screen 
33
	_lightMap.scrollRect = new Rectangle(0, 0, ShadowEngine.WIDTH, ShadowEngine.HEIGHT); 
34
	 
35
	_drawingArea.addChild(_lightMap); 
36
	 
37
	trace("Light map created with success!"); 
38
	 
39
	if (_drawBalls) 
40
	{ 
41
		_ballsMap = new Sprite(); 
42
		 
43
		// Creates a scroll rect to render only what is on the screen 
44
		_ballsMap.scrollRect = new Rectangle(0, 0, ShadowEngine.WIDTH, ShadowEngine.HEIGHT); 
45
		 
46
		_drawingArea.addChild(_ballsMap); 
47
		 
48
		trace("Balls map created with success!"); 
49
	} 
50
} 
51
 
52
public function addObject(object:SolidObject):void 
53
{ 
54
	if (_objects.indexOf(object) < 0) 
55
	{ 
56
		_objects.push(object); 
57
		 
58
		_objectMap.addChild(object.drawingArea); 
59
		 
60
		_numberOfObjects = _objects.length; 
61
		 
62
		trace("Object added with success!"); 
63
	} 
64
} 
65
 
66
public function removeObject(object:SolidObject):void 
67
{ 
68
	if (_objects.indexOf(object) >= 0) 
69
	{ 
70
		_objects.splice(_objects.indexOf(object), 1); 
71
		 
72
		_objectMap.removeChild(object.drawingArea); 
73
		 
74
		_numberOfObjects = _objects.length; 
75
		 
76
		trace("Object removed with success!"); 
77
	} 
78
} 
79
 
80
public function addLight(lightObject:Light):void 
81
{ 
82
	if (_lights.indexOf(lightObject) < 0) 
83
	{ 
84
		_lights.push(lightObject); 
85
		 
86
		_lightMap.addChild(lightObject.drawingArea); 
87
		 
88
		_numberOfLights = _lights.length; 
89
		 
90
		trace("Light added with success!"); 
91
	} 
92
} 
93
 
94
public function removeLight(lightObject:Light):void 
95
{ 
96
	if (_lights.indexOf(lightObject) >= 0) 
97
	{ 
98
		_lights.splice(_lights.indexOf(lightObject), 1); 
99
		 
100
		_lightMap.removeChild(lightObject.drawingArea); 
101
		 
102
		_numberOfLights = _lights.length; 
103
		 
104
		trace("Light removed with success!"); 
105
	} 
106
}

And don't forget to add the following import statements:

1
 
2
import flash.geom.Rectangle; 
3
import lightning.Light; 
4
import objects.SolidObject;

In the code above, createObjectMap() and createLightMap() must be called when the ShadowEngine class is instantiated, because they are responsible for setting up all the maps used in the engine. The addObject(), removeObject(), addLight() and removeLight() functions do what their names suggest. Note that when we add or remove a light, we don't add their balls to the ball map yet, because they haven't been created in the Light class. This will be done on the later steps.

As said, in order to set up the light map and the object map, we must run createObjectMap() and createLightMap(). Let's add this code to the ShadowEngine constructor:

1
 
2
public function ShadowEngine(width:int, height:int, ambientLight:uint, ambientLightAlpha:Number, drawBalls:Boolean = true)  
3
{ 
4
	ShadowEngine.WIDTH = width; 
5
	ShadowEngine.HEIGHT = height; 
6
	 
7
	_ambientLight = ambientLight; 
8
	_ambientLightAlpha = ambientLightAlpha; 
9
	 
10
	_drawBalls = drawBalls; 
11
	 
12
	_drawingArea = new Sprite(); 
13
	 
14
	createObjectMap(); 
15
	createLightMap(); 
16
	 
17
	trace("Shadow engine instantiated with success!"); 
18
	trace("Working on a rectangle " + ShadowEngine.WIDTH + " pixels wide and " + ShadowEngine.HEIGHT + " pixels high."); 
19
}

With this code you can already add objects and lights inside the engine! Let's give it a try. In the Main class we will add two lights and one solid object with the following code:

1
 
2
private function init(e:Event):void  
3
{ 
4
	_shadowEngine = new ShadowEngine(640, 480, 0x000000, 0.6, true); 
5
	 
6
	addChild(_shadowEngine.drawingArea); 
7
	 
8
	_shadowEngine.addLight(new Light(new Point(0, 0), 0xFF0000, 200, 1, 0)); 
9
	_shadowEngine.addLight(new Light(new Point(300, 200), 0x00FFFF, 500, 1, 0.15)); 
10
	 
11
	var temporaryVertices:Vector.<Point> = new Vector.<Point>(5); 
12
	temporaryVertices[0] = new Point(0, 0); 
13
	temporaryVertices[1] = new Point(0, 40); 
14
	temporaryVertices[2] = new Point(30, 50); 
15
	temporaryVertices[3] = new Point(60, 25); 
16
	temporaryVertices[4] = new Point(15, 0); 
17
	 
18
	_shadowEngine.addObject(new SolidObject(new Point(250, 250), temporaryVertices)); 
19
}

Use these import statements:

1
 
2
import flash.geom.Point; 
3
import lightning.Light; 
4
import objects.SolidObject;

And this is what we get in the output window (don't worry, in the next steps we will actually draw the objects and lights)!



Step 8: Drawing the Object

It's time for some action: what do you think of drawing all the objects to the screen? In order to do that, we need to add draw() functions inside the SolidObject class.

The object will be drawn using Flash Player's drawing capabilities: we will begin filling the shape with a half-transparent red color, then run through each of the vertices creating lines, and then end the fill. Let's add this code to the SolidObject class:

1
 
2
private var _iterator:int; 
3
 
4
public function draw():void 
5
{ 
6
	_drawingArea.graphics.clear(); 
7
	_drawingArea.graphics.beginFill(0xFF0000, 0.5); 
8
	 
9
	_drawingArea.graphics.moveTo(_vertices[0].x + _x, _vertices[0].y + _y); 
10
	 
11
	_iterator = 1; 
12
	 
13
	// Looping through each vertex 
14
	while (_iterator < _numberOfVertices) 
15
	{ 
16
		_drawingArea.graphics.lineTo(_vertices[_iterator].x + _x, _vertices[_iterator].y + _y); 
17
		 
18
		_iterator++; 
19
	} 
20
	 
21
	_drawingArea.graphics.lineTo(_vertices[0].x + _x, _vertices[0].y + _y); 
22
	 
23
	_drawingArea.graphics.endFill(); 
24
}

The _iterator variable will be used throughout the class. It was created in order to help our engine's performance. Note that we add the object's current x and y positions to the vertices' positions before moving or drawing lines to them. That way we are able to draw in the exact position of our objects.


Step 9: Drawing the Light

In order to draw our light, we will need to create a gradient fill and draw a circle starting in our light's position. If you want to learn more about gradient fills, you can check this tutorial: How to Create Gradients with ActionScript.

Now, let's create some functions inside our Light class:

1
 
2
protected var _lightGradientMatrix:Matrix; 
3
 
4
private function initializeDrawingArea():void  
5
{ 
6
	_drawingArea = new Sprite(); 
7
	 
8
	_shadowArea = new Sprite(); 
9
	 
10
	_lightGradientMatrix = new Matrix(); 
11
	_lightGradientMatrix.createGradientBox(_range * 2, _range * 2, 0, _x - _range, _y - _range); 
12
} 
13
 
14
public function draw():void 
15
{ 
16
	_drawingArea.graphics.clear(); 
17
	_drawingArea.graphics.beginGradientFill(GradientType.RADIAL, [_color, _color], [_intensity, _fallOff], [0, 255], _lightGradientMatrix, SpreadMethod.PAD, InterpolationMethod.LINEAR_RGB); 
18
	_drawingArea.graphics.drawCircle(_x, _y, _range); 
19
	_drawingArea.graphics.endFill(); 
20
}

We created a gradient circle centered in the light's x and y positions in this code. The _lightGradientMatrix property needs to be inside a variable because we will later have to update it. We will also need to create the light's "ball" -- a graphic to represent the light source. Let's use the LightBall image provided in DynamicShadows.swc as the light ball. Inside the Light class, let's add a createBall() function and call it in the constructor:

1
 
2
protected var _ball:Sprite; 
3
protected var _ballColorTransform:ColorTransform; 
4
 
5
public function Light(initialPosition:Point, color:uint, range:Number, intensity:Number = 1, fallOff:Number = 0)  
6
{ 
7
	_x = initialPosition.x; 
8
	_y = initialPosition.y; 
9
	 
10
	_color = color; 
11
	_range = range; 
12
	_intensity = intensity; 
13
	_fallOff = fallOff; 
14
	 
15
	initializeDrawingArea(); 
16
	createBall(); 
17
} 
18
 
19
private function createBall():void 
20
{ 
21
	_ball = new LightBall(); 
22
	 
23
	_ball.x = _x; 
24
	_ball.y = _y; 
25
	 
26
	// Giving the color of our light to the ball 
27
	_ballColorTransform = new ColorTransform(); 
28
	_ballColorTransform.color = _color; 
29
	 
30
	_ball.transform.colorTransform = _ballColorTransform; 
31
} 
32
 
33
public function get ball():Sprite 
34
{ 
35
	return _ball; 
36
}

Don't forget that we need to add some import statements in our Light class!

1
 
2
import flash.display.GradientType; 
3
import flash.display.InterpolationMethod; 
4
import flash.display.SpreadMethod; 
5
import flash.geom.ColorTransform; 
6
import flash.geom.Matrix; 
7
import SWCAssets.LightBall;

The ColorTransform was used here in order to give the same color of our light source to the ball. The getter function for the ball property was created in order to add the light's ball in the ball map, and later in the ShadowEngine class. Now, everything should be right for adding these objects in the screen.


Step 10: Adding the Objects to the Screen

Back in our ShadowEngine class, we need now to draw our objects in the screen. In order to do that, we need to update our engine every frame and then ask every object to draw itself. Since the objects are added to the object map, they will be automatically displayed on the screen.

Our engine will be updated through the updateEngine() function. It should be called every frame. Let's add that in the ShadowEngine class:

1
 
2
public function updateEngine():void 
3
{ 
4
	drawObjects(); 
5
} 
6
 
7
private function drawObjects():void 
8
{ 
9
	var iterator:int = 0; 
10
	 
11
	// Looping through each object 
12
	while (iterator < _numberOfObjects) 
13
	{ 
14
		_objects[iterator].draw(); 
15
		 
16
		iterator++; 
17
	} 
18
}

We can now go to the Main class and create an Event.ENTER_FRAME event listener, then update the engine. Add the following code in the Main class:

1
 
2
private function init(e:Event):void  
3
{ 
4
	_shadowEngine = new ShadowEngine(640, 480, 0x000000, 0.6, true); 
5
	 
6
	addChild(_shadowEngine.drawingArea); 
7
	 
8
	_shadowEngine.addLight(new Light(new Point(0, 0), 0xFF0000, 200, 1, 0)); 
9
	_shadowEngine.addLight(new Light(new Point(300, 200), 0x00FFFF, 500, 1, 0.15)); 
10
	 
11
	var temporaryVertices:Vector.<Point> = new Vector.<Point>(5); 
12
	temporaryVertices[0] = new Point(0, 0); 
13
	temporaryVertices[1] = new Point(0, 40); 
14
	temporaryVertices[2] = new Point(30, 50); 
15
	temporaryVertices[3] = new Point(60, 25); 
16
	temporaryVertices[4] = new Point(15, 0); 
17
	 
18
	_shadowEngine.addObject(new SolidObject(new Point(250, 250), temporaryVertices)); 
19
	 
20
	addEventListener(Event.ENTER_FRAME, engineLoop); 
21
} 
22
 
23
private function engineLoop(e:Event):void 
24
{ 
25
	_shadowEngine.updateEngine(); 
26
}

When compiling the project, we can see the result: our object (drawn in red):



Step 11: Drawing the Lights

Drawing our lights on the screen will be a bit more complicated. In the ShadowEngine class, let's create a drawLights() function and add the call to this function in the updateEngine() function. Let's also not forget to update the addLight() and removeLight() functions to make them add the Light's ball in the ball map:

1
 
2
private var _currentLight:Light; 
3
private var _lightIterator:int; 
4
 
5
public function updateEngine():void 
6
{ 
7
	drawObjects(); 
8
	drawLights(); 
9
} 
10
 
11
private function drawLights():void 
12
{ 
13
	// Applying the ambient light 
14
	_lightMap.graphics.clear(); 
15
	_lightMap.graphics.beginFill(_ambientLight, _ambientLightAlpha); 
16
	_lightMap.graphics.drawRect(0, 0, ShadowEngine.WIDTH, ShadowEngine.HEIGHT); 
17
	_lightMap.graphics.endFill(); 
18
	 
19
	_lightIterator = 0; 
20
	 
21
	// Looping through each light and making it draw 
22
	while (_lightIterator < _numberOfLights) 
23
	{ 
24
		_currentLight = _lights[_lightIterator]; 
25
		 
26
		_currentLight.draw(); 
27
		 
28
		_lightIterator++; 
29
	} 
30
} 
31
 
32
public function addLight(lightObject:Light):void 
33
{ 
34
	if (_lights.indexOf(lightObject) < 0) 
35
	{ 
36
		_lights.push(lightObject); 
37
		 
38
		_lightMap.addChild(lightObject.drawingArea); 
39
		 
40
		_numberOfLights = _lights.length; 
41
		 
42
		trace("Light added with success!"); 
43
		 
44
		if (_drawBalls) 
45
		{ 
46
			_ballsMap.addChild(lightObject.ball); 
47
			 
48
			trace("Draw Balls is true. Light's ball added with success!"); 
49
		} 
50
	} 
51
} 
52
 
53
public function removeLight(lightObject:Light):void 
54
{ 
55
	if (_lights.indexOf(lightObject) >= 0) 
56
	{ 
57
		_lights.splice(_lights.indexOf(lightObject), 1); 
58
		 
59
		_lightMap.removeChild(lightObject.drawingArea); 
60
		 
61
		_numberOfLights = _lights.length; 
62
		 
63
		trace("Light removed with success!"); 
64
		 
65
		if (_drawBalls) 
66
		{ 
67
			_ballsMap.removeChild(lightObject.ball); 
68
			 
69
			trace("Draw Balls is true. Light's ball removed with success!"); 
70
		} 
71
	} 
72
}

This code clears the light map in order to apply the ambient light, and also loops through each light and makes the light draw itself in its drawing area. Since each light's drawing area is added to the light map, they will be automatically shown.

We can now add lights into the engine! Take a look at our result:


You can see the two light sources that we added back in Step 7: one cyan and one red. You can also just about see the solid object, but it's drowned out by the cyan light!


Step 12: Improving the Lights

In our last build, the lights are too much bright, and this makes it hard to see other objects. This happens because we are only drawing the lights in the screen, so the raw color data is being used. What if we wanted to have more than a light (like in our example)? Their colors would need to mix up a bit in their intersection. In our example, the red light can barely be seen. And we can't forget the ambient light, which is present at all the time, but is covered by the lights now. This can be easily changed by using Blend Modes.

The Blend Mode we will use in our engine at this time is the Multiply mode. The Multiply mode must be added in our light map, so that it affects every light added to it. Let's add it in the ShadowEngine class:

1
 
2
private function createLightMap():void 
3
{ 
4
	_lights = new Vector.<Light>(); 
5
	 
6
	_lightMap = new Sprite(); 
7
	 
8
	_lightMap.scrollRect = new Rectangle(0, 0, ShadowEngine.WIDTH, ShadowEngine.HEIGHT); 
9
	 
10
	_lightMap.blendMode = BlendMode.MULTIPLY; 
11
	 
12
	_drawingArea.addChild(_lightMap); 
13
	 
14
	trace("Light map created with success!"); 
15
	 
16
	if (_drawBalls) 
17
	{ 
18
		_ballsMap = new Sprite(); 
19
		 
20
		_ballsMap.scrollRect = new Rectangle(0, 0, ShadowEngine.WIDTH, ShadowEngine.HEIGHT); 
21
		 
22
		_drawingArea.addChild(_ballsMap); 
23
		 
24
		trace("Balls map created with success!"); 
25
	} 
26
}

And let's not forget the import statement:

1
 
2
import flash.display.BlendMode;

Hit the compile button and this is the screen we get:


It looks much better now! We can see that in the non-red corners the ambient light starts to kick in! However, the cyan light still looks too bright. What about reducing its range to 300 pixels and fall off to 0 in the Main class? Let's also increase the ambient light's alpha to 1. That way we can create a totally dark environment with only the two lights illuminating it.

1
 
2
private function init(e:Event):void  
3
{ 
4
	_shadowEngine = new ShadowEngine(640, 480, 0x000000, 1, true); 
5
	 
6
	addChild(_shadowEngine.drawingArea); 
7
	 
8
	_shadowEngine.addLight(new Light(new Point(0, 0), 0xFF0000, 200, 1, 0)); 
9
	_shadowEngine.addLight(new Light(new Point(300, 200), 0x00FFFF, 300, 1, 0)); 
10
	 
11
	var temporaryVertices:Vector.<Point> = new Vector.<Point>(5); 
12
	temporaryVertices[0] = new Point(0, 0); 
13
	temporaryVertices[1] = new Point(0, 40); 
14
	temporaryVertices[2] = new Point(30, 50); 
15
	temporaryVertices[3] = new Point(60, 25); 
16
	temporaryVertices[4] = new Point(15, 0); 
17
	 
18
	_shadowEngine.addObject(new SolidObject(new Point(250, 250), temporaryVertices)); 
19
	 
20
	addEventListener(Event.ENTER_FRAME, engineLoop); 
21
}

Let's take a look at our result:


This is starting to take shape, isn't it?


Step 13: Introducing the Hard-Edged Shadow Casting

Now that we have our classes displaying in the screen properly and that our lights draw themselves correctly in the screen, it's time to begin our work towards shadow casting. The first method we will use is called the Hard-edged Shadow Casting. It is called that way because we assume the light is a single point and every light ray comes only from this point, creating a solid shadow behind the objects.


In order to draw the shadows, we need to set up a strategy. This is ours:

  • Draw a line connecting the light source and a vertex in our shape.
  • Identify whether this vertex is totally illuminated by the light (i.e. is in the "front"), is totally immersed in the shadow (i.e. is in the "back"), or is a boundary vertex. A boundary vertex lies in the intersection between front faced and back faced edges.
  • Create a Vector with all the back-facing vertices and both boundary vertices.
  • Draw triangles, connecting all the back facing and boundary vertices, in the light's shadow area.

All this code will be within the SolidObject class, because it is the only one that should know about its vertices. We will pass the light properties used in our class through a function called castShadows().


Step 14: A bit About Vectors

If you are not familiar with vectors yet, I suggest you take a look at my earlier tutorial, Euclidean Vectors in Flash.

In the next steps we will need to find the normal for every edge of our shape, then make a dot product between the normal and the vector passing through the light's point and the middle of the edge. If this dot product is less than 0, then the edge is back facing. If not, then it is front facing. We will not store the edges that are back and front facing, but instead we will store the index to the first point that makes the edge. This will make things easier later when determining the back facing vertices.


Description: Normals are shown in green. We will do a dot product between each normal and its corresponding orange vector (the vector from the light source to the middle of edge)


Step 15: Classifying the Edges

It is time to begin coding, and the first thing is to loop through each vertex and check if it belongs to an edge that is back facing or front facing. We will then store this in a Vector called _backFacing. We will be using the method described in the tutorial linked in the previous step in order to calculate the dot product and the normal of the edge, and we will have a function called checkEdgeBackFacing() to determine if an edge is back facing. In the SolidObject class:

1
 
2
private var _edgeNormalX:Number; 
3
private var _edgeNormalY:Number; 
4
 
5
private var _lightDirectionX:Number; 
6
private var _lightDirectionY:Number; 
7
 
8
private var _backFacing:Vector.<Boolean>; 
9
 
10
private function checkEdgeBackFacing(lightSourcePosition:Point, firstEdge:Point, secondEdge:Point):Boolean 
11
{ 
12
	// Normal 
13
	_edgeNormalX = -(secondEdge.y - firstEdge.y); 
14
	_edgeNormalY = secondEdge.x - firstEdge.x; 
15
	 
16
	// Vector from the light position to the edge's middle point 
17
	_lightDirectionX = lightSourcePosition.x - ((firstEdge.x + secondEdge.x) / 2); 
18
	_lightDirectionY = lightSourcePosition.y - ((firstEdge.y + secondEdge.y) / 2); 
19
	 
20
	// Dot product 
21
	if ((_edgeNormalX * _lightDirectionX) + (_edgeNormalY * _lightDirectionY) > 0) 
22
	{ 
23
		return false; 
24
	} 
25
	 
26
	return true; 
27
} 
28
 
29
public function castShadows(lightSourcePosition:Point):void 
30
{ 
31
	_backFacing = new Vector.<Boolean>(); 
32
	 
33
	var currentEdgeSecondPoint:int; 
34
	 
35
	_iterator = 0; 
36
	 
37
	// Looping through each vertex 
38
	while (_iterator < _numberOfVertices) 
39
	{ 
40
		// Calculating what is the next vertex that makes an edge 
41
		currentEdgeSecondPoint = (_iterator + 1) % _numberOfVertices; 
42
		 
43
		_backFacing[_iterator] = checkEdgeBackFacing(lightSourcePosition, new Point(_x + _vertices[_iterator].x, _y + _vertices[_iterator].y), new Point(_x + _vertices[currentEdgeSecondPoint].x, _y + _vertices[currentEdgeSecondPoint].y)); 
44
		 
45
		_iterator++; 
46
	} 
47
}

In the above code, note the importance of defining the vertices in a counter-clockwise direction. When we loop through the edges, we are running in a counter-clockwise direction and storing the facing of the edges in the same direction. If there wasn't an order when defining the vertices of each object, then this code would all get messed up.


Step 16: Defining the Boundary Vertices

Now that we know the facing of each edge, we can determine which vertices are the boundary vertices. We will determine the "starting" boundary vertex and the "ending" boundary vertex. The starting vertex is in the intersection with a front facing edge followed by a back facing edge. The ending vertex is in the intersection with a back facing edge followed by a front facing edge. Take a look at the image below:


Let's go to our code. In the SolidObject class, we will add the following code to the castShadows() function.

1
 
2
private var _currentPoint:int; 
3
private var _nextPoint:int; 
4
 
5
private var _startingBoundaryVertexIndex:int; 
6
private var _endingBoundaryVertexIndex:int; 
7
 
8
public function castShadows(lightSourcePosition:Point):void 
9
{ 
10
	_backFacing = new Vector.<Boolean>(); 
11
	 
12
	var currentEdgeSecondPoint:int; 
13
	 
14
	_iterator = 0; 
15
	 
16
	while (_iterator < _numberOfVertices) 
17
	{ 
18
		currentEdgeSecondPoint = (_iterator + 1) % _numberOfVertices; 
19
		 
20
		_backFacing[_iterator] = checkEdgeBackFacing(lightSourcePosition, new Point(_x + _vertices[_iterator].x, _y + _vertices[_iterator].y), new Point(_x + _vertices[currentEdgeSecondPoint].x, _y + _vertices[currentEdgeSecondPoint].y)); 
21
		 
22
		_iterator++; 
23
	} 
24
	 
25
	_startingBoundaryVertexIndex = 0; 
26
	_endingBoundaryVertexIndex = 0; 
27
	 
28
	_iterator = 0; 
29
	 
30
	_currentPoint = 0; 
31
	_nextPoint = 0; 
32
	 
33
	// Looping again through each vertex 
34
	while (_iterator < _numberOfVertices) 
35
	{ 
36
		_currentPoint = _iterator; 
37
		_nextPoint = (_iterator + 1) % _numberOfVertices; 
38
		 
39
		if (!_backFacing[_currentPoint] && _backFacing[_nextPoint]) 
40
			_startingBoundaryVertexIndex = _nextPoint; 
41
		 
42
		if (_backFacing[_currentPoint] && !_backFacing[_nextPoint]) 
43
			_endingBoundaryVertexIndex = _nextPoint; 
44
		 
45
		_iterator++; 
46
	} 
47
}

Step 17: Determining the Number of Vertices in the Shadow and Looping Through Them

Now that we know the starting and ending boundary vertices, we can tell which vertices are in the shadow, so we can draw the shadows later. However, this task is not as easy as it sounds. One may infer that it is just about looping from the _startingBoundaryVertexIndex to the _endingBoundaryVertexIndex, but what if we have the _endingBoundaryVertexIndex lower than the _startingBoundaryVertexIndex? We need to take care of this issue, while still being able to loop through all the vertices. Here is the code for it:

1
 
2
private var _shadowPointCount:int; 
3
private var _currentHullIndex:int; 
4
 
5
public function castShadows(lightSourcePosition:Point):void 
6
{ 
7
	_backFacing = new Vector.<Boolean>(); 
8
	 
9
	var currentEdgeSecondPoint:int; 
10
	 
11
	_iterator = 0; 
12
	 
13
	while (_iterator < _numberOfVertices) 
14
	{ 
15
		currentEdgeSecondPoint = (_iterator + 1) % _numberOfVertices; 
16
		 
17
		_backFacing[_iterator] = checkEdgeBackFacing(lightSourcePosition, new Point(_x + _vertices[_iterator].x, _y + _vertices[_iterator].y), new Point(_x + _vertices[currentEdgeSecondPoint].x, _y + _vertices[currentEdgeSecondPoint].y)); 
18
		 
19
		_iterator++; 
20
	} 
21
	 
22
	_startingBoundaryVertexIndex = 0; 
23
	_endingBoundaryVertexIndex = 0; 
24
	 
25
	_iterator = 0; 
26
	 
27
	_currentPoint = 0; 
28
	_nextPoint = 0; 
29
	 
30
	while (_iterator < _numberOfVertices) 
31
	{ 
32
		_currentPoint = _iterator; 
33
		_nextPoint = (_iterator + 1) % _numberOfVertices; 
34
		 
35
		if (!_backFacing[_currentPoint] && _backFacing[_nextPoint]) 
36
			_startingBoundaryVertexIndex = _nextPoint; 
37
		 
38
		if (_backFacing[_currentPoint] && !_backFacing[_nextPoint]) 
39
			_endingBoundaryVertexIndex = _nextPoint; 
40
		 
41
		_iterator++; 
42
	} 
43
	 
44
	// Counting how many points are in the shadow 
45
	_shadowPointCount = _endingBoundaryVertexIndex > _startingBoundaryVertexIndex ? _endingBoundaryVertexIndex - _startingBoundaryVertexIndex + 1 : _numberOfVertices - _startingBoundaryVertexIndex + _endingBoundaryVertexIndex + 1; 
46
	 
47
	_iterator = 0; 
48
	 
49
	// This will be used to access each point in the shadow 
50
	_currentHullIndex = _startingBoundaryVertexIndex; 
51
	 
52
	// Creating a loop with the same amount of iterations as there are points in the shadow 
53
	while (_iterator < _shadowPointCount) 
54
	{ 
55
		_currentHullIndex = (_currentHullIndex + 1) % _numberOfVertices; 
56
		 
57
		_iterator++; 
58
	} 
59
}

The code added counts the number of vertices in the shadows, then creates a _currentHullIndex property (named after the idea of a convex hull). The _currentHullIndex will loop through our vertices in the shadow. This will be the index used to access the vertices.


Step 18: The Light-to-Vertex Vectors

As stated in Step 13, we will have to draw triangles in order to build our shadow. The triangles will be based on the vertices in the shadow, but they aren't enough. We need a few extra points, which we will call the light-to-vertex vectors, that will give the illusion that the shadow goes to the infinity. In order to do that, we need to first determine these vectors, and then multiply them (refer to the tutorial pointed in Step 14 to learn how to multiply vectors) by a very big scalar number, so that they give the illusion we want.

Here is how we determine them:

1
 
2
private var _currentLightToVertex:Point; 
3
 
4
public function castShadows(lightSourcePosition:Point):void 
5
{ 
6
	_backFacing = new Vector.<Boolean>(); 
7
	 
8
	var currentEdgeSecondPoint:int; 
9
	 
10
	_iterator = 0; 
11
	 
12
	while (_iterator < _numberOfVertices) 
13
	{ 
14
		currentEdgeSecondPoint = (_iterator + 1) % _numberOfVertices; 
15
		 
16
		_backFacing[_iterator] = checkEdgeBackFacing(lightSourcePosition, new Point(_x + _vertices[_iterator].x, _y + _vertices[_iterator].y), new Point(_x + _vertices[currentEdgeSecondPoint].x, _y + _vertices[currentEdgeSecondPoint].y)); 
17
		 
18
		_iterator++; 
19
	} 
20
	 
21
	_startingBoundaryVertexIndex = 0; 
22
	_endingBoundaryVertexIndex = 0; 
23
	 
24
	_iterator = 0; 
25
	 
26
	_currentPoint = 0; 
27
	_nextPoint = 0; 
28
	 
29
	while (_iterator < _numberOfVertices) 
30
	{ 
31
		_currentPoint = _iterator; 
32
		_nextPoint = (_iterator + 1) % _numberOfVertices; 
33
		 
34
		if (!_backFacing[_currentPoint] && _backFacing[_nextPoint]) 
35
			_startingBoundaryVertexIndex = _nextPoint; 
36
		 
37
		if (_backFacing[_currentPoint] && !_backFacing[_nextPoint]) 
38
			_endingBoundaryVertexIndex = _nextPoint; 
39
		 
40
		_iterator++; 
41
	} 
42
	 
43
	_shadowPointCount = _endingBoundaryVertexIndex > _startingBoundaryVertexIndex ? _endingBoundaryVertexIndex - _startingBoundaryVertexIndex + 1 : _numberOfVertices - _startingBoundaryVertexIndex + _endingBoundaryVertexIndex + 1; 
44
	 
45
	_iterator = 0; 
46
	 
47
	_currentHullIndex = _startingBoundaryVertexIndex; 
48
	 
49
	while (_iterator < _shadowPointCount) 
50
	{ 
51
		_currentLightToVertex = new Point(); 
52
		 
53
		_currentLightToVertex.x = _x + _vertices[_currentHullIndex].x - lightSourcePosition.x; 
54
		_currentLightToVertex.y = _y + _vertices[_currentHullIndex].y - lightSourcePosition.y; 
55
		 
56
		// Normalizing the vector so that we can later multiply it by a big number 
57
		_currentLightToVertex.normalize(1); 
58
		 
59
		_currentHullIndex = (_currentHullIndex + 1) % _numberOfVertices; 
60
		 
61
		_iterator++; 
62
	} 
63
}

This code gives us the vector that goes from the light source to the vertex we want. In the next steps we will use it to draw the shadows we want.


Step 19: Details on drawing the shadows

We can now finally draw the shadows, but we must first create a more complete strategy for drawing them. We will need to draw a lot of triangles in order, so if we don't get it organized now, our code will become messy.


According to the image, we will start in the starting boundary vertex. Then a line will be drawn to the first light-to-vertex, and then another line will be drawn to the next shadow point. In order to complete the triangle, we will draw a line back to the starting boundary vertex.


Going to the next vertex, we will do the same thing, but now notice that there is a gap between both triangles. In order to fill this gap, we also must begin in the second vertex, then draw a line to the light-to-vertex of this vertex, and then draw another line to the previous light-to-vertex point. Then we complete the triangle drawing back to the second vertex.


Notice that we will need to hold the previous light-to-vertex as well, in order for this strategy to work.

When we reach the last vertex in the shadows, we will only draw a triangle using the light-to-vertex point for the last vertex and the previous light-to-vertex point.


Step 20: Drawing the Shadows

In order to draw the shadows, we will need the light source's shadow area to draw into them. Let's add a parameter to the castShadows() function and create our code!

1
 
2
private var _previousLightToVertex:Point; 
3
 
4
public function castShadows(lightSourcePosition:Point, drawToArea:Sprite):void 
5
{ 
6
	_backFacing = new Vector.<Boolean>(); 
7
	 
8
	var currentEdgeSecondPoint:int; 
9
	 
10
	_iterator = 0; 
11
	 
12
	while (_iterator < _numberOfVertices) 
13
	{ 
14
		currentEdgeSecondPoint = (_iterator + 1) % _numberOfVertices; 
15
		 
16
		_backFacing[_iterator] = checkEdgeBackFacing(lightSourcePosition, new Point(_x + _vertices[_iterator].x, _y + _vertices[_iterator].y), new Point(_x + _vertices[currentEdgeSecondPoint].x, _y + _vertices[currentEdgeSecondPoint].y)); 
17
		 
18
		_iterator++; 
19
	} 
20
	 
21
	_startingBoundaryVertexIndex = 0; 
22
	_endingBoundaryVertexIndex = 0; 
23
	 
24
	_iterator = 0; 
25
	 
26
	_currentPoint = 0; 
27
	_nextPoint = 0; 
28
	 
29
	while (_iterator < _numberOfVertices) 
30
	{ 
31
		_currentPoint = _iterator; 
32
		_nextPoint = (_iterator + 1) % _numberOfVertices; 
33
		 
34
		if (!_backFacing[_currentPoint] && _backFacing[_nextPoint]) 
35
			_startingBoundaryVertexIndex = _nextPoint; 
36
		 
37
		if (_backFacing[_currentPoint] && !_backFacing[_nextPoint]) 
38
			_endingBoundaryVertexIndex = _nextPoint; 
39
		 
40
		_iterator++; 
41
	} 
42
	 
43
	_shadowPointCount = _endingBoundaryVertexIndex > _startingBoundaryVertexIndex ? _endingBoundaryVertexIndex - _startingBoundaryVertexIndex + 1 : _numberOfVertices - _startingBoundaryVertexIndex + _endingBoundaryVertexIndex + 1; 
44
	 
45
	_iterator = 0; 
46
	 
47
	_currentHullIndex = _startingBoundaryVertexIndex; 
48
	 
49
	_currentLightToVertex = null; 
50
	_previousLightToVertex = null; 
51
	 
52
	while (_iterator < _shadowPointCount) 
53
	{ 
54
		if (_iterator != _shadowPointCount - 1) 
55
		{ 
56
			// This code will run for every point in the shadow, not including the last point (which will only draw one triangle instead of two) 
57
			 
58
			drawToArea.graphics.beginFill(0x000000, 1); 
59
			drawToArea.graphics.moveTo(_x + _vertices[_currentHullIndex].x, _y + _vertices[_currentHullIndex].y); 
60
			 
61
			_currentLightToVertex = new Point(); 
62
			 
63
			_currentLightToVertex.x = _x + _vertices[_currentHullIndex].x - lightSourcePosition.x; 
64
			_currentLightToVertex.y = _y + _vertices[_currentHullIndex].y - lightSourcePosition.y; 
65
			 
66
			_currentLightToVertex.normalize(1); 
67
			 
68
			drawToArea.graphics.lineTo(lightSourcePosition.x + (_currentLightToVertex.x * 10000), lightSourcePosition.y + (_currentLightToVertex.y * 10000)); 
69
			 
70
			drawToArea.graphics.lineTo(_x + _vertices[(_currentHullIndex + 1) % _numberOfVertices].x, _y + _vertices[(_currentHullIndex + 1) % _numberOfVertices].y); 
71
			 
72
			drawToArea.graphics.lineTo(_x + _vertices[_currentHullIndex].x, _y + _vertices[_currentHullIndex].y); 
73
			 
74
			drawToArea.graphics.endFill(); 
75
			 
76
			// Checking if we are past the first vector and start drawing the second "type" of triangle to give a full shadow idea 
77
			if (_previousLightToVertex) 
78
			{ 
79
				drawToArea.graphics.beginFill(0x000000, 1); 
80
				drawToArea.graphics.moveTo(_x + _vertices[_currentHullIndex].x, _y + _vertices[_currentHullIndex].y); 
81
				 
82
				drawToArea.graphics.lineTo(lightSourcePosition.x + (_currentLightToVertex.x * 10000), lightSourcePosition.y + (_currentLightToVertex.y * 10000)); 
83
				 
84
				drawToArea.graphics.lineTo(lightSourcePosition.x + (_previousLightToVertex.x * 10000), lightSourcePosition.y + (_previousLightToVertex.y * 10000)); 
85
				 
86
				drawToArea.graphics.lineTo(_x + _vertices[_currentHullIndex].x, _y + _vertices[_currentHullIndex].y); 
87
				 
88
				drawToArea.graphics.endFill(); 
89
			} 
90
		} 
91
		else 
92
		{ 
93
			// This code will only run for the last shadow point 
94
			 
95
			drawToArea.graphics.beginFill(0x000000, 1); 
96
			drawToArea.graphics.moveTo(_x + _vertices[_currentHullIndex].x, _y + _vertices[_currentHullIndex].y); 
97
			 
98
			_currentLightToVertex = new Point(); 
99
			 
100
			_currentLightToVertex.x = _x + _vertices[_currentHullIndex].x - lightSourcePosition.x; 
101
			_currentLightToVertex.y = _y + _vertices[_currentHullIndex].y - lightSourcePosition.y; 
102
			 
103
			_currentLightToVertex.normalize(1); 
104
			 
105
			drawToArea.graphics.lineTo(lightSourcePosition.x + (_currentLightToVertex.x * 10000), lightSourcePosition.y + (_currentLightToVertex.y * 10000)); 
106
			 
107
			drawToArea.graphics.lineTo(lightSourcePosition.x + (_previousLightToVertex.x * 10000), lightSourcePosition.y + (_previousLightToVertex.y * 10000)); 
108
			 
109
			drawToArea.graphics.lineTo(_x + _vertices[_currentHullIndex].x, _y + _vertices[_currentHullIndex].y); 
110
			 
111
			drawToArea.graphics.endFill(); 
112
		} 
113
		 
114
		_previousLightToVertex = _currentLightToVertex; 
115
		 
116
		_currentHullIndex = (_currentHullIndex + 1) % _numberOfVertices; 
117
		 
118
		_iterator++; 
119
	} 
120
}

Notice that we multiply the light-to-vertex points by 10000, a reasonable number to give the illusion of a shadow going to the infinity.


Step 21: Adding the Drawing Code to the Engine

In order to have our engine drawing the shadows, we need to add some code in the ShadowEngine class. Let's do it!

1
 
2
private var _currentObject:SolidObject; 
3
private var _objectIterator:int; 
4
 
5
private function drawLights():void 
6
{ 
7
	_lightMap.graphics.clear(); 
8
	_lightMap.graphics.beginFill(_ambientLight, _ambientLightAlpha); 
9
	_lightMap.graphics.drawRect(0, 0, ShadowEngine.WIDTH, ShadowEngine.HEIGHT); 
10
	_lightMap.graphics.endFill(); 
11
	 
12
	_lightIterator = 0; 
13
	 
14
	while (_lightIterator < _numberOfLights) 
15
	{ 
16
		_currentLight = _lights[_lightIterator]; 
17
		 
18
		_currentLight.draw(); 
19
		 
20
		_objectIterator = 0; 
21
		 
22
		while (_objectIterator < _numberOfObjects) 
23
		{ 
24
			_currentObject = _objects[_objectIterator]; 
25
			 
26
			_currentObject.castShadows(new Point(_currentLight.x, _currentLight.y), _currentLight.shadowArea); 
27
			 
28
			_objectIterator++; 
29
		} 
30
		 
31
		_lightIterator++; 
32
	} 
33
}

Don't forget to add the following import statement:

1
 
2
import flash.geom.Point;

With that code in the function, all left to do is make the Light's shadow area visible. Let's head to the Light class and add this code in initializeDrawingArea():

1
 
2
		private function initializeDrawingArea():void  
3
		{ 
4
			_drawingArea = new Sprite(); 
5
			 
6
			_shadowArea = new Sprite(); 
7
			 
8
			_drawingArea.addChild(_shadowArea); 
9
			 
10
			_lightGradientMatrix = new Matrix(); 
11
			_lightGradientMatrix.createGradientBox(_range * 2, _range * 2, 0, _x - _range, _y - _range); 
12
		}

Now, let's compile the project aaaaand...

Check out the result!

Congratulations!!! You have just made the first step to an awesome dynamic shadows engine! However, there are more things that we should do before using it.


Step 22: Creating Bounds

In order to optimize our engine, we must save processing time. Right now, our engine is looping through every light and making every object draw shadows in their drawing areas. Let's add bounds to every object and light and check whether the bounds of an object touch the bounds of a light. If this happens, then we draw the object's shadow into the light's drawing area. If not, then we skip the drawing. That will save a lot of performance.

Inside the Light class:

1
 
2
protected var _AABB:Rectangle; 
3
 
4
public function Light(initialPosition:Point, color:uint, range:Number, intensity:Number = 1, fallOff:Number = 0)  
5
{ 
6
	_x = initialPosition.x; 
7
	_y = initialPosition.y; 
8
	 
9
	_color = color; 
10
	_range = range; 
11
	_intensity = intensity; 
12
	_fallOff = fallOff; 
13
	 
14
	_AABB = new Rectangle(); 
15
	 
16
	initializeDrawingArea(); 
17
	createBall(); 
18
	updateAABB(); 
19
} 
20
 
21
protected function updateAABB():void 
22
{ 
23
	_AABB.x = _x - _range; 
24
	_AABB.y = _y - _range; 
25
	 
26
	_AABB.left = _x - _range; 
27
	_AABB.right = _x + _range; 
28
	 
29
	_AABB.top = _y - _range; 
30
	_AABB.bottom = _y + _range; 
31
} 
32
 
33
public function set x(value:Number):void 
34
{ 
35
	_x = value; 
36
	 
37
	updateAABB(); 
38
} 
39
 
40
public function set y(value:Number):void 
41
{ 
42
	_y = value; 
43
	 
44
	updateAABB(); 
45
} 
46
 
47
public function get AABB():Rectangle 
48
{ 
49
	return _AABB; 
50
}

(AABB stands for Axis-Aligned Bounding Box.)

This code will create the bounds of our light as a square, centred on the light, and update it every time we change our light's position. Don't forget to import the Rectangle class:

1
 
2
import flash.geom.Rectangle;

Now, inside SolidObject:

1
 
2
protected var _AABB:Rectangle; 
3
 
4
public function SolidObject(initialPosition:Point, vertices:Vector.<Point>)  
5
{ 
6
	_vertices = vertices.concat(); 
7
	 
8
	_numberOfVertices = _vertices.length; 
9
	 
10
	_x = initialPosition.x; 
11
	_y = initialPosition.y; 
12
	 
13
	createAABB(); 
14
	initializeDrawingArea(); 
15
} 
16
 
17
private function createAABB():void 
18
{ 
19
	_AABB = new Rectangle(0, 0, 0, 0); 
20
	 
21
	_iterator = 0; 
22
	 
23
	while (_iterator < _numberOfVertices) 
24
	{ 
25
		if (_vertices[_iterator].x < _AABB.left) 
26
		{ 
27
			_AABB.left = _vertices[_iterator].x; 
28
		} 
29
		else if (_vertices[_iterator].x > _AABB.right) 
30
		{ 
31
			_AABB.right = _vertices[_iterator].x; 
32
		} 
33
		 
34
		if (_vertices[_iterator].y < _AABB.top) 
35
		{ 
36
			_AABB.top = _vertices[_iterator].y; 
37
		} 
38
		else if (_vertices[_iterator].y > _AABB.bottom) 
39
		{ 
40
			_AABB.bottom = _vertices[_iterator].y; 
41
		} 
42
		 
43
		_iterator++; 
44
	} 
45
	 
46
	_AABB.x += _x; 
47
	_AABB.y += _y; 
48
} 
49
 
50
public function set x(value:Number):void 
51
{ 
52
	_AABB.x -= _x; 
53
	 
54
	_x = value; 
55
	 
56
	_AABB.x += _x; 
57
} 
58
 
59
public function set y(value:Number):void 
60
{ 
61
	_AABB.y -= _y; 
62
	 
63
	_y = value; 
64
	 
65
	_AABB.y += _y; 
66
} 
67
 
68
public function get AABB():Rectangle 
69
{ 
70
	return _AABB; 
71
}

Don't forget the import statement here, either:

1
 
2
import flash.geom.Rectangle;

The createAABB() function creates the bounds of our object based on the position the vertices were created. The reason we don't have an updateAABB() function in the SolidObject class is that, when the x or y properties change, all we need to do is bring the AABB rectangle to the new position, and that can easily be handled in the setter functions themselves.


Step 23: Simple Boundary Check

Now that we have our boundaries created in each object, let's do a quick check in the ShadowEngine class: if the bounds of an object intersect the bounds of a light, then the object's shadow should be cast in the light. If not, then nothing happens. The code:

1
 
2
		private function drawLights():void 
3
		{ 
4
			// Applying the ambient light 
5
			_lightMap.graphics.clear(); 
6
			_lightMap.graphics.beginFill(_ambientLight, _ambientLightAlpha); 
7
			_lightMap.graphics.drawRect(0, 0, ShadowEngine.WIDTH, ShadowEngine.HEIGHT); 
8
			_lightMap.graphics.endFill(); 
9
			 
10
			_lightIterator = 0; 
11
			 
12
			// Looping through each light and making it draw 
13
			while (_lightIterator < _numberOfLights) 
14
			{ 
15
				_currentLight = _lights[_lightIterator]; 
16
				 
17
				_currentLight.draw(); 
18
				 
19
				_objectIterator = 0; 
20
				 
21
				while (_objectIterator < _numberOfObjects) 
22
				{ 
23
					_currentObject = _objects[_objectIterator]; 
24
					 
25
					// Checking for bounding rectangle intersection 
26
					if (_currentLight.AABB.intersects(_currentObject.AABB)) 
27
					{ 
28
						_currentObject.castShadows(new Point(_currentLight.x, _currentLight.y), _currentLight.shadowArea); 
29
					} 
30
					 
31
					_objectIterator++; 
32
				} 
33
				 
34
				_lightIterator++; 
35
			} 
36
		}

With that code, we saved a lot of process time when our engine begins to have more objects and lights!


Step 24: Correction of the Light's Matrix

If we take another look at our code in our Light class, we will notice that our _lightGradientMatrix depends on the Light's x and y properties, and it doesn't update when these properties change. Let's fix that:

1
 
2
protected function updateGradientMatrix():void 
3
{ 
4
	_lightGradientMatrix.createGradientBox(_range * 2, _range * 2, 0, _x - _range, _y - _range); 
5
} 
6
 
7
public function set x(value:Number):void 
8
{ 
9
	_x = value; 
10
	 
11
	updateAABB(); 
12
	updateGradientMatrix(); 
13
} 
14
 
15
public function set y(value:Number):void 
16
{ 
17
	_y = value; 
18
	 
19
	updateAABB(); 
20
	updateGradientMatrix(); 
21
}

With this code, everything should be right for our Light class. Everything that depends on the x and y properties are updated.


Step 25: Creating a Mask for the Light

If you had the interest to try a few things in our current engine, you will notice that if you change the ambient light, you will notice something very weird.


Description: our engine with the ambient light set to full green (0x00FF00) with an alpha of 0.3 and a white (0xFFFFFF) background.

See that our object's shadow extends to the infinity and takes up the space (the red rectangle) that should be the ambient light's space, since the cyan light doesn't have "power" to illuminate everything in the stage? We need to fix that, and for that we can simply add a circular mask to the Light. The code:

1
 
2
protected var _drawingAreaMask:Sprite; 
3
 
4
private function initializeDrawingArea():void  
5
{ 
6
	_drawingArea = new Sprite(); 
7
	 
8
	_shadowArea = new Sprite(); 
9
	 
10
	_drawingArea.addChild(_shadowArea); 
11
	 
12
	_lightGradientMatrix = new Matrix(); 
13
	_lightGradientMatrix.createGradientBox(_range * 2, _range * 2, 0, _x - _range, _y - _range); 
14
	 
15
	_drawingAreaMask = new Sprite(); 
16
	_drawingAreaMask.graphics.beginFill(0x000000, 1); 
17
	_drawingAreaMask.graphics.drawCircle(_x, _y, _range); 
18
	_drawingAreaMask.graphics.endFill(); 
19
	 
20
	_drawingArea.mask = _drawingAreaMask; 
21
} 
22
 
23
protected function updateDrawingAreaMask():void 
24
{ 
25
	_drawingAreaMask.graphics.clear(); 
26
	_drawingAreaMask.graphics.beginFill(0x000000, 1); 
27
	_drawingAreaMask.graphics.drawCircle(_x, _y, _range); 
28
	_drawingAreaMask.graphics.endFill(); 
29
} 
30
 
31
public function set x(value:Number):void 
32
{ 
33
	_x = value; 
34
	 
35
	updateAABB(); 
36
	updateGradientMatrix(); 
37
	updateDrawingAreaMask(); 
38
} 
39
 
40
public function set y(value:Number):void 
41
{ 
42
	_y = value; 
43
	 
44
	updateAABB(); 
45
	updateGradientMatrix(); 
46
	updateDrawingAreaMask(); 
47
}

The code part is done. If we compile our project (maintaining the properties in the description of this step's image), this is what we will see:


Still doesn't look quite right, does it? Time to fix those shadows!


Step 26: Using the Erase Blend Mode and Cleaning the Shadows

Right now our engine draws shadows in a full black (0x000000) color. The problem with this is that not always we have a full black ambient light and the shadows should be the absence of light. Our objective in this step is to completely remove the shadows from the visible area, while still leaving an empty space in its location. In order to do that, we need to simply add a BlendMode.ERASE in our Light's shadow area. However, this requires that the parent display object container (in our case, the Light's drawing area) has a blend mode set to Layer.

Let's do it. In Light.as:

1
 
2
private function initializeDrawingArea():void  
3
{ 
4
	_drawingArea = new Sprite(); 
5
	 
6
	_shadowArea = new Sprite(); 
7
	 
8
	_drawingArea.addChild(_shadowArea); 
9
	 
10
	_drawingArea.blendMode = BlendMode.LAYER; 
11
	 
12
	_shadowArea.blendMode = BlendMode.ERASE; 
13
	 
14
	_lightGradientMatrix = new Matrix(); 
15
	_lightGradientMatrix.createGradientBox(_range * 2, _range * 2, 0, _x - _range, _y - _range); 
16
	 
17
	_drawingAreaMask = new Sprite(); 
18
	_drawingAreaMask.graphics.beginFill(0x000000, 1); 
19
	_drawingAreaMask.graphics.drawCircle(_x, _y, _range); 
20
	_drawingAreaMask.graphics.endFill(); 
21
	 
22
	_drawingArea.mask = _drawingAreaMask; 
23
}

And add the following import statement:

1
 
2
import flash.display.BlendMode;

We also must notice that our Light's shadow area isn't being cleared on every frame. That way, if any object moves, the shadows will "sum up", which definitely isn't what we want. It also starts to lag after some time, due to not clearing the shadow area before drawing the new shadow. Let's go to ShadowEngine and add a single line of code to fix that:

1
 
2
private function drawLights():void 
3
{ 
4
	// Applying the ambient light 
5
	_lightMap.graphics.clear(); 
6
	_lightMap.graphics.beginFill(_ambientLight, _ambientLightAlpha); 
7
	_lightMap.graphics.drawRect(0, 0, ShadowEngine.WIDTH, ShadowEngine.HEIGHT); 
8
	_lightMap.graphics.endFill(); 
9
	 
10
	_lightIterator = 0; 
11
	 
12
	// Looping through each light and making it draw 
13
	while (_lightIterator < _numberOfLights) 
14
	{ 
15
		_currentLight = _lights[_lightIterator]; 
16
		 
17
		_currentLight.shadowArea.graphics.clear(); 
18
		 
19
		_currentLight.draw(); 
20
		 
21
		_objectIterator = 0; 
22
		 
23
		while (_objectIterator < _numberOfObjects) 
24
		{ 
25
			_currentObject = _objects[_objectIterator]; 
26
			 
27
			if (_currentLight.AABB.intersects(_currentObject.AABB)) 
28
			{ 
29
				_currentObject.castShadows(new Point(_currentLight.x, _currentLight.y), _currentLight.shadowArea); 
30
			} 
31
			 
32
			_objectIterator++; 
33
		} 
34
		 
35
		//_currentLight.clearShadowsFromDrawingArea(); 
36
		 
37
		_lightIterator++; 
38
	} 
39
}

If we compile our project now, that's what we should get:


Works like a charm! You see how the shadow of the solid object is now the absence of cyan light, rather than the absence of all light, including the ambient light?

Our next step is to improve the look of our shadows.


Step 27: Introducing Soft-Edged Shadow Casting

Our engine has been using hard-edged shadow casting until now. This isn't a problem, since it is, in theory, how shadows should work with lights represented as points. However, in reality there isn't a source of light that behaves as a single point: every light source has some kind of dimension, even if it's small. We can view these light sources as an infinity of other tiny light sources, so tiny that they can be considered points. That way, a real light source can be represented as being made up of many of these "tiny light sources". We would spend a lot of time adding this to our engine, since this would require a lot of processing, and Flash wouldn't handle that for a few light sources per frame.

Instead of taking the approach cited above, we are going to use a small trick to give the impression of soft-edged shadow casting. Compare both images below:



Can you guess what are we going to do? That's right: we will add a small blur filter to our lights, to give the same idea of soft-edged shadow casting. Let's do that in ShadowEngine:

1
 
2
private function createLightMap():void 
3
{ 
4
	_lights = new Vector.<Light>(); 
5
	 
6
	_lightMap = new Sprite(); 
7
	 
8
	_lightMap.scrollRect = new Rectangle(0, 0, ShadowEngine.WIDTH, ShadowEngine.HEIGHT); 
9
	 
10
	_lightMap.blendMode = BlendMode.MULTIPLY; 
11
	 
12
	_lightMap.filters = [new BlurFilter(5, 5, 1)]; 
13
	 
14
	_drawingArea.addChild(_lightMap); 
15
	 
16
	trace("Light map created with success!"); 
17
	 
18
	if (_drawBalls) 
19
	{ 
20
		_ballsMap = new Sprite(); 
21
		 
22
		_ballsMap.scrollRect = new Rectangle(0, 0, ShadowEngine.WIDTH, ShadowEngine.HEIGHT); 
23
		 
24
		_drawingArea.addChild(_ballsMap); 
25
		 
26
		trace("Balls map created with success!"); 
27
	} 
28
}

And don't forget the import statement:

1
 
2
import flash.filters.BlurFilter;

Let's change our ambient light back to full black (0x000000) with an alpha of 1 to see the effect better. When we compile our project, this is what we see:


Notice something weird around our object? Me too. Let's see what's causing the problem and how to fix that.


Step 28: Adding the Shadows on our Objects' Shapes

The problem with our engine right now is that we are only drawing the shadows behind our objects. However, we forgot that in the place where our objects are, there is also shadow! We can easily fix that by drawing their shape in the castShadows() function, in the SolidObject class. Remember the process used in the draw() function for our solid objects? We will do the same thing:

1
 
2
public function castShadows(lightSourcePosition:Point, drawToArea:Sprite):void 
3
{ 
4
	_backFacing = new Vector.<Boolean>(); 
5
	 
6
	var currentEdgeSecondPoint:int; 
7
	 
8
	_iterator = 0; 
9
	 
10
	while (_iterator < _numberOfVertices) 
11
	{ 
12
		currentEdgeSecondPoint = (_iterator + 1) % _numberOfVertices; 
13
		 
14
		_backFacing[_iterator] = checkEdgeBackFacing(lightSourcePosition, new Point(_x + _vertices[_iterator].x, _y + _vertices[_iterator].y), new Point(_x + _vertices[currentEdgeSecondPoint].x, _y + _vertices[currentEdgeSecondPoint].y)); 
15
		 
16
		_iterator++; 
17
	} 
18
	 
19
	_startingBoundaryVertexIndex = 0; 
20
	_endingBoundaryVertexIndex = 0; 
21
	 
22
	_iterator = 0; 
23
	 
24
	_currentPoint = 0; 
25
	_nextPoint = 0; 
26
	 
27
	while (_iterator < _numberOfVertices) 
28
	{ 
29
		_currentPoint = _iterator; 
30
		_nextPoint = (_iterator + 1) % _numberOfVertices; 
31
		 
32
		if (!_backFacing[_currentPoint] && _backFacing[_nextPoint]) 
33
			_startingBoundaryVertexIndex = _nextPoint; 
34
		 
35
		if (_backFacing[_currentPoint] && !_backFacing[_nextPoint]) 
36
			_endingBoundaryVertexIndex = _nextPoint; 
37
		 
38
		_iterator++; 
39
	} 
40
	 
41
	_shadowPointCount = _endingBoundaryVertexIndex > _startingBoundaryVertexIndex ? _endingBoundaryVertexIndex - _startingBoundaryVertexIndex + 1 : _numberOfVertices - _startingBoundaryVertexIndex + _endingBoundaryVertexIndex + 1; 
42
	 
43
	_iterator = 0; 
44
	 
45
	_currentHullIndex = _startingBoundaryVertexIndex; 
46
	 
47
	_currentLightToVertex = null; 
48
	_previousLightToVertex = null; 
49
	 
50
	while (_iterator < _shadowPointCount) 
51
	{ 
52
		if (_iterator != _shadowPointCount - 1) 
53
		{ 
54
			drawToArea.graphics.beginFill(0x000000, 1); 
55
			drawToArea.graphics.moveTo(_x + _vertices[_currentHullIndex].x, _y + _vertices[_currentHullIndex].y); 
56
			 
57
			_currentLightToVertex = new Point(); 
58
			 
59
			_currentLightToVertex.x = _x + _vertices[_currentHullIndex].x - lightSourcePosition.x; 
60
			_currentLightToVertex.y = _y + _vertices[_currentHullIndex].y - lightSourcePosition.y; 
61
			 
62
			_currentLightToVertex.normalize(1); 
63
			 
64
			drawToArea.graphics.lineTo(lightSourcePosition.x + (_currentLightToVertex.x * 10000), lightSourcePosition.y + (_currentLightToVertex.y * 10000)); 
65
			 
66
			drawToArea.graphics.lineTo(_x + _vertices[(_currentHullIndex + 1) % _numberOfVertices].x, _y + _vertices[(_currentHullIndex + 1) % _numberOfVertices].y); 
67
			 
68
			drawToArea.graphics.lineTo(_x + _vertices[_currentHullIndex].x, _y + _vertices[_currentHullIndex].y); 
69
			 
70
			drawToArea.graphics.endFill(); 
71
			 
72
			if (_previousLightToVertex) 
73
			{ 
74
				drawToArea.graphics.beginFill(0x000000, 1); 
75
				drawToArea.graphics.moveTo(_x + _vertices[_currentHullIndex].x, _y + _vertices[_currentHullIndex].y); 
76
				 
77
				drawToArea.graphics.lineTo(lightSourcePosition.x + (_currentLightToVertex.x * 10000), lightSourcePosition.y + (_currentLightToVertex.y * 10000)); 
78
				 
79
				drawToArea.graphics.lineTo(lightSourcePosition.x + (_previousLightToVertex.x * 10000), lightSourcePosition.y + (_previousLightToVertex.y * 10000)); 
80
				 
81
				drawToArea.graphics.lineTo(_x + _vertices[_currentHullIndex].x, _y + _vertices[_currentHullIndex].y); 
82
				 
83
				drawToArea.graphics.endFill(); 
84
			} 
85
		} 
86
		else 
87
		{ 
88
			drawToArea.graphics.beginFill(0x000000, 1); 
89
			drawToArea.graphics.moveTo(_x + _vertices[_currentHullIndex].x, _y + _vertices[_currentHullIndex].y); 
90
			 
91
			_currentLightToVertex = new Point(); 
92
			 
93
			_currentLightToVertex.x = _x + _vertices[_currentHullIndex].x - lightSourcePosition.x; 
94
			_currentLightToVertex.y = _y + _vertices[_currentHullIndex].y - lightSourcePosition.y; 
95
			 
96
			_currentLightToVertex.normalize(1); 
97
			 
98
			drawToArea.graphics.lineTo(lightSourcePosition.x + (_currentLightToVertex.x * 10000), lightSourcePosition.y + (_currentLightToVertex.y * 10000)); 
99
			 
100
			drawToArea.graphics.lineTo(lightSourcePosition.x + (_previousLightToVertex.x * 10000), lightSourcePosition.y + (_previousLightToVertex.y * 10000)); 
101
			 
102
			drawToArea.graphics.lineTo(_x + _vertices[_currentHullIndex].x, _y + _vertices[_currentHullIndex].y); 
103
			 
104
			drawToArea.graphics.endFill(); 
105
		} 
106
		 
107
		_previousLightToVertex = _currentLightToVertex; 
108
		 
109
		_currentHullIndex = (_currentHullIndex + 1) % _numberOfVertices; 
110
		 
111
		_iterator++; 
112
	} 
113
	 
114
	drawToArea.graphics.beginFill(0x000000, 1); 
115
	 
116
	drawToArea.graphics.moveTo(_vertices[0].x + _x, _vertices[0].y + _y); 
117
	 
118
	_iterator = 1; 
119
	 
120
	while (_iterator < _numberOfVertices) 
121
	{ 
122
		drawToArea.graphics.lineTo(_vertices[_iterator].x + _x, _vertices[_iterator].y + _y); 
123
		 
124
		_iterator++; 
125
	} 
126
	 
127
	drawToArea.graphics.lineTo(_vertices[0].x + _x, _vertices[0].y + _y); 
128
	 
129
	drawToArea.graphics.endFill(); 
130
}

After compiling, this is what we get:


Did you notice that our object has disappeared? This happened because the light map is being added over the object map, and since our ambient light is totally black with an alpha of 1, our object can't be seen. Let's change that by making our ambient light a bit transparent. In the Main class:

1
 
2
private function init(e:Event):void  
3
{ 
4
	_shadowEngine = new ShadowEngine(640, 480, 0x000000, 0.7, true); 
5
	 
6
	addChild(_shadowEngine.drawingArea); 
7
	 
8
	_shadowEngine.addLight(new Light(new Point(0, 0), 0xFF0000, 200, 1, 0)); 
9
	_shadowEngine.addLight(new Light(new Point(300, 200), 0x00FFFF, 300, 1, 0)); 
10
	 
11
	var temporaryVertices:Vector.<Point> = new Vector.<Point>(5); 
12
	temporaryVertices[0] = new Point(0, 0); 
13
	temporaryVertices[1] = new Point(0, 40); 
14
	temporaryVertices[2] = new Point(30, 50); 
15
	temporaryVertices[3] = new Point(60, 25); 
16
	temporaryVertices[4] = new Point(15, 0); 
17
	 
18
	_shadowEngine.addObject(new SolidObject(new Point(250, 250), temporaryVertices)); 
19
	 
20
	addEventListener(Event.ENTER_FRAME, engineLoop); 
21
}

If we compile our project now, we can see that everything works fine!



Step 29: Adding More Objects and a Problem

It's time to add some more objects in the screen. Let's create two more objects in the Main init() function:

1
 
2
private function init(e:Event):void  
3
{ 
4
	_shadowEngine = new ShadowEngine(640, 480, 0x000000, 0.7, true); 
5
	 
6
	addChild(_shadowEngine.drawingArea); 
7
	 
8
	_shadowEngine.addLight(new Light(new Point(0, 0), 0xFF0000, 200, 1, 0)); 
9
	_shadowEngine.addLight(new Light(new Point(300, 200), 0x00FFFF, 300, 1, 0)); 
10
	 
11
	var temporaryVertices:Vector.<Point> = new Vector.<Point>(5); 
12
	temporaryVertices[0] = new Point(0, 0); 
13
	temporaryVertices[1] = new Point(0, 40); 
14
	temporaryVertices[2] = new Point(30, 50); 
15
	temporaryVertices[3] = new Point(60, 25); 
16
	temporaryVertices[4] = new Point(15, 0); 
17
	 
18
	_shadowEngine.addObject(new SolidObject(new Point(250, 250), temporaryVertices)); 
19
	 
20
	temporaryVertices = new Vector.<Point>(4); 
21
	 
22
	temporaryVertices[0] = new Point(0, 0); 
23
	temporaryVertices[1] = new Point(0, 60); 
24
	temporaryVertices[2] = new Point(30, 60); 
25
	temporaryVertices[3] = new Point(30, 0); 
26
	 
27
	_shadowEngine.addObject(new SolidObject(new Point(280, 170), temporaryVertices)); 
28
	 
29
	temporaryVertices = new Vector.<Point>(3); 
30
	 
31
	temporaryVertices[0] = new Point(30, 0); 
32
	temporaryVertices[1] = new Point(0, 40); 
33
	temporaryVertices[2] = new Point(60, 40); 
34
	 
35
	_shadowEngine.addObject(new SolidObject(new Point(450, 320), temporaryVertices)); 
36
	 
37
	addEventListener(Event.ENTER_FRAME, engineLoop); 
38
}

Don't forget: the vertices must be always declared in the counter-clockwise direction!

After we compile our project, this is what we get:


Hey! Something is wrong! We added an object "around" our light source, and that caused it not to create light anymore! How can we fix that?


Step 30: Checking if the Light Source is Inside a Polygon

In order to fix our problem, we must, in addition to checking whether the bounds of a light intersects with the bounds of an object, check whether the light is inside the shape. If that is true, we simply will not ask that object to cast shadows on our light, giving the illusion that the light is over the object.

Do you remember the tutorial about vectors? It also explains a few methods of checking if a point is inside any shape (Steps 15-22).

We can implement any method that deals with convex shapes, since our engine uses convex shapes. Let's instead add the universal method of the even-odd check, because someone might want to change this engine to work with other shapes, and thus the rest of our code has to work with it.

Let's add a function checkLightInsideShape() in our ShadowEngine class:

1
 
2
private function checkLightInsideShape(point:Point, shapeVertices:Vector.<Point>):Boolean 
3
{ 
4
	var numberOfSides:int = shapeVertices.length; 
5
	 
6
	var i:int = 0; 
7
	var j:int = numberOfSides - 1; 
8
	 
9
	var oddNodes:Boolean = false; 
10
	 
11
	while (i < numberOfSides) 
12
	{ 
13
		if ((shapeVertices[i].y < point.y && shapeVertices[j].y >= point.y) || 
14
			(shapeVertices[j].y < point.y && shapeVertices[i].y >= point.y)) 
15
		{ 
16
			if (shapeVertices[i].x + (((point.y - shapeVertices[i].y) / (shapeVertices[j].y - shapeVertices[i].y)) * 
17
				(shapeVertices[j].x - shapeVertices[i].x)) < point.x) 
18
			{ 
19
				oddNodes = !oddNodes; 
20
			} 
21
		} 
22
		 
23
		j = i; 
24
		 
25
		i++; 
26
	} 
27
	 
28
	return oddNodes; 
29
}

And then, let's check this in our drawLights() function:

1
 
2
private function drawLights():void 
3
{ 
4
	_lightMap.graphics.clear(); 
5
	_lightMap.graphics.beginFill(_ambientLight, _ambientLightAlpha); 
6
	_lightMap.graphics.drawRect(0, 0, ShadowEngine.WIDTH, ShadowEngine.HEIGHT); 
7
	_lightMap.graphics.endFill(); 
8
	 
9
	_lightIterator = 0; 
10
	 
11
	while (_lightIterator < _numberOfLights) 
12
	{ 
13
		_currentLight = _lights[_lightIterator]; 
14
		 
15
		_currentLight.shadowArea.graphics.clear(); 
16
		 
17
		_currentLight.draw(); 
18
		 
19
		_objectIterator = 0; 
20
		 
21
		while (_objectIterator < _numberOfObjects) 
22
		{ 
23
			_currentObject = _objects[_objectIterator]; 
24
			 
25
			if (_currentLight.AABB.intersects(_currentObject.AABB)) 
26
			{ 
27
				if (!checkLightInsideShape(new Point(_currentLight.x - _currentObject.x, _currentLight.y - _currentObject.y), _currentObject.vertices)) 
28
				{ 
29
					_currentObject.castShadows(new Point(_currentLight.x, _currentLight.y), _currentLight.shadowArea); 
30
				} 
31
			} 
32
			 
33
			_objectIterator++; 
34
		} 
35
		 
36
		_lightIterator++; 
37
	} 
38
}

Notice that we must access the current object's vertices, but currently there's no way to do that. Let's go to our SolidObject class and add a small getter function:

1
 
2
public function get vertices():Vector.<Point> 
3
{ 
4
	return _vertices; 
5
}

With that, we can hit compile and see our result:

Check out the result!

Isn't it getting good?


Step 31: Further Improvements

Our engine is almost ready to use, but what do you think of making some improvements first? There's also a bug in our current code, so let's fix it first. In our Light class, we forgot to change the ball's x and y positions when our light moved too, so let's add this code in there:

1
 
2
public function set x(value:Number):void 
3
{ 
4
	_x = value; 
5
	 
6
	_ball.x = _x; 
7
	 
8
	updateAABB(); 
9
	updateGradientMatrix(); 
10
	updateDrawingAreaMask(); 
11
} 
12
 
13
public function set y(value:Number):void 
14
{ 
15
	_y = value; 
16
	 
17
	_ball.y = _y; 
18
	 
19
	updateAABB(); 
20
	updateGradientMatrix(); 
21
	updateDrawingAreaMask(); 
22
}

Now our engine is free of bugs and you can already use it, but what's next? There is so much we could do with it! The classes in our engine were built in order to aid the creation of many types of objects and lights. For example, we could create a spot light, or we could create a RegularPolygon class that will represent a solid object in a regular polygon shape with the amount of sides we want. We could create support for rotation, and even add support to using different images for the solid objects, other than only drawing a half-transparent red shape!

In the next steps, you will learn how to create different objects and add support for different images, as well as for rotation.


Step 32: Creating a RegularPolygon Class

Our RegularPolygon class will be created to ease the process of creating regular polygons for the shadow engine. The class will create automatically a polygon once we pass the required parameters to it.

Regular polygons share the property of having all of its vertices defined in a single circle. We will use that to create our class. Basically, we will loop through the circle, defining the vertices as the current cosine and sine values of the angle. We will need the circle's radius in order to do that, as well as the number of sides. Take a look at the code:

1
 
2
package objects  
3
{ 
4
	import flash.geom.Point; 
5
	 
6
	public class RegularPolygon extends SolidObject  
7
	{ 
8
		protected var _circleRadius:Number; 
9
		protected var _numberOfSides:int; 
10
		 
11
		public function RegularPolygon(initialPosition:Point, circleRadius:Number, sides:int)  
12
		{ 
13
			_circleRadius = circleRadius; 
14
			_numberOfSides = sides; 
15
			 
16
			var points:Vector.<Point> = new Vector.<Point>(_numberOfSides); 
17
			 
18
			var iterator:int = 0; 
19
			 
20
			var angleStep:Number = 2 * Math.PI / _numberOfSides; 
21
			 
22
			while (iterator < _numberOfSides) 
23
			{ 
24
				points[iterator] = new Point((Math.cos(iterator * angleStep) * _circleRadius), (Math.sin(iterator * angleStep) * _circleRadius)); 
25
				 
26
				iterator++; 
27
			} 
28
			 
29
			super(initialPosition, points); 
30
		} 
31
		 
32
	} 
33
 
34
}

In the code, we define the angleStep property. This property is the amount of radians we will "walk" in each iteration of the loop, completing the circle on the last iteration. Take a look at the image:


Our Regular Polygon class is almost done! It would be really cool if we could define the radius of our circle based on the amount of sides our polygon has and the size of each side. Here is a quick formula for getting the circle's radius given the size (length) of a side and number of sides:


Let's add it to our code and make our class able to receive either the circle's radius or the size of each side:

1
 
2
package objects  
3
{ 
4
	import flash.geom.Point; 
5
	 
6
	public class RegularPolygon extends SolidObject  
7
	{ 
8
		protected var _circleRadius:Number; 
9
		protected var _numberOfSides:int; 
10
		protected var _sideSize:Number; 
11
		 
12
		public function RegularPolygon(initialPosition:Point, sides:int, radiusOrSideSize:Object)  
13
		{ 
14
			_numberOfSides = sides; 
15
			 
16
			if (radiusOrSideSize.radius) 
17
			{ 
18
				_circleRadius = radiusOrSideSize.radius; 
19
				 
20
				_sideSize = _circleRadius * 2 * Math.sin(Math.PI / _numberOfSides); 
21
			} 
22
			else if (radiusOrSideSize.size) 
23
			{ 
24
				_sideSize = radiusOrSideSize.size; 
25
				 
26
				_circleRadius = _sideSize / (2 * Math.sin(Math.PI / _numberOfSides)); 
27
			} 
28
			 
29
			var points:Vector.<Point> = new Vector.<Point>(_numberOfSides); 
30
			 
31
			var iterator:int = 0; 
32
			 
33
			var angleStep:Number = 2 * Math.PI / _numberOfSides; 
34
			 
35
			while (iterator < _numberOfSides) 
36
			{ 
37
				points[iterator] = new Point((Math.cos(iterator * angleStep) * _circleRadius), (Math.sin(iterator * angleStep) * _circleRadius)); 
38
				 
39
				iterator++; 
40
			} 
41
			 
42
			super(initialPosition, points); 
43
		} 
44
		 
45
	} 
46
 
47
}

And that's our RegularPolygon class! We can add a regular polygon to our engine with the following code in Main:

1
 
2
private function init(e:Event):void  
3
{ 
4
	_shadowEngine = new ShadowEngine(640, 480, 0x000000, 0.7, true); 
5
	 
6
	addChild(_shadowEngine.drawingArea); 
7
	 
8
	_shadowEngine.addLight(new Light(new Point(0, 0), 0xFF0000, 200, 1, 0)); 
9
	_shadowEngine.addLight(new Light(new Point(300, 200), 0x00FFFF, 300, 1, 0)); 
10
	 
11
	var temporaryVertices:Vector.<Point> = new Vector.<Point>(5); 
12
	temporaryVertices[0] = new Point(0, 0); 
13
	temporaryVertices[1] = new Point(0, 40); 
14
	temporaryVertices[2] = new Point(30, 50); 
15
	temporaryVertices[3] = new Point(60, 25); 
16
	temporaryVertices[4] = new Point(15, 0); 
17
	 
18
	_shadowEngine.addObject(new SolidObject(new Point(250, 250), temporaryVertices)); 
19
	 
20
	temporaryVertices = new Vector.<Point>(4); 
21
	 
22
	temporaryVertices[0] = new Point(0, 0); 
23
	temporaryVertices[1] = new Point(0, 60); 
24
	temporaryVertices[2] = new Point(30, 60); 
25
	temporaryVertices[3] = new Point(30, 0); 
26
	 
27
	_shadowEngine.addObject(new SolidObject(new Point(280, 170), temporaryVertices)); 
28
	 
29
	temporaryVertices = new Vector.<Point>(3); 
30
	 
31
	temporaryVertices[0] = new Point(30, 0); 
32
	temporaryVertices[1] = new Point(0, 40); 
33
	temporaryVertices[2] = new Point(60, 40); 
34
	 
35
	_shadowEngine.addObject(new SolidObject(new Point(450, 320), temporaryVertices)); 
36
	 
37
	_shadowEngine.addObject(new RegularPolygon(new Point(400, 150), 5, { size: 30 } )); 
38
	 
39
	addEventListener(Event.ENTER_FRAME, engineLoop); 
40
}

And here's our result:



Step 33: Rotating our Shapes

It's about time to let our shapes rotate, but as you may have seen, we will have to rotate the vertices according to the origin point of our shape! Let's take another look at the Euclidean Vectors tutorial in order to get an idea of how to rotate our shapes.

Did you see it? Let's create a applyVerticesRotation() function in our SolidObject class:

1
 
2
public function applyVerticesRotation(rotationAngle:Number):void 
3
{ 
4
	_iterator = 0; 
5
	 
6
	while (_iterator < _numberOfVertices) 
7
	{ 
8
		_vertices[_iterator] = rotatePoint(_vertices[_iterator], rotationAngle); 
9
		 
10
		_iterator++; 
11
	} 
12
} 
13
 
14
private function rotatePoint(point:Point, angleRadians:Number):Point 
15
{ 
16
	var tempX:Number = point.x * Math.cos(angleRadians) - point.y * Math.sin(angleRadians); 
17
	var tempY:Number = point.x * Math.sin(angleRadians) + point.y * Math.cos(angleRadians); 
18
	 
19
	return new Point(tempX, tempY); 
20
}

After that, let's do a quick change in our init() and engineLoop() function in the Main class, so that we rotate a shape 5 degrees every frame. Here is the code:

1
 
2
private var _randomShape:SolidObject; 
3
 
4
private function init(e:Event):void  
5
{ 
6
	_shadowEngine = new ShadowEngine(640, 480, 0x000000, 0.7, true); 
7
	 
8
	addChild(_shadowEngine.drawingArea); 
9
	 
10
	_shadowEngine.addLight(new Light(new Point(0, 0), 0xFF0000, 200, 1, 0)); 
11
	_shadowEngine.addLight(new Light(new Point(300, 200), 0x00FFFF, 300, 1, 0)); 
12
	 
13
	var temporaryVertices:Vector.<Point> = new Vector.<Point>(5); 
14
	temporaryVertices[0] = new Point(0, 0); 
15
	temporaryVertices[1] = new Point(0, 40); 
16
	temporaryVertices[2] = new Point(30, 50); 
17
	temporaryVertices[3] = new Point(60, 25); 
18
	temporaryVertices[4] = new Point(15, 0); 
19
	 
20
	_randomShape = new SolidObject(new Point(250, 250), temporaryVertices); 
21
	 
22
	_shadowEngine.addObject(_randomShape); 
23
	 
24
	temporaryVertices = new Vector.<Point>(4); 
25
	 
26
	temporaryVertices[0] = new Point(0, 0); 
27
	temporaryVertices[1] = new Point(0, 60); 
28
	temporaryVertices[2] = new Point(30, 60); 
29
	temporaryVertices[3] = new Point(30, 0); 
30
	 
31
	_shadowEngine.addObject(new SolidObject(new Point(280, 170), temporaryVertices)); 
32
	 
33
	temporaryVertices = new Vector.<Point>(3); 
34
	 
35
	temporaryVertices[0] = new Point(30, 0); 
36
	temporaryVertices[1] = new Point(0, 40); 
37
	temporaryVertices[2] = new Point(60, 40); 
38
	 
39
	_shadowEngine.addObject(new SolidObject(new Point(450, 320), temporaryVertices)); 
40
	 
41
	_shadowEngine.addObject(new RegularPolygon(new Point(400, 150), 5, { size: 30 } )); 
42
	 
43
	addEventListener(Event.ENTER_FRAME, engineLoop); 
44
} 
45
 
46
private function engineLoop(e:Event):void 
47
{ 
48
	_shadowEngine.updateEngine(); 
49
	 
50
	// Rotating a shape 5 degrees every frame 
51
	_randomShape.applyVerticesRotation(5 * Math.PI / 180); 
52
}

And here's our result!

Check out the result!


Step 34: Adding Textures or Another Image to Your SolidObject Class

So I heard you are getting sick of the half-transparent red shapes in our engine. That's serious. What about making it better by adding any kind of image you want? In this example, I will use one of the great texture packs made by Georges Grondin, which are free to use by anyone. The texture I'm using is available in the Texture.swc file.

In order to draw any image we want, we must use what is currently being drawn in the object's drawing area as a mask. To do that, let's create two other properties, another function and modify a few functions to make it work. In the SolidObject class:

1
 
2
protected var _image:Sprite; 
3
 
4
protected var _imageMask:Sprite; 
5
 
6
private function initializeDrawingArea():void 
7
{ 
8
	_drawingArea = new Sprite(); 
9
	 
10
	_image = new Sprite(); 
11
	 
12
	_imageMask = new Sprite(); 
13
	 
14
	_image.mask = _imageMask; 
15
	 
16
	_drawingArea.addChild(_image); 
17
} 
18
 
19
public function draw():void 
20
{ 
21
	_imageMask.graphics.clear(); 
22
	_imageMask.graphics.beginFill(0xFF0000, 0.5); 
23
	 
24
	_imageMask.graphics.moveTo(_vertices[0].x + _x, _vertices[0].y + _y); 
25
	 
26
	_iterator = 1; 
27
	 
28
	while (_iterator < _numberOfVertices) 
29
	{ 
30
		_imageMask.graphics.lineTo(_vertices[_iterator].x + _x, _vertices[_iterator].y + _y); 
31
		 
32
		_iterator++; 
33
	} 
34
	 
35
	_imageMask.graphics.lineTo(_vertices[0].x + _x, _vertices[0].y + _y); 
36
	 
37
	_imageMask.graphics.endFill(); 
38
} 
39
 
40
public function setImage(image:Sprite):void 
41
{ 
42
	if (_drawingArea.contains(_image)) 
43
		_drawingArea.removeChild(_image); 
44
	 
45
	_image = image; 
46
	 
47
	_image.x = _x; 
48
	_image.y = _y; 
49
	 
50
	_image.mask = _imageMask; 
51
	 
52
	_drawingArea.addChild(_image); 
53
} 
54
 
55
public function set x(value:Number):void 
56
{ 
57
	_AABB.x -= _x; 
58
	 
59
	_x = value; 
60
	 
61
	_AABB.x += _x; 
62
	 
63
	_image.x = _x; 
64
} 
65
 
66
public function set y(value:Number):void 
67
{ 
68
	_AABB.y -= _y; 
69
	 
70
	_y = value; 
71
	 
72
	_AABB.y += _y; 
73
	 
74
	_image.y = _y; 
75
}

Let's add a piece of code to set the image of a shape in the Main class and remove our rotating code:

1
 
2
private function init(e:Event):void  
3
{ 
4
	_shadowEngine = new ShadowEngine(640, 480, 0x000000, 0.7, true); 
5
	 
6
	addChild(_shadowEngine.drawingArea); 
7
	 
8
	_shadowEngine.addLight(new Light(new Point(0, 0), 0xFF0000, 200, 1, 0)); 
9
	_shadowEngine.addLight(new Light(new Point(300, 200), 0x00FFFF, 300, 1, 0)); 
10
	 
11
	var temporaryVertices:Vector.<Point> = new Vector.<Point>(5); 
12
	temporaryVertices[0] = new Point(0, 0); 
13
	temporaryVertices[1] = new Point(0, 40); 
14
	temporaryVertices[2] = new Point(30, 50); 
15
	temporaryVertices[3] = new Point(60, 25); 
16
	temporaryVertices[4] = new Point(15, 0); 
17
	 
18
	_randomShape = new SolidObject(new Point(250, 250), temporaryVertices); 
19
	 
20
	_randomShape.setImage(new DemoImage()); 
21
	 
22
	_shadowEngine.addObject(_randomShape); 
23
	 
24
	temporaryVertices = new Vector.<Point>(4); 
25
	 
26
	temporaryVertices[0] = new Point(0, 0); 
27
	temporaryVertices[1] = new Point(0, 60); 
28
	temporaryVertices[2] = new Point(30, 60); 
29
	temporaryVertices[3] = new Point(30, 0); 
30
	 
31
	_shadowEngine.addObject(new SolidObject(new Point(280, 170), temporaryVertices)); 
32
	 
33
	temporaryVertices = new Vector.<Point>(3); 
34
	 
35
	temporaryVertices[0] = new Point(30, 0); 
36
	temporaryVertices[1] = new Point(0, 40); 
37
	temporaryVertices[2] = new Point(60, 40); 
38
	 
39
	_shadowEngine.addObject(new SolidObject(new Point(450, 320), temporaryVertices)); 
40
	 
41
	_shadowEngine.addObject(new RegularPolygon(new Point(400, 150), 5, { size: 30 } )); 
42
	 
43
	addEventListener(Event.ENTER_FRAME, engineLoop); 
44
} 
45
 
46
private function engineLoop(e:Event):void 
47
{ 
48
	_shadowEngine.updateEngine(); 
49
}

(The DemoImage is from Texture.swc.)

After hitting compile, this is our result:


We can see that our texture works, but the default image for the other shapes doesn't. What could be wrong? Let's fix it in the next step.


Step 35: Fixing our Solid Objects' Image

In the previous step, we noticed a problem after adding custom images to a shape: the others lost their default image. What's wrong? Let's take a look at this part of code from our SolidObject class:

1
 
2
private function initializeDrawingArea():void 
3
{ 
4
	_drawingArea = new Sprite(); 
5
	 
6
	_image = new Sprite(); 
7
	 
8
	_imageMask = new Sprite(); 
9
	 
10
	_image.mask = _imageMask; 
11
	 
12
	_drawingArea.addChild(_image); 
13
} 
14
 
15
public function draw():void 
16
{ 
17
	_imageMask.graphics.clear(); 
18
	_imageMask.graphics.beginFill(0xFF0000, 0.5); 
19
	 
20
	_imageMask.graphics.moveTo(_vertices[0].x + _x, _vertices[0].y + _y); 
21
	 
22
	_iterator = 1; 
23
	 
24
	while (_iterator < _numberOfVertices) 
25
	{ 
26
		_imageMask.graphics.lineTo(_vertices[_iterator].x + _x, _vertices[_iterator].y + _y); 
27
		 
28
		_iterator++; 
29
	} 
30
	 
31
	_imageMask.graphics.lineTo(_vertices[0].x + _x, _vertices[0].y + _y); 
32
	 
33
	_imageMask.graphics.endFill(); 
34
}

Did you notice that we are only drawing on our _imageMask property? In order to have the default image, we will also need to change a bit of code to set a default image. Let's do it:

1
 
2
private function createDefaultImage():void 
3
{ 
4
	_image.graphics.clear(); 
5
	_image.graphics.beginFill(0xFF0000, 0.5); 
6
	 
7
	_image.graphics.moveTo(_vertices[0].x + _x, _vertices[0].y + _y); 
8
	 
9
	_iterator = 1; 
10
	 
11
	while (_iterator < _numberOfVertices) 
12
	{ 
13
		_image.graphics.lineTo(_vertices[_iterator].x + _x, _vertices[_iterator].y + _y); 
14
		 
15
		_iterator++; 
16
	} 
17
	 
18
	_image.graphics.lineTo(_vertices[0].x + _x, _vertices[0].y + _y); 
19
	 
20
	_image.graphics.endFill(); 
21
} 
22
 
23
private function initializeDrawingArea():void 
24
{ 
25
	_drawingArea = new Sprite(); 
26
	 
27
	_image = new Sprite(); 
28
	 
29
	_imageMask = new Sprite(); 
30
	 
31
	_image.mask = _imageMask; 
32
	 
33
	_drawingArea.addChild(_image); 
34
	 
35
	createDefaultImage(); 
36
}

The createDefaultImage() function is just a modified version of draw(). It runs only once and creates the default image. If we set another image, the default one will be lost and the new image will be added, and so everything will be working again. Let's hit compile and see what we get:


Success! We can now use custom images in our engine.


Step 36: Making an Object Move With the Mouse

If you would like to have a moving object so you can play with its shadows, let's add a very simple code to make an object follow the mouse's position! In the Main class:

1
 
2
private function engineLoop(e:Event):void 
3
{ 
4
	_randomShape.x = stage.mouseX; 
5
	_randomShape.y = stage.mouseY; 
6
	 
7
	_shadowEngine.updateEngine(); 
8
}

This is the result:

Check out the result!


Conclusion

If you are reading this, congratulations. You have just created your very own Dynamic Shadows engine, and can now use it freely for any project you want! That was a tough task, and I hope you have learned a lot from this. Feel free to post anything you make with this engine in the comments, and don't forget to put a link so that everyone can play with it! Thank you for reading this tutorial.

Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.