Cabal Common Library Doc Functions

From Elite Wiki
Revision as of 11:40, 6 May 2011 by Svengali (talk | contribs)

Overview

This is the main class for the helper library with its members. Scripts can instantiate a copy, e.g.

this.myHelper = new Cabal_Common();


Properties

internalVersion

Number. Property to give OXPs a chance to check the required lib min. version easily. This number will be raised with every release.

var a = this.myHelper.internalVersion;

a -> 3

Methods

baseChange()

baseChange: function(n, to, from )

Changes the base of n.

Parameters:

n
Number. To be changed.
to
Number. Base which should be used to convert to. Usually 2,10 or 16.
from
Number. Optional. Base from which should be converted. Usually 2,10 or 16.

Returns:

str
String. Base changed.
var a = this.myHelper.baseChange(10, 16); // convert decimal 10 to hex

var b = this.myHelper.baseChange(0xA, 2); // convert hex 0xA (10) to binary
var c = this.myHelper.baseChange('a', 2, 16); // alternative convert hex 0xA to binary
a -> 'a', b -> '1010', c -> '1010'

Author: Dr.J R Stockton.


msbPos()

msbPos: function( n )

Returns position of most significant bit of n.

Paramaters:

n
Number. To be evaluated.

Returns:

n
Number. The position of the most significant bit or 0 (zero).
var a = this.myHelper.msbPos(25);

a -> 5

Author: Dr.J R Stockton.


nBitsUsed()

nBitsUsed: function( n )

Returns number of bits set in n. If n<0 a bitwise NOT will be applied before execution.

Parameters:

n
Number. To be evaluated.

Returns:

e
Number. The counted number of bits set to 1.
var a = this.myHelper.nBitsUsed(13);

a -> 3

(New in 1.3).


pseudoRand()

pseudoRand: function( salt, mode )

LCG (Linear congruential generator) pseudo-random number generator with salt (and pepper). Can be used to generate deterministic unique values, e.g. to decide if a specific entity should be spawned.

Parameters:

salt
Number. This is used to generate a pseudo random number.
mode
Boolean. Optional. If specified and true the returned value is integer (Math.floor(n*100)).

Returns:

n
Number.
  • No mode. In range 0...1,
  • mode. In range 0...100.
var test = this.myHelper.pseudoRand(55);

test -> 0.11969016003422439

var test = this.myHelper.pseudoRand(55,true);
test -> 11

Author: Jens Ayrton (Ahruman).


rand()

rand: function( n )

Random number in range 0...n.

Parameters:

n
Number. Maximum value.

Returns:

n
Number. Returns the random Number.
var crc = this.myHelper.rand(35);

crc -> 12

Author: Dr.J R Stockton.


randSpan()

randSpan: function( minN, maxN )

Random number in range minN...maxN.

Paramaters:

minN
Number. Minimum.
maxN
Number. Maximum.

Returns:

n
Number. The newly generated random Number.
var crc = this.myHelper.randSpan(35,88);

crc -> 55

Author: Dr.J R Stockton.


strCompareVersion()

strCompareVersion: function( strA, strB )

Compares version strings (like “2.0.3”) against each other and returns number. It also strips pre/suffixes like “Build” or “Beta”. Subroutine from oxpVersionTest() and oxpVersionTest2Array(), but can also be used directly.

Parameters:

strA
String. Actual version.
strB
String. Version to be compared against.

Returns:

  • 0 - Number. If strA < strB
  • 1 - Number. If strA = strB
  • 2 - Number. If strA > strB
var check = this.myHelper.strCompareVersion("Beta2.1","1.0.7");

check -> 2


strDateFromMinutes()

strDateFromMinutes: function( minutes )

Takes an integer number of minutes and converts it into a string. The returned string has the form 'd' days, 'h' hours and 'm' minutes, accomodating all cases of singular, plural, and 0.

Parameters:

minutes
Number. The time in minutes.

Returns:

timeString
String.
var str = this.myHelper.strDateFromMinutes(56566);

str -> 39 days, 6 hours and 46 minutes
var str = this.myHelper.strDateFromMinutes(-56566);
str -> 39 days, 6 hours and 46 minutes ago

Author: Commander McLane. (New in 1.3).


strDecrypt()

strDecrypt: function( str, pwd )

Decrypts string.

Parameters:

str
String. To be decrypted. Minimum length 6 chars.
pwd
String. Password. Minimum length 4 chars.

Returns:

dec_str
String/Boolean. Decrypted string or false.
var test = this.myHelper.strDecrypt("6053cae17efb01230f4768046cac63","MYPASS");

test -> "Hello world"

Author: Terry Yuen.


strEncrypt()

strEncrypt: function( str, pwd )

Encrypts string.

Parameters:

str
String. To be encrypted. Minimum length 6 chars.
pwd
String. Password. Minimum length 4 chars.

Returns:

enc_str
String/Boolean. Encrypted string or false.
var test = this.myHelper.strEncrypt("Hello world","MYPASS");

test -> "6053cae17efb01230f4768046cac63"

Author: Terry Yuen.


strGetCRC()

strGetCRC: function( str )

Very simple CRC from string and does not create unique checksums. It uses Unicodes, but limits every char via &0xff and the output via &0x3fff.

Parameters:

str
String. Which should be used to create a CRC.

Returns:

crc
Number. The CRC.
var crc = this.myHelper.strGetCRC("Hello");

crc -> 500


strLZ()

strLZ: function( n )

Returns string with a leading zero if n<10.

Parameters:

n
Number. To be evaluated.

Returns:

str
String. With leading zero if necessary.
var a = this.myHelper.strLZ(3);

a -> "03"

Author: Dr.J R Stockton.


strLZZ()

strLZZ: function( n )

Returns string with a leading zeros if n<100. Uses strLZ() as subfunction.

Parameters:

n
Number. To be evaluated.

Returns:

str
String. With leading zeros if necessary.
var a = this.myHelper.strLZZ(3);

a -> "003"

Author: Dr.J R Stockton.


strScreenSubString()

strScreenSubString: function( str, chrs )

Formats the string str into lines of at most chrs characters in length. Subfunction of strScreenString().

Parameters:

str
String. To be used.
chrs
Number. The length.

Returns:

out
String. With specified length.
var scr = this.myHelper.strScreenSubString("Iwantthisandnotthatandforsurenotsuch",16);

scr -> "Iwantthisandnott\nhatandforsurenot\nsuch"


strScreenString()

strScreenString: function( str, mode, chrs )

Splits string in pieces of chrs, with intermediate linebreaks for missionscreens. The method splits the incoming string by spaces and loops over the elements, and tries to fill up the current line until the maximum length (chrs) is reached. If there are still remaining elements the next line will be used. The replacement (mode) is done via regexp and removes the following: ‘\t \r \f \n \v’. If splitting is not possible or a word is longer than chrs, strScreenSubString() will be used.

Parameters:

str
String. To be used.
mode
Boolean. Optional. If mode is false or not specified it replaces special signs like linebreaks with spaces.
chrs
Number. Optional. Length. If not specified default of 70 is used.

Returns:

display
String. With linebreaks.
var scr = this.myHelper.strScreenString("I want this and not that and for sure not such",1,16);

scr -> "I want this and\nnot that and for\nsure not such"


strSplitToPhrases()

strSplitToPhrases: function( str, n )

Splits string into n words phrases.

Parameters:

str
String. To be used.
n
Number. Words.

Returns:

out
Array. Containing Strings with n words per element.
var cleanedArray = this.myHelper.strSplitToPhrases("My cat has a good time",3);

cleanedArray -> "My cat has","cat has a","has a good","a good time"


strToWidth()

strToWidth: function( str, max, chr )

Returns string with specific length based on Oolites font size. If stringwidth > max it is truncated, otherwise filled up with space or specified chr.

Parameters:

str
String. To be used.
max
Number. Maximum width.
chr
String. Char to be used to fill up if stringwidth < max.

Returns:

str
String. With specified width.
var a = this.myHelper.strToWidth("MyveryOwnApproach",3);

a -> "Myvery"


arrDiff()

arrDiff: function( ar1, ar2 )

Returns difference between two arrays.

Parameters:

ar1
Array. First.
ar2
Array. Second.

Returns:

diff
Array. Difference between two arrays.
var testA = ["AA","AB","AC"],testB = ["AB","AC","AD"];

var cleanedArray = this.myHelper.arrDiff(testA,testB);
cleanedArray -> "AA","AD"


arrRemoveByValue()

arrRemoveByValue: function( arr, val )

Removes specific entry from array.

Parameters:

arr
Array. From which things should be removed.
val
Object. Value that has to be removed.

Returns:

arr
Array. The cleaned array.
var testA = ["A","B","C"];

var cleanedArray = this.myHelper.arrRemoveByValue(testA,"B");
cleanedArray -> "A","C"


arrSortByProperty()

arrSortByProperty: function( arr, prop )

Sort array containing objects by specific property.

Parameters:

arr
Array. To be sorted.
prop
String. Propertyname.

Returns:

what
Array. Sorted by specified property.
var objA = [{ID:2,Other:"TestA"},{ID:1,Other:"TestB"}];

var sorted = this.myHelper.arrSortByProperty(objA,"ID");
sorted -> [{ID:1,Other:"TestB"},{ID:2,Other:"TestA"}]


arrUnique()

arrUnique: function( arr )

Removes duplicates from array.

Parameters:

arr
Array. The input array, from which duplicates are to be removed.

Returns:

r
Array. The cleaned array.
var testArray = ["AB","AB","AB","AC","AC","AC"];

var cleanedArray = this.myHelper.arrUnique(testArray);
cleanedArray -> "AB","AC"


oxpVersionTest()

oxpVersionTest: function( who, requires )

Checks required OXPs and versions. The array is expected to contain two elements for each script and version must be null for legacy scripts!

Checking requirements can be a pain as the version property often contains several numbers, such as Oolites own scripts (“1.74.2”), and checking for a minimum version is sometimes necessary. The method does exactly this and returns false if the requirments are not matched and logs where they are not fullfilled. It also strips pre/suffixes like “Build” or “Beta”. To use it you’ll need an array of required OXPs and their versions. This array can hold JS and Legacy worldScripts and the version can be set to null (required for Legacy), false or 0 (integer) to bypass the version test and only perform the check for existance. The method checks for a property ‘deactivated’ in OXPs to determine whether or not they are deactived.

Parameters:

who
String. Actual scriptname. It’s only used to log for which OXP the requirements are not fullfilled.
requires
Array. Holds for every required OXP the scriptname and version. To check only for existance set version to null.

Returns:

Boolean.
  • false - If a requirement is not fullfilled or OXP is deactivated,
  • true - Otherwise.
var requires = ["snoopers","2.0.8","vector","1.5","Cabal_Common_Keyboard","1.0"];

var checked = this.myHelper.oxpVersionTest(this.name,requires);
checked -> true (or false)


oxpVersionTest2Array()

oxpVersionTest2Array: function( who, requires )

Checks required OXPs and versions. The array is expected to contain two elements for each script and version must be null for legacy scripts! See the description for oxpVersionTest() for more details.

Parameters:

who
String. Actual scriptname. It’s only used to log for which OXP the requirements are not fullfilled.
requires
Array. Holds for every required OXP the scriptname and version. To check only for existance set version to null.

Returns:

checked
Array. With values for checked elements of requires.
  • 2 - version is greater,
  • 1 - version is equal,
  • 0 - not installed,
  • -1 - OXP is deactivated,
  • -2 - version is lower.
var requires = ["snoopers","2.0.8","vector","1.5","Cabal_Common_Keyboard","1.0"];

var checked = this.myHelper.oxpVersionTest2Array(this.name,requires);
checked -> 1,-2,1


entModelView()

entModelView: function( which )

Spawns or resets the modelview entity and returns it. Via JS we can set the orientation, position, etc. of the displayed model, but we can’t stop the rotation if spinModel is not explicitely set to false, because it is hardcoded for screen models and the AI of the model itself can’t do it, because AIs are not executed on missionscreens. That’s why we sometimes need a control entity to do the job.

The modelview entity scans for a specific role and if found sets its target and does the “safeScriptActionOnTarget: performTumble” on the missionscreen model. This overrides the hardcoded rotation with the specified settings in shipdata.plist for the model.

The model (for the missionscreen) has to declare

  • role to be scanned via modelview entity - default for the library is ‘cabal_common_model’.
  • max_flight_pitch (usually between 0..0.2)
  • max_flight_roll (usually between 0..0.2)

Parameters:

which
String. Optional. Role to be used for modelview. If not specified defaults to ‘cabal_common_modelview’.

Returns:

mv
Entity. Returns modelview Entity or null.
var a = this.myHelper.entModelView();

a -> [Ship "cabal_common_modelview" position: (8846.43, 8857.51, -2544.76) scanClass: CLASS_NEUTRAL status: STATUS_IN_FLIGHT]


entFaceEntity()

entFaceEntity: function( ent1, ent2 )

This function causes ent1 to be reorientated such that it faces ent2. A common use-case is when spawning stations whose docking tunnel should face another entity, typically the main planet. Reorienting is instantly.

Parameters:

ent1
Entity. To be reoriented.
ent2
Entity. To which ent1 should be oriented.

Returns:

nothing.
var a = player.ship.target;

var b = system.mainPlanet;
this.myHelper.entFaceEntity(a,b);