Mixin: ABM.util

Defined in: src/util.coffee
Included in: ABM.Util

Overview

ABM.util contains the general utilities for the project.

Note: Within util @ referrs to ABM.util, not the global name space as above.

Alias: u is an alias for ABM.util within the agentscript module (not outside)

 u.clearContext(context) is equivalent to
 ABM.util.clearContext(context)

Extended with ABM.util.array.

Method Summary

Method Details

~ (void) error(string)

Shortcut for throwing an error. Good for debugging:

error("wtf? foo=#{foo}") if fooProblem

~ (void) isObject(object)

~ (void) isArray(object)

~ (void) isFunction(object)

~ (void) isString(object)

~ (void) isNumber(object)

~ (void) isInteger(object)

~ (void) isBoolean(object)

~ (void) randomSeed(seed = 123456)

Replace Math.random with a simple seedable generator. See StackOverflow.

~ (void) randomInt(minmax = 2, max = null)

Return random int in [0, max) or [min, max).

~ (void) randomFloat(minmax = 1, max = null)

Return float in [0, max) or [min, max) or [-r / 2, r / 2).

~ (void) randomNormal(mean = 0.0, standardDeviation = 1.0)

Return float Gaussian normal with given mean, std deviation.

~ (void) randomCentered(r)

~ (void) onceEvery(number = 100)

~ (void) log10(number)

Return log number where base is 10, base, e respectively.

Note: ln: (n) -> Math.log number .. i.e. JS's log is log base e.

~ (void) log2(number)

~ (void) logN(number, base)

~ (void) mod(number, moduloOf)

Return true modulo, % is remainder, not mod.

~ (void) wrap(number, min, max)

Return number to be between min, max via modulo.

~ (void) clamp(number, min, max)

Return number to be between min, max via clamping with min/max.

~ (void) sign(number)

Return sign of a number as +/- 1.

~ (void) isLittleEndian()

Return little/big endian-ness of hardware.

See Mozilla pixel manipulation article.

~ (void) degreesToRadians(degrees)

Convert between degrees and radians. We/Math package use radians.

~ (void) radiansToDegrees(radians)

~ (void) substractRadians(radians1, radians2)

Return angle in (-pi, pi] that added to rad2 = rad1.

See NetLogo's subtract-headings for explanation.

~ (void) ownKeys(object)

Return object's own key or variable values.

~ (void) ownVariableKeys(object)

~ (void) ownValues(object)

~ (void) merge(first, second)

Returns a new hash that merges two hashes. Second object overrides first.

Shallow. So does not deal with nested hashes.

~ (void) addUp(first, second)

Adds up integers set as hash elements

Shallow, and needs only integers.

~ (void) indexHash(array)

Turns an array, into a hash with the array values as keys, and numbers as values. So ["first", "second"] -> {"first": 1, "second": 2}

Usefull for settings.

~ (void) deIndexHash(hash)

Transforms an index hash, created with the function above, back into a correctly sorted array.

~ (void) angle(point1, point2, patches)

Return angle in [-pi, pi] radians from point1 to point2 See: Math.atan2.

~ (void) angleEuclidian(point1, point2)

Euclidian radians toward.

~ (void) angleTorus(point1, point2, patches)

Return the angle from x1, y1 to x2, y2 on torus using shortest reflection.

~ (void) inCone(heading, cone, radius, point1, point2, patches)

Return true if point2 is in cone radians around heading radians from point1.x, point2.x and within distance radius from point1.x, point2.x. I.e. is point2 in cone/heading/radius from point1?

~ (void) inConeEuclidian(heading, cone, radius, point1, point2)

inCone for euclidian distance.

~ (void) inConeTorus(heading, cone, radius, point1, point2, patches)

Return true if point2 is in cone radians around heading radians from point1.x, point2.x and within distance radius from point1.x, point2.x considering all torus reflections.

~ (void) distance(point1, point2, patches, options = {})

Return the distance between point1 and 2.

Not to be used directly. Run from agent or patch instead.

~ (void) distanceEuclidian(point1, point2)

Return the Euclidean distance between point1 and 2.

~ (void) distanceTorus(point1, point2, patches)

Return the torus distance between two points point1 (A) and point2 (B):

dx = |point2.x - point1.x|
dy = |point2.y - point1.y|
d = sqrt(min(dx, W - dx)^2 + min(dy, H - dy)^2)

Torus note: ABMs often use a Torus topology where the right and left edges fold to meet, and similarly for the top/bottom.

For points, this is easily handled with the mod function .. insuring the point is within the rectangle modulo W & H.

The relationship between points is more difficult. The relationship between A and B must also include the towards-reflections around A, thus 4 points.

     |               |
     |      W        |
-----+---------------+-----
 B1  |           B   |
     |               |  H
     |               |
     |  A            |
-----+---------------+-----
 B3  |           B2  |
     |               |

~ (void) distanceMaxDimension(point1, point2)

Return the Max Dimension distance between point1 and 2.

Max dimension only looks for distance along the X and Y axis, and returns the biggest distance of the two.

~ (void) distanceMaxDimensionTorus(point1, point2, patches)

Return the Max Dimension distance between point1 and 2.

Max dimension only looks for distance along the X and Y axis, and returns the biggest distance of the two.

~ (void) torus4Points(point1, point2, width, height)

Return 4 torus point reflections of point2 around point1.

~ (void) closestTorusPoint(point1, point2, width, height)

Return closest of 4 torus points from point1 to 2.

~ (void) torusReflect(point1, point2, width, height)

Used in torus4Points.

~ (void) importImage(name, call = function() {})

Import an image, executing (async) optional function call(image) on completion.

~ (void) xhrLoadFile(name, method = "GET", type = "text", call = function() {})

Use XMLHttpRequest to fetch data of several types. Data Types: text, arraybuffer, blob, json, document, See specification.

Method is "GET" or "POST". f is function to call onload, default to no-op.

~ (void) filesLoaded(files = @fileIndex)

Return true if all files are loaded.

~ (void) waitOnFiles(call, files = @fileIndex)

Wait for files to be loaded before executing callback call.

~ (void) waitOn(done, call)

Wait for function done() to return true before calling callback call.

~ (void) cloneImage(image)

Make a copy of an image.

Note: new image will have the naturalWidth/Height of input image. Should be sync.

~ (void) imageToData(image, call, arrayType = Uint8ClampedArray)

Create a data array from an image's imageData image may be a canvas.

The function call = call(imageData, rgbIndex) -> number.

~ (void) imageRowsToData(image, rowsPerSlice, call, arrayType = Uint8ClampedArray)

~ (void) imageSliceToContext(image, sx, sy, sw, sh, context)

~ (void) pixelByte(n)

~ (void) createCanvas(width, height)

Create a new canvas of given width/height.

~ (void) createContext(width, height, contextType = "2d")

As above, but returing the context object.

Note: context.canvas is the canvas for the context, and can be use as an image.

~ (void) createLayer(div, width, height, z, context = "2d")

Return a "layer" 2D/3D rendering context within the specified HTML <div>, with the given width/height positioned absolutely at top/left within the div, and with the z-index of z.

The z level gives us the capability of buildng a "stack" of coordinated canvases.

~ (void) insertLayer(div, element, w, h, z)

~ (void) setContextSmoothing(context, smoothing)

~ (void) setIdentity(context)

Install identity transform. Call context.restore() to revert to previous transform.

~ (void) clearContext(context)

Clear the 2D/3D layer to be transparent.

Note: this discussion.

~ (void) fillContext(context, color)

Fill the 2D/3D layer with the given color.

~ (void) contextDrawText(context, string, x, y, color = u.color.black, setIdentity = true)

Draw string of the given color at the xy location, in context pixel coordinates. Use setIdentity .. reset if a transform is being used by caller.

~ (void) contextTextParams(context, font, align = "center", baseline = "middle")

Set the element text align and baseline drawing parameters

  • font is a HTML/CSS string like: "9px sans-serif"
  • align is left right center start end
  • baseline is top hanging middle alphabetic ideographic bottom

See reference for details.

~ (void) elementTextParams(element, font, align = "center", baseline = "middle")

~ (void) contextToDataUrl(context)

Convert a canvas to an image, executing fcn f on completion. Generally can skip callback but see stackoverflow

Note: uses toDataURL thus possible cross origin problems.

Fix: use context.canvas for programatic imaging.

~ (void) contextToDataUrlImage(context, call)

~ (void) contextToImageData(context)

Convert a context to an imageData object.

~ (void) drawCenteredImage(context, image, radians, x, y, dx, dy)

Draw an image centered at x, y w/ image size dx, dy. See this tutorial.

~ (void) copyContext(context)

Duplicate a context's image. Returns the new context, use context.canvas for canvas.

~ (void) resizeContext(context, width, height, scale = false)

Resize a context/canvas and preserve data.

~ (void) linearInterpolate(low, high, scale)

Return a linear interpolation between low and high. Scale is in [0 - 1], and the result is in [low, high].

~ (void) identityFunction(object)

Return argument unchanged; for primitive arrays or objs sorted by reference.

~ (void) propertyFunction(property)

Return a function that returns an object's property. Property in function closure.

~ (void) propertySortFunction(property)

Return a function that returns an object's property. Property in function closure.

~ (void) typedToJS(typedArray)

Return a JS array given a TypedArray.

To create TypedArray from JS array: new Uint8Array(js array) etc.

    Quickly fuzzy find classes, mixins, methods, file:

    Control the navigation frame:

    You can focus and blur the search input: