LimpetGE Logo

LimpetGE Reference Manual

The LimpetGE reference manual. An attempt to list all the API in the LimpetGE library. However, this does not include the shaders, that has its own section.

Pre-Requisites

The LimpetGE library make use of the glMatrix script, a copy of this is provided with the distribution files. Basic knowledge of what matrix maths does is assumed.

Global Variables

The Camera objectThe Camera object
Global variableValueDescription
Some generic constants
LCANVAS_ID"limpetge_canvas"The HTML ID of the canvas used for WebGL
LMESTIME5Length of time (in seconds) messages should appear for
Shortcuts for ordinals when placing objects
LR90Math.PI / 290 degrees in radians
LR180Math.PI180 degrees in radians
LR270Math.PI * 3 / 2270 degrees in radians
LR360Math.PI * 2360 degrees in radians
When adding entities to structures, the following can be used for controlling textures etc.
LI_FRONT0The identifier for the front of the structure component
LI_BACK1The identifier for the back of the structure component
LI_SIDE2The identifier for the side of the structure component (cylinders) or the first side in polygons.
LI_TOP2The identifier for the top of the block structure component
LI_RIGHT3The identifier for the right of the block structure component
LI_BOTTOM4The identifier for the bottom of the block structure component
LI_LEFT5The identifier for the left of the block structure component
The collision detection methodology to be used for the objects of structures
LSTATIC1Indicator the objects of the structure should use the static collision mechanism
LDYNAMIC2Indicator the objects of the structure should use the dynamic collision mechanism
LNONE0Indicator the objects of the structure should use no collision mechanism
Size of mobile/tablet buttons, where applicable
LBUT_WIDTH50The width of buttons for mobile apps
LBUT_HEIGHT50The height of buttons for mobile apps
Asset download control
LASSET_THREADS5Number of assets to download at a time
LASSET_RETRIES5Number of times to retry failed downloads
lGlThe WebGL context
lCamera
lSceneThe "Scene" object
lSSceneA static object containing the relative directional vector

Audio Classes

This is a rapper around the HTML5 Audio class.

new LAudios(source, number)Create a new audios object
SourceA string representing source of the audio (mp3, wav, etc) Ir can also be a LimpetGE asset.
NumberNumber of instances, or max number of times the sound can be simultaneously played
lAudios.play()Play the sound

new LAudioLoop(source)Create a new audio loop object
SourceA string representing source of the audio (mp3, wav, etc) It can also be a LimpetGE asset for that.
lAudioLoop.play()Plays/un-pauses sound, increasing stack if already playing. The sound will "loop" when it gets to the end.
lAudioLoop.pause()Decreases stack, Pauses/Stops the sound if stack is zero.
lAudioLoop.stop()Pauses the sound and sets the stack to zero.

The lInit() function
This initialises the lGl WebGL context, it also compiles the shaders. Needs to be called more or less first thing in the "onload" function.

The lClear() function
This clears everything except the lGl context. Including all structures.

The lStructureSetup() function
Sets up the structure data, especially assembling the buffers for the shaders. It needs to be called after all static structures are created. It is in fact done automatically when creating a "new Scene" (derived from "LBase"), so it need not be specifically called. It is documented here for legacy.

The LBase class

This class needs to be the "base" for the "Scene" class, or more specifically, the "Scene" class needs to derive this.

All methods and properties follow the LimpetGE naming convention (follows the regex: "_?[lL][A-Z][A-Za-z0-9_]+"), so programmers can put any method/property in the "Scene" class so long as the names do not match that.

Implementing code should look something like....

class Scene extends LBase {
    constructor(args)
    {
        super(args);
    
        // Then for example, 
    
        this.hurt = 0.0;
        this.ambientLight =  vec3.fromValues(0.3, 0.3, 0.3);
        this.directionalLightColor = vec3.fromValues(1.0, 1.0, 1.0);
        this.runme = true;
        this.life = 100;
        this.bescape = false;
        ...
        ...
    
    }

    lLoop: function(delta)
    {
        ....
        ....
    }
    ....
    ....
    ....
}

Initialisation and setting up methods.
new Scene(....)"Scene" will be programmer written class that inherits from "LBase". When this is created it places a reference to the object in the global variable "lScene".
LBase.call(this, args)In constructor of "Scene"
argsA "dictionary" of optional named arguments, consisting of:
args.lDirectionalVectorA "vec3" type giving the source directional of the directional lighting.
args.lCFromA "vec3" coordinates giving the most bottom left back point of the scene.
args.lCToA "vec3" coordinates giving the most top right front point of the scene.
the LCFrom and LCTo arguments should represent two opposing corners of a cube within which the scene needs to be. It is used as the basis of the sparse array for collision detecting, so it does not matter if it is too big.
args.lCSizeThe "size" of the collision array cubes. Should not be smaller than the largest collision detection distance..
args.lCIncrementThe "size" of the ray tracing increment. Should not be smaller than the smallest collision distance.
args.lLControlThe control object for the camera. Defaults to the camera object itself (lCamera).
args.lLDynamicIf set to "true" makes the camera a dynamic object
args.lLDistanceThe spherical size of the camera if a dynamic object.
args.lLAngleThe angle for the camera perspective. Defaults to 45 degrees.
args.lLNearThe near clip plane for the camera. Defaults to 0.1.
args.lLFarThe far clip plane for the camera. Defaults to 2000.
lScene.lInit()An optional virtual method called when "lScene" is created. Not used much as you may as well put things like that in the constructor of the "Scene" class.
lScene.lSwitch()Switch to this scene if multiple ones in use.
LObject placement and processing methods.
lScene.lAddChild(object, position)Adds an object onto the "root" of the object tree.
objectThe "LObject", "LIObject" or "LWObject" instance to add.
positionA "mat4" instance. Where to add it onto the scene.
lScene.lPlace(object, position)This performs an "lAddChild" at the origin, then moves the object to "position" supplied.
objectThe "LObject", "LIObject" or "LWObject" instance to add.
positionA "mat4" instance. Where to move it to once added.
lScene.lSetup()Sets up the scene after all static objects has been added. Especially sets up the "Static Collision" sparse array.
Running the actual game.
lScene.lPos()Processes the positions for all objects in the scene. It does a tree walk of all objects.
lScene.lMessage(message, color)Displays a message for 5 (LMESTIME) seconds.
messageThe message to display.
colorOptional, the font color to display the message. It needs to be a string containing an HTML5 color. Defaults to "red".
lScene.lSetTitle(title)The title to display.
titleThe title to display.
lScene.lMain()This runs the thing. The programmer calls this when the "scene" is set up to run the game.
lScene.lLoop(delta)This is a virtual method on "LBase". It is called on each frame (javascript's requestAnimationFrame).
deltaA float representing the time in seconds (not milliseconds) since the previous iteration.
This needs to return the boolean "true" to continue the game, or "false" to terminate it.
Static objects collision detection methods.
lScene.lCAddStaticArea(from, to, object)Used to add a static area for the "Static Collision Detection" mechanism. This is not normally called by the programmer as the object creation mechanism does this for "normal" objects when using the "collision: LSTATIC" option when creating the structure. However, you can add virtual objects ("LVirtObject" instances) to the static area as well if required".
fromThe bottom left back corner of the "block" to add.
toThe top right front corner of the "block" to add.
objectThe "LVirtObject" object to add.
lScene.lCStaticPointDetect(object, distance)Implements the static collision detection mechanism for the "object". This performs a ray tracing check for the object, using the last time a detection was performed on this object, or the last time "lObject.warp()" was called as a base.
objectThe object to perform the check.
distanceA "block" buffer (not sphere) around the object's point to act as a "buffer" (or "padding").
This returns the object reference of the first thing it has "collided" with, or null if it does not.
lScene.lCAllStaticPointDetect(object, distance, callback)This is similar to "lCStaticPointDetect" except it does not return anything. Instead, it calls the "callback" function, with the object it has collided with as the argument.
objectThe object to perform the check.
distanceA "block" buffer (not sphere) around the object's point to act as a "buffer" (or "padding").
callbackThe callback function to perform if a collision occurs, using the object as the argument to the callback.
lScene.lCStaticPDC(x, y, z, distance)Implements the static collision detection mechanism for any point of coordinates (x, y, z). This does not include ray tracing. This is not normally used by the programmer.
xThe "x" coordinate.
yThe "y" coordinate.
zThe "z" coordinate.
distanceA "block" buffer (not sphere) around the object's point to act as a "buffer" (or "padding").
This returns the object reference of the first thing it has "collided" with, or null if it does not.
lScene.lCAllStaticPDC(x, y, z, distance, callback)As lCAllStaticPoint Detect is to lCStaticPointDetect, this is to lCStaticPDC.
xThe "x" coordinate.
yThe "y" coordinate.
zThe "z" coordinate.
distanceA "block" buffer (not sphere) around the object's point to act as a "buffer" (or "padding").
callbackThe callback function to perform if a collision occurs, using the object as the argument to the callback.
Dynamic objects collision detection methods.
lScene.lCAdd(object)Adds an object to the Dynamic Collision sparse array. Only really (and rarely) used for virtual objects, as normal ones are added automatically when using the "collision: LDYNAMIC" option on the structure definition.
objectThe object to add.
lScene.lCRemove(object)Removes an object from the Dynamic Collision sparse array.
objectThe object to remove.
lScene.lCMove(object)Moves the location of an object within the Dynamic Detection sparse array. This is done automatically when "lObject.procpos()" or "lScene.lPos()" is called, so the programmer only needs to do this for virtual objects.
objectThe object to move.
lScene.lCDynamicPointDetect(object, distance)Implements the dynamic collision detection mechanism for the "object". This performs a ray tracing check for the object, using the last time a detection was performed on this object, or the last time "lObject.warp()" was called as a base.
objectThe object to perform the check.
distanceA "sphere" buffer (not block) around the object's point to act as a "buffer" (or "padding").
This returns the object reference of the first thing it has "collided" with, or null if it does not.
lScene.lCAllDynamicPointDetect(object, distance, callback)This is similar to "lCDynamicPointDetect" except it does not return anything. Instead, it calls the "callback" function, with the object it has collided with as the argument.
objectThe object to perform the check.
distanceA "sphere" buffer (not block) around the object's point to act as a "buffer" (or "padding").
callbackThe callback function to perform if a collision occurs, using the object as the argument to the callback.
lScene.lCDynamicPDC(x, y, z, distance)Implements the dynamic collision detection mechanism for any point of coordinates (x, y, z). This does not include ray tracing. This is not normally used by the programmer.
xThe "x" coordinate.
yThe "y" coordinate.
zThe "z" coordinate.
distanceA "sphere" buffer (not block) around the object's point to act as a "buffer" (or "padding").
This returns the object reference of the first thing it has "collided" with, or null if it does not.
lScene.lCAllDynamicPDC(x, y, z, distance, callback)As lCAllDynamicPoint Detect is to lCDynamicPointDetect, this is to lCDynamicPDC.
xThe "x" coordinate.
yThe "y" coordinate.
zThe "z" coordinate.
distanceA "sphere" buffer (not block) around the object's point to act as a "buffer" (or "padding").
callbackThe callback function to perform if a collision occurs, using the object as the argument to the callback.
Combined objects collision detection methods.
lScene.lPointDetect(object, distance)Combines "lCStaticPointDetect" and "lCDynamicPointDetect". This performs a ray tracing check for the object, using the last time a detection was performed on this object, or the last time "lObject.warp()" was called as a base.
objectThe object to perform the check.
distanceA buffer (block for static, sphere for dynamic) around the object's point to act as a "buffer" (or "padding").
This returns the object reference of the first thing it has "collided" with, or null if it does not.
lScene.lCAllPointDetect(object, distance, callback)Combines "lCAllStaticPointDetect" and "lCAllDynamicPointDetect". This performs a ray tracing check for the object, using the last time a detection was performed on this object, or the last time "lObject.warp()" was called as a base.
objectThe object to perform the check.
distanceA buffer (block for static, sphere for dynamic) around the object's point to act as a "buffer" (or "padding").
callbackThe callback function to perform if a collision occurs, using the object as the argument to the callback.
Object properties.
lChildrenAn array that contains the top-level objects. Not normally directly accessed by the programmer.
lRestartThis property contains a function. It is not a method as it is not (and should not be) on the "LBase" or "Scene" class definitions. It executes when the game finishes. The function takes no arguments.
lCameraThe camera object. The current camera object is also referenced in the global "lCamera" variable, however this copy is useful if there is more than one "scene" around.
lDefaultMessageThe message to display if no other is. The default for this is "Press ? for help".

LCamera class

An instance of the "LCamera" class is created when the "Scene" (derived from "LBase") class is, and a copy of the reference is placed in the global "lCamera" variable - as well as the property "lCamera" on the scene object.

When created, it uses the same "args" argument as when the "LBase" constructor is called.

This also uses a similar interface to the "LObject"/"LWObject"/"LIObject"/"LVirtObject" classes, so the camera can be used as a base for collision detection, and/or included in the Dynamic sparse array.

Regarding movements and rotations. There are in effect two modes...

In "3D mode" movement can occur any which way, like a spaceship. Methods for this are:

In "Flat mode" movement occurs as though travelling over a floor, with a definite "up". Methods for this are:

The other movement and rotational methods can be used for either.

Setting up and general operation.
new LCamera(args)This creates a new camera object, it also places a reference of that in the global variable "lCamera". This is called automatically when a new "Scene" is created, using the same "args" object passed to the "LBase" constructor.
argsA "dictionary" of optional named arguments, consisting of:
args.lLControlThe control object for the camera. Defaults to the camera object itself (lCamera).
args.lLDynamicIf set to "true" makes the camera a dynamic object
args.lLDistanceThe spherical size of the camera if a dynamic object.
args.lLAngleThe angle for the camera perspective. Defaults to 45 degrees.
args.lLNearThe near clip plane for the camera. Defaults to 0.1.
args.lLFarThe far clip plane for the camera. Defaults to 2000.
lCamera.save()Saves key parts of the camera's properties in an object and returns it.
Returns an object containing saved data..
lCamera.restore(saved)Restores what was saved in the "save" method.
savedWhat was returned in the "save" method.
lCamera.setperspective(args)Sets the perspective of the camera. Called in the constructor using the "args" supplied there..
argsIf "args" is omitted the previous one when this function was called is used. A "dictionary" of optional named arguments. This consists of:
args.lLAngleThe angle for the camera perspective. Defaults to 45 degrees.
args.lLNearThe near clip plane for the camera. Defaults to 0.1.
args.lLFarThe far clip plane for the camera. Defaults to 2000.
lCamera.getview()Retrieves the current view (mat4) of the camera, used in shaders. Combines the position of the camera combined with the projection.
Returns the transformation matrix to use (mat4).
Rotation methods
lCamera.rotate(rx, ry, rz)Rotates the camera around the x, y and z axis (in that order) by the supplied amount, relative to the camera's direction.
rxThe amount in radians to rotate around the x axis.
ryThe amount in radians to rotate around the y axis.
rzThe amount in radians to rotate around the z axis.
lCamera.rotateFlat(rx, ry)Rotates the camera around the origin's y axis by the appropriate amount, then "up" or "down" around the camera's X axis, which is parallel to the scene's X and Z axis - ensuring it does not go "up" or "down" by more than 90 degrees.
rxThe amount in radians to rotate around the camera's x axis.
ryThe amount in radians to rotate around the scene's y axis.
lCamera.rotateFlatHere(rx, ry)Rotates the camera around the origin's y axis by an absolute amount from the origin, then "up" or "down" around the camera's X axis again by an absolute amount again from the origin, which is parallel to the scene's X and Z axis - ensuring it does not go "up" or "down" by more than 90 degrees.
lCamera.rotateFlat(rx, ry) === lCamera.rotate(lCamera.rx + rx, lCamera.ry + ry)
rxThe amount in radians to rotate around the camera's x axis.
ryThe amount in radians to rotate around the scene's y axis.
Movement methods
lCamera.move(x, y, z)Moves the camera along its x, y and z axis
xThe amount to move it along its x axis.
yThe amount to move it along its y axis.
zThe amount to move it along its z axis.
lCamera.moveFlat(x, y, z)Moves the camera along the origin's X and Z axis accordingly, taking into consideration the camera's Y rotation, and up or down by the Y amount.
xThe camera's flat x coordinate to move by.
yThe amount to move "up" or "down" along the Y axis.
zThe camera's flat z coordinate to move by.
lCamera.moveHere(x, y, z)Moves the camera to the scenes (x, y, z) coordinates
xThe x coordinate to move to.
yThe y coordinate to move to.
zThe z coordinate to move to.
lCamera.moveAbs(x, y, z)Moves the camera by the scenes (x, y, z) coordinates.
lCamera.moveAbs(x, y, z) === lCamera.moveHere(lCamera.x + x, lCamera.y + y, lCamera.z + z)
xThe scene's x coordinate to move by.
yThe scene's y coordinate to move by.
zThe scene's z coordinate to move by.
Collision detection methods
lCamera.warp()Updates the "base" coordinates used for ray tracing to current position for collision detecting.
lCamera.getSceneXYZ()Retrieves the current coordinates as a "vec4" - with "w" equal to 1.0. Internally used, same as [lCamera.x, lCamera.y, lCamera.z, 1.0].
Returns the current coordinates as a "vec4": [x, y, z, 1.0].
lCamera.getDistance(x, y, z, distance)Retrieves the distance fom the supplied (x, y, z) coordinates, and subtracts the distance supplied. Internally used, the programmer will have little use for this.
xThe x coordinate to reference.
yThe y coordinate to reference.
zThe z coordinate to reference.
distanceThe distance to subtract.
Returns the appropriate distance, which is less than or equal zero for a collision.
lCamera.procpos()Needs to be called after moving if the camera is in the dynamic sparse array. No harm in calling it anyway if not.
Object properties that may be relevant.
xThe current X coordinates
yThe current Y coordinates
zThe current Z coordinates
rxThe current rotational amount in radians around the camera's X axis. Only applicable if "rotateFlat" methodology is used
ryThe current rotational amount in radians around the scene's Y axis. Only applicable if "rotateFlat" methodology is used
oxThe current X coordinate base for ray tracing in collision detection
oyThe current Y coordinate base for ray tracing in collision detection
ozThe current Z coordinate base for ray tracing in collision detection
quatThe "quat" of the rotational direction of the camera inverted.
positionThe scene position and direction of the camera as represented by a transformation matrix (mat4). This is inverted.
projectionThe projection transformation matrix ("mat4").
currviewThe current transformation matrix of the camera incorporating the projection ("mat4").
keyA unique object number for the camera.
distanceThe distance used for dynamic collision detection, set using the "lLDistance" property of the "args" argument when initialised. Can be updated if necessary.
ignoreUpdateable boolean property. The needs to be set to "true" if the camera is in the dynamic collision sparse array and needs to be ignored for the detection, then set back to "false" afterwards.
controlThe "control" object as defined by the "args.lLControl" setting when the object was created.

LGroupDef class

A "group" is an object with no structure. That is it can have children, dynamic or static collision functionality and so on, but nothing gets drawn by it itself.

This class is the structure base for the object. Implemented as....

var grpdef = new LGroupDef();
var game_object = new LObject(grpdef, whatever);
new GroupDef(args)This creates a new static group.
argsA Javascript object containing some optional named parameters.
args.collision
Controls if this object is to be included in a Collision Sparse Array. It can be one of the following:
  • LNONE - The default. Not included in any collision detection sparse array.
  • LSTATIC - Included in the static collision detection sparse array.
  • LDYNAMIC - Included in the dynamic collision detection sparse array.
args.cornersUsed for "static" collision type groups only. An array of two "vec3" type arrays representing the bottom left back and top right front corners of a block.
Eg: [[-1, -2, -3], [4, 5, 6]]
args.distanceThe spherical distance of the collision realm of the object if included in the dynamic collision detection sparse array.

LStructureDef class

The structure definition is where the "building" of objects occurs. Building happens by creating a number of "shapes" using one of the add....(...) methods.

these being placed at a certain place by using a "position" argument.

The "add...(....)" method takes a single argument which is a Javascript object consisting of named variables. Ones that are not applicable to that particular shape are ignored.

These named arguments are consistent throughout the methods, so I will document those in a separate section,

Constructor
new LStructureDef(shader, args)This creates a new structure definition.
shaderThe LimetGE shader javascript object to use from the "shader library".
argsA javascript object containing some optional named arguments.
args.collision
This is:
  • LNONE - The default. Not included in any collision detection sparse array.
  • LSTATIC - Included in the static collision detection sparse array.
  • LDYNAMIC - Included in the dynamic collision detection sparse array.
args.distanceThe spherical distance (radius) to use when included in the dynamic collision detection sparse array.
args.***SHADER_ARGS***The args argument is passed to the shader's doInitBuffer method, so those would depend on the appropriate shader, however, the following is reasonably consistent.
args.textureThe URL of a jpg/png/gif whatever file that represents a collage of the texture to use in the structure. It can also be a LimpetGE asset of that. See separate section for that
args.rawtextureThe loaded texture rather than the URL.
args.colorA "vec4" array representing the color. This is [Red, Green, Blue, Alpha] values, each being a float between 0 and 1.0
args.colorsAn array of "vec4" arrays representing the colors used. Each entry is [Red, Green, Blue, Alpha] values, each being a float between 0 and 1.0
Adding shapes (see separate section of documentation as well)
structure.addBlock(args)Adds a block. Valid named arguments are: "position", "texturecontrol", "texturecontrols", "hold", "corners", "collsize", "depth", "size", "insideout".
structure.addBlockPatch(args)Adds a block patch, or a rectangle. Valid named arguments are:
structure.addCylinder(args)Adds a cylinder. Valid named arguments are: "position", "texturecontrol", "texturecontrols", "hold", "corners", "collsize", "depth", "radius", "segments, "insideout"".
structure.addSphere(args)Adds a sphere. Valid named arguments are: "position", "texturecontrol", "corners", "collsize", "radius".
structure.addPolygon(args)Adds a polygon block. Valid named arguments are: "position", "texturecontrol", "texturecontrols", "hold", "corners", "collsize", "depth", "coords", "insideout".
structure.addTriangle(args)Adds a triangle block. Valid named arguments are: "position", "texturecontrol", "texturecontrols", "hold", "corners", "collsize", "depth", "coords", "insideout".
structure.addWTriangle(args)Adds a "wonky triangle" block. Valid named arguments are: "position", "texturecontrol", "texturecontrols", "corners", "collsize", "depth", "coords", "insideout".
structure.addTrianglePatch(args)Adds a triangle patch (2D). Valid named arguments are: "position", "texturecontrol", "hold", "corners", "collsize", "coords".
structure.addBezierPatch(args)Adds a Bezier patch (2D). Valid named arguments are: "position", "texturecontrol", "corners", "collsize", "coords", "xsegments", "ysegments".
structure.addBezierBlock(args)Adds a triangle block. Valid named arguments are: "position", "texturecontrol", "texturecontrols", "hold", "corners", "collsize", "coords", "depth", "xsegments", "ysegments", "insideout".
structure.addImport(args)Adds an imported asset, covered in separate section. Valid named arguments are: "position", "texturecontrol", "corners", "collsize".
Corner methods.
structure.useCorners(corners, args)Adds "corners" for inclusion in the static collision detection sparse array, if applicable.
cornersAn array (or object) consisting of a list of "vec3" coordinates of corners. Usually two items (bottom-left-back and top-right-front), but can be more. The "corners" it uses is the smallest cartesian block to fit all points.
argsA javascript object consisting of a number of named optional arguments.
args.collsizeThe cubical size the corner block to divided into if object is to be rotated in a non cartesian manor.
args.cornersIf this is supplied it overrides the first argument of the method.
structure.consolidateCorners()When called, it consolidates all corner "blocks" defined in the structure up to that point into one big block (that fits all).

As for the "add....(....)" method arguments:

positionA transformation matrix ("mat4") that is applied to the component after creation, to place it in the appropriate place of the object. This defaults to the identity transformation matrix (no effect).
texturecontrolsA list of "LTextureControl" instances, (or "LTextureColor" instances) that define which texture (or color) to use in the collage of textures (provided to the shader) in the "args.texture" (args.colors) argument supplied in the constructor. This defaults to using the entire texture. There is a separate section for this as well.
texturecontrolMutually exclusive to the "texturecontrols" argument. This is a single instance of the above, and it is applied to all textures of the component.
hold
A list of "LI_***" global variables for which parts NOT to draw. This can be:
  • LI_FRONT - Do not draw front
  • LI_BACK - Do not draw back
  • LI_SIDE - Do not draw side (of the cylinder)
  • LI_SIDE + number - Do not draw "nth" side of a polygon (starting at 0)
  • LI_TOP - Do not draw top of blocks
  • LI_LEFT - Do not draw left of blocks
  • LI_BOTTOM - Do not draw bottom of blocks
  • LI_RIGHT - Do not draw right of blocks
corners
This only applies to those that are added to the static collision detection sparse array.
  • If this is omitted then calculate the smallest corner block that is possible.
  • If this is "null" then do not include corners from this component.
  • If this is a list of "vec3" coordinates then use that. Note - the "args.position" matrix are not applied to this in this case.
collsizeThe size of "sub-blocks" the corner blocks is to be divided into in the event of non-cartesian rotation
sizeOnly applies to the "addBlock" method. This is a "vec3" coordinate. The block created has the opposite corners of that coordinates, and the negative of that.
coordsSome kind of array of [x, y] coordinates or [x, y, z] coordinates (depending on the specific method) to build the component. Described below.
depthIf this is defined it is the depth of the component along the "z" axis. The exception to that is the "addBezierBlock" method, where it is the depth that is perpendicular to the bezier "curved plane(s)".
radiusFor "round" type components this is the radius of the circular part.
segmentsFor "round" type components this is the number of polygons that go around the circumference. Defaults to something sensible
xsegmentsFor Bezier shapes, the number of polygons that go "left to right" in the matrix provided.
ysegmentsFor Bezier shapes, the number of polygons that go "top to bottom" in the matrix provided.
insideoutLimpetGE employs "gl.CULL_FACE, and normally components cannot be seen from the "inside". If this is set to the boolean "true" then this reverses that and it can only be seen from the inside, not the outside. Originally written for panoramas.

The specific "add....(...)" methods. These can be moved/rotated using the "position" argument to an appropriate place on the structure.

The "CULL_FACE" option in the OpenGL routines are enabled, so things cannot be seen from "inside" blocks, or from the "back" for patches. Also there are problems if you do not go "anti-clockwise" when you should.

addBlockThis creates a "block", the size being a "vec3" coordinate of one opposite corner, the negative of this being the other. Therefore the "size" provided is in fact half the size of the componenet created.
addBlockPatchThis creates a "rectangle", where "z" value is zero, viewable looking from positive to negative down the "z" axis. The size being a [x, y] coordinate of one opposite corner, the negative of this being the other.
addCylinderThis creates a cylinder with the Z axis being the center line. The radius is that, and the depth is how far positive and negative it goes along the "z" axis (so the depth provided is half the componenet depth).
addPolygonThis creates a polygon block. The coordinates are an array of [x, y] coordinate arrays, going in a counter-clockwise direction. The origin should be inside the polygon. The "depth" is how far the block extends positive and negative along the z axis. Only convex polygons are supported.
addTriangleThis behaves like a three sided polygon bock, except does it more efficiently.
addWTriangleAdd "Wonky" triangle block. Like "addTriangle" (add triangle block) except here the each entry in the coordinates array (in coords) also have a "Z" coordinate, and the triangle block is "sheared" along the Z axis accordingly.
addTrianglePatchLike "addTriangle" (add triangle block) except in 2D. There is no "depth" and the triangle is placed where z = 0. Also this cannot be seen from the "back" (negative Z value to positive).
addBezierPatchA "Bezier" patch, a "curved 2D component". Adds a bezier patch, although defined as "2D", it is more like a "corrugated/warped sheet", though like the "triangle patch" it cannot be seen from behind. The "coords" entry is in fact a matrix of "vec3" type coordinates that create the points to create the Bezier Sheet. This is described below.
addBezierBlockA "Bezier" block, a "curved 3D component". Uses same method as "addBezierPatch", but to create a central virtual "sheet". A block is crated by taking the "depth" value, and creating two more sheets in front of and behind, by the depth, perpendicular to the sheet. The "sides" of the block are then "filled in".
The Bezier Coordinates

This will not go into the mathematics and generic mechanics of Bezier patches, there is enough resource on the web for that, it just goes into the LimpetGE implementation of this.

The coordinates entry looks something like the following:

    coords: [
        [[0.2,   0.0, 0.0], [0.2,    0.15, 0.0], [0.15,  0.3,  0.0], [0.0,   0.3,  0.0]],
        [[0.2, -0.15, 0.0], [0.2,    0.0, -0.3], [0.0,   0.3, -0.3], [-0.15, 0.3,  0.0]],
        [[0.15, -0.3, 0.0], [0.0,   -0.3, -0.5], [-0.2,  0.0, -0.5], [-0.2,  0.15, 0.0]],
        [[0.0,  -0.3, 0.0], [-0.15, -0.3,  0.0], [-0.2, -0.15, 0.0], [-0.2,  0.0,  0.0]],
    ],

In other words, an array of "lines", and each line being an array of "coordinates", each coordinate being a "vec3" array.

The system works by:

  1. Creating "Bezier lines" using the coordinates on each of the "lines arrays"
  2. Creating a number of points, as reresented by the "xsegments" argument (defaults to 16) along these "lines" equi-distant from each other, (creating a default total of 17 lines).
  3. This number of "perpendicular-ish" "sub bezier lines" are creating using the appropriate "nth" point of each point.
  4. These "sub-lines" are then also divided by a number represented by the "ysegments" argument (again, defaults to 16), creating a number of "sub-points" along each line, (creating a default total of 289 "sub points": 17 x 17).
  5. These "sub points" form a "mesh" that is used as a base to create the polygons for the Bezier patch.

The upshot of which, is that the four "corners" of the above array are (usually) the only coordinates points that the sheets actually "map" to (or is "pinned" to). The rest of the coordinates control the "curvature" of the sheet.

For "Bezier Blocks", regarding the "hold" and "textureconrols" parameters, the LI_TOP, LI_LEFT, LI_BOTTOM and LI_RIGHT controls represent the appropriate "side" as represented by the above array.

The "coords" array must have a width of at least two, and a height of at least two. Also there needs to be the same number of coordinates in each line. With those two criteria in mind,   the array can be of any size.


LObject class

The main object class for the game. An object is a distinct "thing" in the scene, that can move independently of other objects if dynamic.

This class was not designed to be "derived", however, there is nothing stopping the programmer from doing so. Care should be taken that there is no "name" clashes as the normal "LimpetGE" naming conventions do not apply to the methods and properties.

Regarding movements and rotations. There are in effect two modes...

In "3D mode" movement can occur any which way, like a spaceship. Methods for this are:

In "Flat mode" movement occurs as though travelling over a floor, with a definite "up". Methods for this are:

The other movement and rotational methods can be used for either.

Setting up and general operation.
new LObject(structure, control)This creates a new game object. An object is based on a "structure definition".
structureThe structure to base the object on. This can be an instance of "LStructureDef" or "LGroupDef".
controlAn arbitary javascript object that is passed to the shader "draw" routine, and can be used in collision detection.
obj.save()Saves key parts of the game object's properties in an object and returns it.
Returns a javascript object containing saved data.
obj.restore(saved)Restores what was saved in the "save" method.
savedWhat was returned in the "save" method.
obj.mkvisible(visible)makes the game object, and it's children, visible or invisible.
visibleA boolean value, "true" makes the game object and it's children visible, "false" invisible..
Rotation methods
obj.rotate(rx, ry, rz)Rotates the game object around the x, y and z axis (in that order) by the supplied amount, relative to the game object's direction.
rxThe amount in radians to rotate around the x axis.
ryThe amount in radians to rotate around the y axis.
rzThe amount in radians to rotate around the z axis.
obj.rotateFlat(rx, ry)Rotates the game object around the origin's y axis by the appropriate amount, then "up" or "down" around the game object's X axis, which is parallel to the scene's X and Z axis - ensuring it does not go "up" or "down" by more than 90 degrees.
rxThe amount in radians to rotate around the game object's x axis.
ryThe amount in radians to rotate around the scene's y axis.
obj.rotateFlatHere(rx, ry)Rotates the game object around the origin's y axis by an absolute amount from the origin, then "up" or "down" around the game object's X axis again by an absolute amount again from the origin, which is parallel to the scene's X and Z axis - ensuring it does not go "up" or "down" by more than 90 degrees.
obj.rotateFlat(rx, ry) === obj.rotate(obj.rx + rx, obj.ry + ry)
rxThe amount in radians to rotate around the game object's x axis.
ryThe amount in radians to rotate around the scene's y axis.
Movement methods
obj.move(x, y, z)Moves the game object along its x, y and z axis
xThe amount to move it along its x axis.
yThe amount to move it along its y axis.
zThe amount to move it along its z axis.
obj.moveFlat(x, y, z)Moves the game object along the origin's X and Z axis accordingly, taking into consideration the game object's Y rotation, and up or down by the Y amount.
xThe game object's flat x coordinate to move by.
yThe amount to move "up" or "down" along the Y axis.
zThe game object's flat z coordinate to move by.
obj.moveHere(x, y, z)Moves the game object to the scenes (x, y, z) coordinates
xThe x coordinate to move to.
yThe y coordinate to move to.
zThe z coordinate to move to.
obj.moveAbs(x, y, z)Moves the game object by the scenes (x, y, z) coordinates.
xThe scene's x coordinate to move by.
yThe scene's y coordinate to move by.
zThe scene's z coordinate to move by.
obj.moveMat(matrix)Moves the game object by the supplied transformation matrix.
matrixThe transformation matrix.
Collision detection methods
obj.warp()Sets the base position for ray tracing collision detection to the current position. The "obj.procpos()" method should be called before calling this.
obj.setOld(argobj)Sets the base position for ray tracing collision detection to the current position of the argument object
argobjA game object to set "this" base position to.
obj.getSceneXYZ()Retrieves the current scene coordinates s a "vec4" - with "w" equal to 1.0.
Returns the current coordinates as a "vec4": [x, y, z, 1.0].
obj.procpos()Processes the current position of the object and it's children, updating the dynamic collision detection sparse array if neccessary. This needs to be called after movement(s)/rotation(s) and before the next render.
obj.setDistance(distance)Sets the spherical "distance" or "radius" for dynamic game objects.
distanceThe appropriate distance.
obj.getDistance(x, y, z, distance)Retrieves the distance from the supplied (x, y, z) coordinates, and subtracts the distance supplied. Internally used, the programmer will have little use for this.
xThe x coordinate to reference.
yThe y coordinate to reference.
zThe z coordinate to reference.
distanceThe distance to subtract.
Returns the appropriate distance, which is less than or equal zero for a collision.
Game object tree methods
obj.addChild(object, position)Adds an object onto the current game object.
objectThe "LObject" instance to add.
positionA "mat4" instance. Where to add it relative to the current object.
obj.remove()Removes this game object from the parent. Note - this is the "child" in "obj.addChild(...) or lScene.lAddChild(...).
Object properties
childrenAn array that contains the child game objects. Not normally directly accessed by the programmer.
xThe current relative X coordinates
yThe current relative Y coordinates
zThe current relative Z coordinates
rxThe current rotational amount in radians around the game object's initial X axis. Only applicable if "rotateFlat" methodology is used
ryThe current rotational amount in radians around the scene's initial Y axis. Only applicable if "rotateFlat" methodology is used
oxThe current scene X coordinate base for ray tracing in collision detection
oyThe current scene Y coordinate base for ray tracing in collision detection
ozThe current scene Z coordinate base for ray tracing in collision detection
quatThe "quat" of the rotational direction of the game object.
basepositionThe scene position of, in effect, the parent game object (or the identity matrix if top level). This is a transformation matrix (mat4).
initialPositionThe transformation matrix used in the "addChild(....)" method when adding this game object (mat4).
positionThe current scene position and direction of the game object as a transformation matrix (mat4).
keyA unique object number for the game object.
distanceThe distance used for dynamic collision detection. Can be updated if necessary.
ignoreUpdatable boolean property. The needs to be set to "true" if the game object is in the dynamic collision sparse array and needs to be ignored for the detection, then set back to "false" afterwards.
isvisibleNon updatable boolean property, use the "mkvisible(...)" method to do that. Is "true" if the object is visible, "false" otherwise.
controlThe "control" object used when the object was created.

LWObject class

This supports the same methods and properties as the LObject class. In fact, it is derived from it. However it is optimised so that it can only be added at the top level on lScene using the "lPlace(....)" method. Things will go wrong if an LWObject instance is used otherwise.


LIObject class

This supports most of the same methods and properties as the LObject class. In fact, it is derived from it. However when "mkvisible" or "procpos" is called on the parent (or ancestor), the functionality is not automatically called here. Therefore those functions need to be called independantly on these objects.


LVirtObject class

The Virtual Object. This has no structure, and is not included in the game object tree. However it can be used for extra dynamic collision functionality. For instance, it is useful to determine if something can go somewhere without moving it, or to create a temporary area to see if something, possibly specific, moves there.

These can "move", and perform ray tracing, like a normal object if required.

new LVirtObject(conrol, x, y, z, distance)Create a new virtual object
controlA javascript object that is assigned to the control property
xThe scene X coordinate where to create this
yThe scene Y coordinate where to create this
zThe scene Z coordinate where to create this
distanceThe spherical distance if to be included in the dynamic collision detection sparse array.
vobj.save()Create an object containing data if the state of this object is to be "saved".
Returns the data in a crated object
vobj.restore(saved)Restores what has been "saved".
savedWhat was returned when executing the "vobj.save()" function.
vobj.setPosition(x, y, z)Sets the position to a particular point, also the base position for ray tracing .
xThe scene X coordinate where to go to
yThe scene Y coordinate where to go to
zThe scene Z coordinate where to go to
vobj.getDistance(x, y, z, distance)Retrieves the distance from the supplied (x, y, z) coordinates, and subtracts the distance supplied. Internally used, the programmer will have little use for this.
xThe x coordinate to reference.
yThe y coordinate to reference.
zThe z coordinate to reference.
distanceThe distance to subtract.
Returns the appropriate distance, which is less than or equal zero for a collision.
vobj.mkvisible(visible)Makes the game object, and it's children, visible or invisible.
visibleA boolean value, "true" makes the game object visible, "false" invisible..
vobj.copy(obj)Copies the scene coordinates and the ray tracing base position of the game object ("LObject", "LWObject" or "LVirtObject" type).
vobj.getSceneXYZ()Retrieves the current scene coordinates s a "vec4" - with "w" equal to 1.0.
Returns the current coordinates as a "vec4": [x, y, z, 1.0].
vobj.warp()Updates the "base" coordinates used for ray tracing to current position for collision detecting.
vobj.relative(obj, x, y, z)Sets the position to a particular point relative to another object. Applies the same relative positioning on the ray tracing base point.
objThe object to apply this to. Can be a "LObject", "LWObject" or "LVirtObject" type.
xThe value to increment the X coordinate value
yThe value to increment the Y coordinate value
zThe value to increment the Z coordinate value
vobj.moveHere(x, y, z)Moves the virtual object to the scenes (x, y, z) coordinates
xThe x coordinate to move to.
yThe y coordinate to move to.
zThe z coordinate to move to.
obj.moveAbs(x, y, z)Moves the virtual object by the scenes (x, y, z) coordinates.
xThe scene's x coordinate to move by.
yThe scene's y coordinate to move by.
zThe scene's z coordinate to move by.

LStaticGroup class

This class instances can be included in the game object tree, but themselves have no structures, or game objects, associated with them. They simply pass respective calls to their children.

new LStaticGroup()This creates a new static group.
stat.addChild(object, position)Adds an object onto the current game object.
objectThe "LObject" instance to add.
positionA "mat4" instance. Where to add it relative to the current object.
stat.remove()Removes this game object from the parent. Note - this is the "child" in "obj.addChild(...) or lScene.lAddChild(...).

LGroup class

This is a quick method for creating a "one off" group object.

var grp = new LGroup(args, control)
is the same as
var grp  = new LObject(new LGroupDef(args), control);

This then can be included in the game object tree, collision sparse arrays or anything else as per a normal "LObject" type.


LStructure class

This is a quick method for creating a "one off" structures and the associated object.

var obj = new LStructure(shader, args, control)
is the same as
var obj  = new LObject(new LStructureDef(shader, args), control);

Components can be used by using the "structure" property of the object:

obj.structure.addBlock({........});
...

This then can be included in the game object tree, collision sparse arrays or anything else as per a normal "LObject" type.


Textures

Textures are a bit peculiar in LimpetGE in that they need to be handled in shaders a lot more than other aspects. Also, if flat colors are used, these are represented as "mini textures", being a series of one-pixel points, each one a color to be used in the objects.

The overall mechanism that is employed is:

Note: When defining colors in LimpetGE, they are defined using a "vec4" type array, representing red, green, blue and alpha values respectively. Each value is a float between 0.0 and 1.0.

The texture loading is handled in the "doInitBuffer" function of the specific shader (documented in the Shader section), which is programmer controlled. The following applies to the "standard" shaders supplied, and is recommended to follow this convention as much as possible.

In the "args" argument object of the "LStructureDef" constructor, - (an instance of this is passed as an argument to doInitBuffer) one of the following is passed:

When creating collages of images, it is recommended the collage image is "re-scaled" so that the pixel height and width is equal to (2 ^ n) - where "n" is any integer. In other words, the width is one of 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024 etc pixels wide, and ditto for pixels high. They need not be the same, just 2 ^ n.

When the components of the structure are created, using the "add....(...)" methods, a "texturecontrols" argument is supplied, which can contain:

LTextureControl class

This defines which part of a texture image collage to use for a specific surface. An instance itself does not contain any texture/image data itself, just the geometric "slice" or "rectangle" of the texture to use for the surface.

new LTextureControl(image_size, base, size)Create a new texture control instance. The argument are a series of two element arrays, each representing width and height. These can be of any scale, they need not be pixels, centimeters or anything else (but can be). Also width and height may not need to be the same unit. The units are just used to determine which "bit" of the collage to use for each surface.
image_sizeThe size of the collage image as a array of [width, height] in any scale.
baseThe bottom left hand corner of the collage to use for the surface in the same scale.
sizeThe size of the collage section to use for the surface in the same scale.

The "scale" of these units can be anything so long as consistence. For example, if a collage is two images high, and four images wide, then:

The above can be used regardless how wide or high the images in the collage are (as long as they are all the same).

Images can be "inverted" or "reflected" by using negative values in the "size" argument, in this case, the "base" should be moved to reflect this, so for the above example for the same "section" to be reflected as though looking at a reflection on water (reflected vertically)...

There is a global constant - LTEXCTL_STATIC - that represents a LTextureControl instance that includes the entire collage - equivalent to "LTextureControl([1, 1], [0, 0], [1, 1])".

To apply images, or parts of the collage, the "texturecontrols" array is used. Which ones to which surfaces the "LI_*" keys are used for keyed objects, (or those particular positions in an array), for instance, imagine a dice face collage that looks like:

Dice

Note - the dimensions of the image has been padded out to obey the "2 ^ n" criteria for images.

Then - this is applied by...

var dice_struct = new LStructureDef(shaderSimple, {texture: "dice_faces.png"});

var die_one   = new LTextureControl([4, 2], [0, 1], [1, 1]);
var die_two   = new LTextureControl([4, 2], [1, 1], [1, 1]);
var die_three = new LTextureControl([4, 2], [2, 1], [1, 1]);
var die_four  = new LTextureControl([4, 2], [0, 0], [1, 1]);
var die_five  = new LTextureControl([4, 2], [1, 0], [1, 1]);
var die_six   = new LTextureControl([4, 2], [2, 0], [1, 1]);

var dice_cube = new LObject(dice_struct, null);

dice_cube.addBlock({size: [1, 1, 1],
                    texturecontrols: lIndArray([
                            [LI_FRONT,  die_one],
                            [LI_BACK,   die_six],
                            [LI_TOP,    die_three],
                            [LI_LEFT,   die_two],
                            [LI_BOTTOM, die_four],
                            [LI_RIGHT,  die_five],
                    ]));

Note: The "lIndArray" function changes array pairs into a key-value entry in an object. See later this document.

Alternatively, if you look at the "LI_*" values, the "txturecontrol arguments could be written..

dice_cube.addBlock({size: [1, 1, 1],
                    texturecontrols: [die_one, die_six, die_two, die_three, die_five, die_four]);

Any entries omitted, or are "null", the surface will not be drawn. Same as including it in the "hold" argument.

The texture will automatically stretch or shrink in each dimension independently so that it is the smallest size that will cover all parts of the surface.

Colors on surfaces

At time of writing, LimpetGE does not include "static colors" for individual surfaces, however, this can be done using textures designed for the purpose, and some helper functions exist to do this.

If the "color" argument is supplied with the appropriage color values in the LStructureDef constructor (using standard "shader" routines), then a texture image is created one pixel wide and one pixel high consisting of that color. Omitting "texturecontrols" argument from the "add....(...)" componenet creation methods means that all the image is used for all surfaces, in effect coloring the object that color.

Should the "colors" argument is supplied, with an array of colors, then an image 1 pixel high, and the array length pixels wide, is created and used as a texture.

When componenets are then created using the "add....(...)" methods, the "texturecontrols" array or list can pass LTextureControl objects returned using the "lTextureColor" function. This consists of:

ctrl = ltextureColor(total_colors, color_number)Retrieve the color to draw on surface
total_colorsTotal colors in the "colors" array
numberThe index of the color to use (starting from 0)
Returns the "LTextureControl" instance that will extract the appropriate color

For example:

var colors = [
                [1.0, 0.0, 0.0, 1.0],   // red
                [0.0, 1.0, 0.0, 1.0],   // green 
                [0.0, 0.0, 1.0, 1.0],   // blue
                [0.5, 0.5, 0.0, 1.0],   // yellow
                [0.5, 0.0, 0.5, 1.0],   // purple
                [0.0, 0.5, 0.5, 1.0],   // turquoise
                [0.0, 0.0, 0.0, 1.0],   // Black
                [0.0, 0.0, 0.0, 1.0]    // Black
            ];
// Above padded out with "black" so it is 2 ^ n in length

var red       = lTextureColor(8, 0);
var green     = lTextureColor(8, 1);
var blue      = lTextureColor(8, 2);
var yellow    = lTextureColor(8, 3);
var purple    = lTextureColor(8, 4);
var turquoise = lTextureColor(8, 5);

var cube_struct = new LStructureDef(shaderSimple, {colors: colors});

var cube = new LObject(cube_struct, null);

cube.addBlock(size: [1, 1, 1],
              texturecontrols: [red, green, blue, yellow, purple, turquoise]);

Applying textures to surfaces

Imagine the object center is at the origin, and the texture image is at a positive value along the Z axis, perpendicular to it, but the right way up regarding the X and Y axis, then the way the textures are applied is:

addBlockAdding a block, six surfaces:
LI_FRONTApplied as is
LI_BACKRotated 180 degrees around the Y axis
LI_TOPRotated minus 90 degrees around the X axis
LI_RIGHTRotated plus 90 degrees around the Y axis
LI_BOTTOMRotated plus 90 degrees around the X axis
LI_LEFTRotated minus 90 degrees around the Y axis
addBlockPatchAdding a block patch, one surface:
LI_FRONTApplied as is
addCylinderAdding a cylinder block, three surfaces:
LI_FRONTApplied as is
LI_BACKRotated 180 degrees around the Y axis
LI_SIDERotated minus 90 degrees around the X axis, then applied so the sides join at the top (x is zero, y is positive)
addSphereAdding a block patch, one surface:
LI_FRONTApplied as is, the image is stretched to a ratio of width two, height 1. It is then "wrapped around the sphere so that the sides meet at the back, and the top and bottom of the image is "shrunk" so it is a tight fit around the sphere.
addPolygonAdding a polygon block, two plus number of sides surfaces:
LI_FRONTApplied as is
LI_BACKRotated 180 degrees around the Y axis
LI_SIDE + nN being the "nth" side starting from zero. The image is rotated minus 90 degrees around the X axis, then rotated around Z axis to be "parallel" to the side to be applied.
addTriangleAdds a triangle block. As per a three sided polygon block.
addWTriangleAdds a wonky triangle block. As per a three sided polygon block. Care should be taken though, on the sides the images are "sheared".
addTrianglePatchAdding a triangle patch, one surface:
LI_FRONTApplied as is
addBezierPatchAdding a bezier patch, one surface:
LI_FRONTApplied as is, however, "as is" is how the coordinates are presented, rather than by the axis.
addBezierBlockAdding a bezier block, six surfaces, based on how the coordinates are presented, rather than by the axis. Also, unlike wonky tiangles, the sides are not "sheared. It is worth bearing in mind the image is stretched or shrunk so it is a tight fit over the curves, with the corners pinned as such.
LI_FRONTApplied as is.
LI_BACKRotated 180 degrees around the Y axis
LI_TOPRotated minus 90 degrees around the X axis
LI_RIGHTRotated plus 90 degrees around the Y axis
LI_BOTTOMRotated plus 90 degrees around the X axis
LI_LEFTRotated minus 90 degrees around the Y axis

Some helper routines used in textures. Used in shader routines if anywhere.

lLoadTexture(url)Load a texture from a URL and return it
urlThe URL of the appropriate image to load or a LimpetGE asset.
lLoadColor(color)Create a texture containing a one pixel image and return it
colorThe color ("vec4") to use.
lLoadColors(colors, width, height)Create a texture containing a (width * height) pixel image and return it
colorsAn array of "vec4" arrays representing colors. The number of these should equal width multiplied by height.
widthThe width in pixels of the image
heightThe height in pixels of the image. This is usually one, and nothing is achieved by using anything else. The "ltextureColor" helper function assumes this.

LAssets class - LimpetGE assets

Games require various ancillary "assets", or "files" to run. It does not always make sense that these are downloaded asynchronously as required the way a web browser does, or necessarily rely on the cache to stop duplicate downloads. There is a case for pre-downloading these.

In order to achieve this LimpetGE provides the "LAssets" class, which facilitates downloading images, sounds and 3D modelled objects ("XXX.obj" files). It downloads these, stores them in Javascript "Blob" objects, and deploys these where appropriate.

Due to the asynchronous nature of browser downloads, these need to be performed before the game is run, not at the start of it. When download is complete an "event" is run from the class that facilitates starting the actual game. Something like:

// Download assets const g_assets = new Assets({ moo: "sounds/cow.wav", bark: "sounds/dog.wav", meow: "sounds/cat.wav", }); function do_onload() { function inprogress() { document.getElementById("inprogress").innerText = g_assets.succeeded.toString() + " out of " + g_assets.total.toString() + "assets downloaded"; }, function onend() { if(g_assets.succeeded == g_assets.total) { document.getElementById("inprogress").innerText = "All assets downloaded" document.getElementById("playbutton").disabled = false; } else { alert("Not all assets successfully downloaded"); } } g_assets.download({ inprogress: inprogress, onend: onend}); }

For the above, in the HTML file, the body tag would include the attribute: onload="do_onload();" to instigate this. It would also have a "span" or "div" element with an id="inprogress" attribute, and a disabled input button button like: <input type="button" id="playbutton" disabled="disabled" value="Play game" /> used to start the game.

To access the assets themselves, use the "asset.data" property:

sounds.cow = new LAudios(g_assets.moo, 1); sounds.cat = new LAudios(g_assets.meow, 1); sounds.dog = new LAudios(g_assets.bark, 1);

The specification:

new LAssets(assets)The LAssets constructor
assets
A javascript named object, one entry per asset, consisting of:
  • A string being the URL of the asset
  • A javascript object, containing the named arguments:
    • url: A string containing the URL
    • type: The Mime type
asset.download(callbacks)This method starts the downloads. It returns more or less immediately, the downloads occurring asynchronously.
The callbacks fired off by the download process:
  • inprogress: The function called intermittently during the process, once after each download attempt is complete.
  • onend: The function called when all downloads are complete.
Some properties. The programmer should treat these as read only
assets.totalThe total assets to download
assets.completedThe total assets that either have been downloaded, or have failed to download.
assets.succeededThe total assets that either have been downloaded successfully.
assets.dataA javascript object whose named properties contain the respective asset ("Blob") downloaded.

LKey class

The keyboard key control object. This is used internally by the "lInput" object, but can be used outside that if required - but normally is not.

new LKey()Create a new keyboard object
key.func(ind)Set the boolean "val" property to the indicator.
indEither "true" of "false", what to set the "val" property.
key.funcon(ind)Set the boolean "val" property "true" if "ind" is true.
indEither "true" of "false", if "true" sets the "val" property to this
key.funcoff(true)Set the boolean "val" property "false" if "ind" is nt true.
indEither "true" of "false", if "false" sets the "val" property to this
vobj.ison()Return the "val" property..
Returns if the "val" property is "true".

The lInput oject

This behaves like a static class instance. It is used to control keyboard and mouse button input. Functions and methods are:

lInput.register(keycode, function)Register a keycode to perform a function
keycodeThe integer keycode of a key pressed
function
The function to perform when the key is pressed or released. An example:
lInput.register(83, function(ind) {picth_down = ind;});
This is the most efficient way of receiving inputs, though not the most intuitive.
lInput.press(keycode)Register a keycode that updates a "LKey" instance "val" property.
keycodeThe integer keycode of a key pressed
Returns a "LKey" instance, whose "val" property is "true" when the key is pressed, and "false" when released.
lInput.onoff(keycode_on, keycode_off)Register keycodes to turn a "LKey instance "val" properrty to "true" or "false"
keycode_onThe integer keycode of a key pressed that switches the "val" property to "true"
keycode_offThe integer keycode of a key pressed that switches the "val" property to "true"
Returns a "LKey" instance, whose "val" property is switched to "true" or "false"
lInput.usekeys()Tells the browser to use the events/functionality in this static object.
lInput.keydown(event)Used internally, is initiated by the browser "keydown" event
eventThe browser key event object.
lInput.keyup(event)Used internally, is initiated by the browser "keyup" event
eventThe browser key event object.
lInput.dodown(event)Used internally, is initiated by the browser "mousedown" or "touchdown" event
eventThe browser mouse/touch event object.
lInput.doup(event)Used internally, is initiated by the browser "mouseup", "touchup" or "touchcancel" event
eventThe browser mouse/touch event object.

The global variables "lDoDown" and "lDoUp" are used internally for this functionality. The "HTML" section of the documentation goes further into this.


LPRNG and LPRNGD class

A predictable random number generator. Designed for speed rather than "true randomness", should be good nough for games.

new LPRNG(seed)Create a new PRNG object
seedThe seed for the generator, needs to be a (large) integer. The same seed will produce the same sequence.
prng.next(scope)retrieve the next number, which will be an integer greater than or equal zerto and less than the argument.
prng.next(scope)retrieve the next number, which will be an integer greater than or equal zerto and less than the argument.
Returns the next integer is returned: 0 >= returned value > scope.

The LPRNGD class is identical with the exception it returns a floating point number, not an integer.

.

Transformation Matrix Helper Functions

Various helper functions exist to assist transformation matrices, primarily to place objects.

lFromXYZ(x, y, z)Generate a translation transformation matrix
xThe amount to translate along the X axis.
yThe amount to translate along the Y axis.
zThe amount to translate along the Z axis.
Returns the appropriate tranlation transformation matrix ("mat4").
lFromXYZR(x, y, z, ry)Generate a translation, then rotate it around the Y axis in situ to produce a transformation matrix
xThe amount to translate along the X axis.
yThe amount to translate along the Y axis.
zThe amount to translate along the Z axis.
ryThe amount in radians to rotate around the Y axis in situ.
Returns the appropriate transformation matrix ("mat4").
lFromXYZPYR(x, y, z, rx, ry, rz)Generate a translation, then rotate it around Z, X and Y axis in situ (in that order) to produce a transformation matrix
xThe amount to translate along the X axis.
yThe amount to translate along the Y axis.
zThe amount to translate along the Z axis.
rxThe amount in radians to rotate around the X axis in situ (pitch).
ryThe amount in radians to rotate around the Y axis in situ (yaw).
rzThe amount in radians to rotate around the Z axis in situ (roll).
Returns the appropriate transformation matrix ("mat4").

HTML Helper Functions

A number of functions exist to assist creating the HTML containing page for the game...

lElement(tag, attributes, text, children)Create HTML element entries, a helper to javascript's "createElement" function.
tagThe HTML tag, such as "div", "tr", "td" etc
attributesIf a javascript object, the attributes of the element. If a string it is the "class" attribute. Set to null for not or omit applicable
textContaining text of the element. Set to null , "" or omit for not applicable
childrenAn array of elements (HTML Element types). Set to null or omit of not applicable
Returns an appropriate HTML Element object.
lAddButton(orient, vpos, hpos, label, keycode)Creates a button on the canvas.
orient
One of the following:
  • tl : Top left
  • tc : Top center
  • tr : Top right
  • bl : Bottom left
  • bc : Bottom center
  • br : Bottom right
It is where on the canvas the button is anchored.
vpos
How many buttons "in" vertically this button is positioned
hpos
How many buttons "in" horizontally this button is positioned
label
The label of the botton
keycode
The key code to emulate if button is pressed

For use if the "lElelemnt(...)" function it is best to show by example.

    document.getElementById("container").appendChild(
        lElement("table", null, null, [
            lElement("tr", null, null, [
                lElement("td", null, "Top left"),
                lElement("td"),
                lElement("td", null, "Top right"),
            ]),
            lElement("tr", null, null, [
                lElement("td", {colspan: "3"})
            ]),
            lElement("tr", null, null, [
                lElement("td", null, "Bottom left"),
                lElement("td"),
                lElement("td", null, "Bottom right"),
            ]),
        ])
    ]);

Will produce the same DOM section if the folowing HTML was used (whitespaces added for readability):

<table>
    <tr><td>Top left   </td> <td></td> <td>Top right   </td></tr>
    <tr><td colspan="3"></td>                               </tr>
    <tr><td>Bottom left</td> <td></td> <td>Bottom right</td></tr>
</table>

Other Miscellaneous Functions

lGetPosition(x, y, z, matrix)Apply transformation matrix on the coordinates [x, y, z].
xThe original X value
yThe original Y value
zThe original Z value
matrixThe transformation matrix ("mat4") to apply
Returns a "vec3" style array representing the transformed point.
lAntiClock(a, b, c)See if three 2D points are anti-clockwise.
aFirst point, in the form of an array [x, y]
bFirst point, in the form of an array [x, y]
cFirst point, in the form of an array [x, y]
Returns boolean "true" if the points are anti-clockwise, "false" othereise..
lCoalesce(a, b)Returns b if a is null or undefined.
aPrime value or object
bSubstiture value or object
Returns the prime if not null or undefined, otherwise returns the substitute
lIndArray(arraypairs)Returns an object based on an array of arrai pairs. First item being the key, second the value.
arraypairsAn array of array pairs, eg: [[LI_TOP: tx1]. [LI_BOTTOM, tx2]]
Returns an appropriate object obj: obj[LI_TOP] = tx1, obj[LI_BOTTOM] = tx2
lInitShaderPorgram(vertexSource, fragmentSource)Compiles the shader and returns the program. Used internally by the shader routines.
vertexSourceThe vertex source
fragmentSourceThe fragment source
Returns the compiled program

Donate