Contents

Animation

Animations are stored within the AnimationManager as an array of images.

Register animations

To register an animation within the animation manager, use fnRegisterAnimation. fnRegisterAnimation takes three parameters; iAnimationName, iAnimation and iFrameRate. iAnimationName is the name that the animation should be known as in the manager. iAnimation is the array of images that the animation consists of and iFrameRate is the default framerate of the animation.
See meatfactoryanimations.js for example usage.

Play animations

To play an animation, call fnPlayAnimation with the name of the animation to play and a pointer to the entity that wishes to play the animation. fnPlayAnimation also takes a number of extra parameters, such as information if the animation should loop or not. See the reference for more details. Note: The last parameter, iCallback is ignored for looping animations.
See meatfactoryproperties.js for example usage.

Audio

The AudioManager uses the HTML5 audio tag to play sounds in the game.

Load sounds

To load a sound simply call AudioManager.fnLoadSound with a name to identify the sound within the game and the path to the file on the server. The path should not include the file suffix since the manager will search for a file type that is supported by the users browser when loading the file.

    AudioManager.fnLoadSound('jump', 'meatfactory/jump');

Loading sounds is preferably done in a separate script file, before loading the actual game level, to ensure that sounds are loaded before usage.

Play sounds

To play a sound in the game, call AudioManager.fnPlaySound. fnPlaySound takes three parameters; iSoundName, iPosition and iShouldRepeat. To instantly play a sound only the first parameter, iSoundName, is needed.

    AudioManager.fnPlaySound('jump');

To mute or unmute all sounds in the game, use fnSetGlobalMute.

Dynamic Sounds

The second parameter, iPosition, is a reference to a Vector2 and is used if the sound should be a dynamic sound. AudioManager has three fields that it uses to play dynamic sounds; pointOfInterest, innerCircleRadius, outerCircleRadius. See the reference for more details on how to use these.

Repeating Sounds

The third parameter is used to tell the manager whether the sound should loop or not. When playing a repeating sound fnPlaySound will return a handle to the sound that can be used with fnStopRepeatingSound to stop the sound at any time.

    var sound = AudioManager.fnPlaySound('menu', null, true);

    AudioManager.fnStopRepeatingSound(sound);

Note that a sound can be a repeating sound without being dynamic by passing null for iPosition. Warning: repeating sounds uses the HTML5 audio loop attribute will therefore currently not work in Firefox.

Entities

Game Entity

A GameEntity is basically a structure to maintain a set of properties and their corresponding attributes.

Create entities

To create entities, use the editor and create levels.

To create an entity "behind the scenes", i.e. without adding them to the game on creation, simply create a level with the desired entity with the desired properties, attributes and name, and set uncheck its GraphicsProperty's isVisible checkbox and its (if it has one) PhysicsProperty's isPhysicsActive. Then load that level, get the entity using EntityManager.fnGetEntityByName() and simply send a message to it with the type 'setActive' and the content true (boolean) to make it part of the physics simulation. And finally, don't forget to set its attributes.graphicsVisible attribute to true, like so:

	var EntityManager = VENISON.ENTITY.EntityManager;
	var Message = VENISON.MESSAGES.Message;
	var MessageManager = VENISON.MESSAGES.MessageManager;
	var LevelLoader = VENISON.TOOLS.LevelLoader;
	
	
	LevelLoader.fnLoadLevelFromFile('levelContainingMyEntity');
	var myEntity = EntityManager.fnGetEntityByName('nameOfMyEntity');
	MessageManager.fnSendMessage(new Message('setActive', myEntity.id, null, true));
	myEntity.attributes.graphicsVisible = true;

For an example of how to use levels as templates for only a few or a single entity at a time, or to make entities persistant across levels, see the example in meatfactorygamestates.js, in particular, its fnOnEnter method.

Change image of entity

To change the image of an entity, simply repoint its graphicsImage member, like so:

	var newImage = document.createElement('img');
	newImage.src = 'someplace/somepicture';
	entity.graphicsImage = newImage;

EntityManager

Use the EntityManager to get a particular entity (by name or by id) or to remove entities.

Focus

The foci are handled by the FocusManager. It keeps track of which entity has what focus, and notifies entities via messages when they gain or lose focus. There are two different types of foci: input focus and camera focus. There can be up to exactly one entity in the world in possession of input focus, and up to exactly one entity in the world in possession of camera focus. One single entity may possess both input and camera focus, and in such a case it is the only entity in the world with any type of focus.

Switching focus

To give an entity input focus, use the fnSetInputFocusEntityID method.
To give an entity camera focus, use the fnSetCameraFocusEntityID method.
To give an entity both input and camera focus, use the fnSetFocusEntityID convenience method.

When an entity gains or loses input focus, it will receive a Message with the type 'inputFocusGained' or 'inputFocusLost', respectively.
When an entity gains or loses camera focus, it will receive a Message with the type 'cameraFocusGained' or 'cameraFocusLost', respectively.

Game States

The GamesStateManager manages the states of the game. Register states with fnRegisterGameState (see the reference for an example). Set the current state explicitely with fnSetState and allow the current state to handle events with fnHandleEvent.

Global variables

If you need certain variables to be accessible from anywhere in your code, favourably use the global object VENISON.VARS.

Say you configure the game settings in a certain file:

	//Set how long a game should last
	VENISON.VARS.gameDuration = 30000; //milliseconds

When you start the game, you might do something like:

	//Save the starting time of the game
	VENISON.VARS.gameStart = (new Date()).getTime();

Now, in order to determine whether the game has been running long enough already, simply do something like this:

	var now = (new Date()).getTime();
	if (now >= VENISON.VARS.gameStart + VENISON.VARS.gameDuration) {
		//End the game something something...
	}

Graphics

Cameras

Cameras are responsible for drawing entities to a canvas. Create a new Camera by passing the canvas to draw on to the constructor. For the camera to acutally render anything it has to be registered with the GraphicsManager. The camera class also has a helper function for transforming a position in document space into world space, fnTransformDocumentPositionToWorld.

GraphicsManager

The GraphicsManager is used for updating all the cameras and also contains some useful helper functions. Cameras are registered under a certain name with the manager using fnRegisterCameraWithName. To get a camera with a certain name, use fnGetCameraByName.

Picking

The GraphicsManager has some useful functions for selecting entities in the game world. The first one fnGetEntityOnPosition takes a position in world space as an argument and returns the entity on that position. The second one, fnGetEntitiesInRect returns all the entities that are within a rectangle. Below is a snippet of code of how clicking an entity works in the editor.

    var mousePos = gfnGetMousePos(e);
    mousePos = GraphicsManager.fnGetCameraByName('default').fnTransformDocumentPositionToWorld(mousePos);

    var entity = GraphicsManager.fnGetEntityOnPosition(mousePos, true);
    if (entity) {
    	gfnSelectEntity(entity);
    }

HUD

Heads-up-displays utilizes native HTML programatically created through JavaScript.

See the HUDManager reference, the Meat Factory demo HUDs and how they are controlled by the Meat Factory demo game states.

Input

The InputManager keeps track of keyboard events to track the state of all keys.

Three different querys can be made to receive information about a certain key:


The handling of mouse event is very game specific and should be implemented directly via standard HTML/Javascript methods.
Example from FloosePlayerProperty.fnOnAttach() in flooseproperties.js:

	//The player should be able to click anywhere on the game area, which is fully covered by the HUD.
	var clickArea = VENISON.GRAPHICS.HUDManager.fnGetHUDElement();

	clickArea.addEventListener('mousedown', fnMouseDown, false);
	clickArea.addEventListener('mouseup', fnMouseUp, false);
	clickArea.addEventListener('mouseout', fnMouseUp, false);

In the example, fnMouseDown and fnMouseUp are previously defined functions. See the actual file for details.

See also: HUDManager.

Levels

Levels are loaded and unloaded via the LevelLoader. To unload the current level, call fnUnloadCurrentLevel. To load a level, call fnLoadLevelFromFile. Note that the current level is not unloaded when calling fnLoadLevel again, the new entities are simply added after the existing ones.

LevelLoader also has support for copying and pasting entities with the fnCopyEntities, and fnPasteEntities functions.

Here is an example of copying an entity, loading a new level, and then pasting the entity in the new level.

    var player = EntityManager.fnGetEntityByName('player');

    var playerCopy = VENISON.TOOLS.LevelLoader.fnCopyEntities([player], true);

    VENISON.TOOLS.LevelLoader.fnUnloadCurrentLevel();

    VENISON.TOOLS.LevelLoader.fnLoadLevelFromFile(iLevel);

    player = VENISON.TOOLS.LevelLoader.fnPasteEntities(playerCopy)[0];

Messages

Message

The Message class is used for creating messages to communicate with entities. A message contains message type, sender + receiver IDs and message specific contents. The properties of an entity register which messages they want to handle. To actually send a message, use MessageManager.

MessageManager

The MessageManager is responsible for dispatching messages to the correct entity. To send a message use fnSendMessage. The second parameter of fnSendMessage is a delay time, incase the message should be dispatched after a certain amount of time.

Core Messages

It is very simple to create and use a custom type of message since the type of a message is determined only by the string that is passed as the first argument to the constructor of the Message.
There are however a few types that are already in use by the core of the Venison Engine, and one should be careful not to use these types for other purposes, as unwanted behaviour could occur.

The following message types are used by the Venison Engine.

'inputFocusGained'

Sent by the FocusManager to an entity that gained input focus.

	content: no content.

'inputFocusLost'

Sent by the FocusManager to an entity that lost input focus.

	content: no content.

'cameraFocusGained'

Sent by the FocusManager to an entity that gained camera focus.

	content: no content.

'cameraFocusLost'

Sent by the FocusManager to an entity that lost camera focus.

	content: no content.

'setGraphicsLayer'

Received by GraphicsProperty. Used to set the graphics layer.

	content: {Number} The new layer.

'setPosition'

Received by GraphicsProperty and PhysicsProperty. Used to set the position of the entity.

	content.x: {Number} The x coordinate of the new position.
	content.y: {Number} The y coordinate of the new position.

'setRotation'

Received by GraphicsProperty and PhysicsProperty. Used to set the rotation of the entity.

	content: {Number} The rotation in radians.

'setScale'

Received by GraphicsProperty and PhysicsProperty. Used to scale the entity.

	content.x: {Number} The horizontal scale.
	content.y: {Number} The vertical scale.

'applyImpulseAt'

Received by PhysicsProperty. Apply an impulse to the entity at a specific point.

	content.position.x: {Number} The x coordinate of the point in world space on which to apply the impulse.
	content.position.y: {Number} The y coordinate of the point in world space on which to apply the impulse.
	content.impulse.x: {Number} The horizontal component of the impulse in world space.
	content.impulse.y: {Number} The vertical component of the impulse in world space.

'setPhysicsType'

Received by PhysicsProperty. Set the physicsType of the physics entity.

	content: {String} 'dynamic', 'static' or 'kinematic'.

'addPhysicsShapes'

Received by PhysicsProperty. Used to add new physics shapes to the entity.

	content: {Array} An array of shapes.

'setLinearVelocity'

Received by PhysicsProperty. Used to set the linear velocity of the entity.

	content.x: {Number} The horizontal component of the linear velocity, in pixels per second.
	content.y: {Number} The vertical component of the linear velocity, in pixels per second.

'setAngularVelocity'

Received by PhysicsProperty. Used to set the angular velocity of the entity.

	content: {Number} The new angular velocity, in radians per second.

'setAngularDamping'

Received by PhysicsProperty. Used to set the angular damping of the entity.

	content: {Number} The new angular damping. See Box2d documentation for details.

'setLinearDamping'

Received by PhysicsProperty. Used to set the linear damping of the entity.

	content: {Number} The new linear damping. See Box2d documentation for details.

'setCollidesWithForAllShapes'

Received by PhysicsProperty. Set the collidesWith attribute for all physics shapes.

	content: {Array} An array of collision categories (as strings)

'setFixedRotation'

Received by PhysicsProperty. Used to lock or unlock the rotation of the entity.

	content: {Boolean} true to lock the rotation, false to unlock it.

'setActive'

Received by PhysicsProperty. Used to set whether the entity should be physically active or not, that is, whether it should take part of the physics simulation or not.

	content: {Boolean} true means active and involved in physics simulation, false means the opposite.

'physicsOnContactBegin'

Received by TriggerProperty. Sent by the PhysicsManager to notify entities of when a contact has been established.

	content.contactPosition: {VENISON.UTILITIES.Vector2} A vector representing the position of the contact.
	content.collideeID: {Number} The id of the other entity involved in the contact.
	content.contactNormal: {VENISON.UTILITIES.Vector2} A vector representing the contact normal.

'physicsOnContactEnd'

Received by TriggerProperty. Sent by the PhysicsManager to notify entities of when a contact has ended.

	content.contactPosition: {VENISON.UTILITIES.Vector2} A vector representing the position of the contact.
	content.collideeID: {Number} The id of the other entity involved in the contact.
	content.contactNormal: {VENISON.UTILITIES.Vector2} A vector representing the contact normal.

'pauseAnimation'

Received by SimpleAnimationProperty. Used to pause or unpause the animation currently playing for the entity.

	content: {Boolean} true to pause the animation, false to unpause.

Networking

Real-time networking is powered by socket.io which is run by Node.js on the server side. Socket.io uses WebSockets if available in the browser, otherwise it transparently falls back on Flash sockets or different polling methods, in order of performance. A client-side example is available in Floose and a server-side example is available in /venison_misc/serverstuff/webserver.js in the Venison Engine download.

See also:
The NetworkManager reference.

Physics

The PhysicsManager is used for updating the actual physics engine. Physics entities are created via the PhysicsProperty. Several functions exists in the manager to update the physics of an entity.

Ray-casting

To cast a ray in the physics world, use PhysicsManager.fnRayCastOne or PhysicsManager.fnRayCastAll.

Changing physics engine

Due to the adapter implementation of the physics engine, it is quite easy to change which physics engine is used. In order to switch engine all that is needed is to create a new adapter class and implement all the functions in the PhysicsManager to translate between the manager and the physics engine.

Properties

Property

The Property class is the abstract base class for all properties. Properties register which messages they should be notified of with the function fnRegisterToMessages. Messages that the property is listening for are then handled in the function fnHandleMessage. When adding a new property to your game, it has to be registered with the PropertyFactory, in order to be able to create it later.

PropertyFactory

Registering properties is done via the fnRegisterProperty function. To create new properties in the game, use fnCreateProperty. Properties are then attached to entities using their fnAttachProperty function.

Core Properties

The following properties are included in the core distribution of the Venison Engine. To better understand how they are implemented, please see the source code (control-f your way to the properties themselves).

GraphicsProperty

PhysicsProperty

TriggerProperty

ChaseCameraProperty

SimpleAnimationProperty

Templates

Here are a few useful templates for creating various custom classes. Just copy and paste the following code and change as necessary.

Property template

Copy and paste this into your own properties.js file to create a new property. See meatfactoryproperties.js.

    //A template to copy and paste when making a new property
    //Replace 'NameOfTheProperty' with the name of the new property
    PropertyFactory.fnRegisterProperty('NameOfTheProperty', function () {

	    //The attributes connected to this property that will be added to the entity which it is attached to.
	    //If this property does not need any extra attributes, remove this statement.
	    //There can be any number of attribute name/value pairs - extend as needed.
	    this.attributes = {attributeName1: attributeValue1,
	    attributeName2: attributeValue2};
	
	    //@Override
	    //Called when this property has been attached to an entity. mEntity contains a pointer to the entity.
	    this.fnOnAttached = function () {
	
	    }
	    //@Override
	    //Called when the level has been completely loaded
	    this.fnOnLevelLoaded = function () {
	
	    }
	    //@Override
	    //Called just prior to this property being removed from the entity it is attached to
	    this.fnOnRemoved = function() {
	
	    }
	    //@Override
	    //Called once every frame
	    this.fnOnFrame = function () {
	
	    }
	    //@Override
	    //This method is automatically called when this property is attached to an entity. Use it to register which messages this property should be notified of.
	    this.fnRegisterToMessages = function () {
	    //this.entity.fnRegisterForMessage(this,'messageTypeHere');
	    }
	    //@Override
	    //Called when the game entity that this property is attached to receives a message of a type that this property has registered to
	    this.fnHandleMessage = function (iMessage) {
		    /*
		    switch (iMessage.type)
		    {
			    case 'messageTypeHere':
			    // Do stuff here...
			    break;
		    }
		    */
	    }
    });

Games state template

Copy and paste this into your own gamestates.js file to create a new game state. See meatfactorygamestates.js.

	//Template for implementing a new game state
	new
	function () {
		var mName = 'AnotherState';
	
		//Called once when entering this state
		this.fnOnEnter = function () {
			//Do stuff here.
		}
		//Called once when leaving this state
		this.fnOnLeave = function () {
			//Do stuff here.
		}
		//Returns the name of the game state to use next frame
		this.fnOnFrame = function () {
			//Do stuff here.
			return mName;
		}
		//Register this state with the game state manager (no need to change when creating a new state)
		GameStateManager.fnRegisterGameState(this,mName);
	}

Network handler template

Copy and paste this into your own networkhandler.js file to create a new network listener. See floosenetworkhandler.js.

	// This is a template to add a network listener
	(function () {
		VENISON.NETWORK.NetworkManager.fnAddNetworkListener({
			fnMessageReceived: function (iMessage) {
			},
			fnMessageSent: function (iMessage) {
			},
			fnConnectionOpened: function () {
			},
			fnConnectionClosed: function () {
			},
			fnExceptionCaught: function (iException) {
			}
		});
	})();

Utilities

Vector2

The Vector2 class represents a 2D vector. It contains various functions for performing vector operations, such as normalizing vectors and calculating their length.

Transformation

The Transformation class contains information about position, rotation and scale. It also has functions for transforming positions in and out of object space. The function fnLocalToWorld transforms a point from object space to world space. The function fnWorldToLocal transforms a point from world space to object space.

Utility functions

There exist some miscellaneous functions that might be useful in different situations. Check them out in the reference.