SCAR CDE Manual
Divi 3.25

Note: This manual will soon be deprecated, a new manual is being developed and parts are already included with this release, this manual is only still included to provide access to documentation about functions that are not yet documented in the new manual.

Author information
SCAR Divi is created by Kaitnieks (Aivars Irmejs) and Freddy1990 (Frédéric Hannes)
© 2010-2011 Frédéric Hannes
If you like SCAR, drop me a line: freddy1990@gmail.com
Community website: http://freddy1990.com/forums
SCAR official webpage: http://www.freddy1990.com/?page=products&name=scar

Additional Credits
- Everyone who tested this version of SCAR.
- Benland100 for the WindMouse function and a nice deal of math functions.
- Cruel for his MoveMouseCC function.
- Newbiehacker for his string functions.
- Janilabo for his Average function.

Introduction
SCAR is a scriptable color clicker which is meant to be used to automate tasks. The general purpose of SCAR is automating repetitive actions in online games by simulating human interaction, which in most cases is considered cheating. SCAR uses custom  version of Pascal language for scripts and includes a number of built in functions for mouse, keyboard interaction, text, color, bitmap searching etc. SCAR makes script developing easy by offering friendly IDE with syntax highlighting and script debugging features.

General
You should start with trying out sample scripts. The default shortcut keys are Ctrl+Alt+R to run script and Ctrl+Alt+S to stop.
To specify client window just drag the crosshair over the client (the game area itself).
If it can't find files or there are any other problems, make sure you have extracted all required files and directories from the archive.
If it doesn't run script because includes are missing, make sure you download the required includes and copy them to same folder your script is or "Includes" folder (from SCAR menu Tools > Explore Folder > Includes Folder).

Pascal basics
Some Pascal basics can be found here, but I must warn you that the site will scare you:
http://www.learn-programming.za.net/programming_pascal_learn01.html
You really should find and read a serious Pascal tutorial, this manual will give you an idea, not teach the Pascal language.
The simplest Pascal program:
begin
end.
As you see, it requires 2 lines - begin shows where the program starts, end with dot - where it ends. Everything after it gets ignored. A better program would be:

program MyFirst;
begin
† Writeln ('Hello World!');
end.

It's a good style to specify program name at the beginning, also pay attention to spacing, small and capital letters, usage of semicolons.
Here is a thing about variables. I know most of you avoided them at all in AR script, but they are easier here (I hope). The variables have types. SCAR supports less types than Pascal and for those who are familiar with Pascal - it doesn't support arrays (ok it actually does, I just didn't want to explain it here :P). Here are types you will use:

string Text, string of characters 'a', 'some text', 'awaa'#13'bah'
Integer Whole numbers, positive and negative 0, 1, 2, 3, ..., -1, -2, -3, ...
Extended Real numbers, positive and negative 0, 1.5, -100.67, 100.3333
Boolean Have only 2 values - true or false

True, False

There are other types too, but these are the main to operate with. A simple example:

program VarDemo;
var s: string;
begin
† s:= 'Hello World!';
† Writeln(s);
end.

As you see, we have to use var variable_name : type; to define the variable before using it.
You will sometimes want to print out Integer and Extended type variable values, so here is a sample to do it as only strings can be printed out. A sample of type conversion:

program PrintNumbers;
var i: Integer;
††† e: Extended;
begin
† i:= 10;
† e:= 3.5;
† Writeln('i=' + IntToStr(i) + ', e=' + FloatToStr(e));
end.

(Copy and paste it in SCAR window to test)
What can you do with variables? It depends on variable type. You can concatenate string variables: s:= 'wo' + 'rd'; will result with 'word' in variable s. You can do a whole bunch of arithmetic operations with Integer and Extended: i:= 4 + 5 will result with 9 in i etc. Boolean are useful too. You can set it to true or false: b:= True; or to logical condition b:= (a = 1); will result with True in b is a is equal to 1 or False if a is equal to anything else.
Now about control types.
Conditional statement.

† if( a = 1)or(a = 4)then
† begin
††† a:= 0;
††† Writeln('a was 1 or 4 so we made it to zero');
† end else
† begin
††† Writeln('a was neither 1 nor 4');
† end;

While loops.

i:= 0;
while(i < 10) do
begin
† i:= i + 1;
† Writeln(IntToStr(i));
end;

Repeat loop is very similar, except the condition is checked at the end of the loop and it's exit condition (if it's true, the loop ends), so it always go through repeat-until loop at least 1 time.

i:= 0;
repeat
† i:= i + 1;
† Writeln(IntToStr(i));
until(i >= 10);

For loops.

for i:= 1 to 10 do
begin
† Writeln(i);
end;


That's all about control structures. You will understand more from the examples included with SCAR.

Here you also have an ascii table for keycodes to use with keyboard functions:
Ascii Table

Standard functions

function Readln(question: string): string;
Asks question to user and returns the answer.

function GetArrayLength(var Arr): LongInt;
Returns the length of the specified array.

procedure SetArrayLength(var Arr; Count: LongInt);
Sets the length of the specified array.

function VarGetType(x: Variant): TVarType;

function Null: Variant;

procedure RaiseLastException;

procedure RaiseException(Ex: TIFException; Param: string);

function ExceptionType: TIFException;

function ExceptionParam: string;

function ExceptionProc: Cardinal;

function ExceptionPos: Cardinal;

function ExceptionToString(er: TIFException; Param: string): string;

Function means that the function returns a value, procedure just does something and doesn't return anything. Parameters and their types are specified in brackets and as the last comes type of function return value.

Supported classes

This is only a list of some of classes that can be used in SCAR. For more help on properties and methods of individual classes consult Delphi help or internet search. Remember that only very limited functionality is implemented and many properties and methods that work in Delphi will not work in SCAR. Not all supported classes are listed here, only the main ones.

TGroupBox - The TGroupBox component represents a standard group box, used to group related controls on a form.

TLabel - Use TLabel to add text or a bitmap that the user canít edit to a form.

TEdit - Use a TEdit object to put a standard edit control on a form.

TMemo - Use TMemo to put a standard multiline edit control on a form.

TComboBox - A TComboBox component is an edit box with a scrollable drop-down list attached to it.

TButton - Use TButton to put a standard push button on a form.

TCheckBox - A TCheckBox component presents an option for the user.

TRadioButton - Use TRadioButton to add a radio button to a form.

TListBox - Use TListBox to display a scrollable list of items that users can select, add, or delete.

TScrollBar - Use TScrollBar to add a free-standing scroll bar to a form.

TImage - Use TImage to display a graphical image on a form.

TPanel - Use TPanel to put an empty panel on a form.

TTimer - TTimer is used to simplify calling the system timer functions.

TForm - form (window) component.

TApplication - TApplication encapsulates a windowed application.

TMenuItem - Use TMenuItem to specify the appearance and behavior of an item in a menu.

TMenu - Use TMenu as a base class when defining a component that represents a collection of menu items.

TMainMenu - Use TMainMenu to provide the main menu for a form.

TPopupMenu - Use TPopupMenu to define the pop-up menu that appears when the user clicks on a control with the right mouse button.

TCanvas - Use TCanvas as a drawing surface for objects that draw an image of themselves.

TProgressBar - Use TProgressBar to add a progressbar to a form.

TRichEdit - Use TRichEdit to add a RichEdit textbox to a form.

TPageControl - Use TPageControl to add a pagecontrol to a form.

TTabControl - Use TTabControl to add a tabcontrol to a form.

TTabSheet - Use TTabSheet to add a tab to a pagecontrol or tabcontrol.

TStatusBar - Use TStatusBar to add a statusbar to a form.

TStatusPanel - Use TStatusPanel to add a panel to a statusbar.

TColorPicker - Use TColorPicker to create a ColorPicker control.

String functions

function copy(s: string; ifrom, icount: LongInt): string;
Returns part of the string (Copy('abcde',2,3) would return 'bcd'.

function pos(substr, s: string): LongInt;
Returns position of substring in string. Returns 0 if not found.

procedure delete(var s: string; ifrom, icount: LongInt);
Delete part of string.

procedure insert(s: string; var s2: string; ipos: LongInt);
Insert s into s2.

function Between(s1, s2, s: string): string;
Returns part of string s between substrings s1 and s2.

function StrGet(var S: string; I: Integer): Char;

procedure StrSet(c: Char; I: Integer; var s: string);

function Uppercase(s: string): string;
Returns the specified string in upper case.

function Lowercase(s: string): string;
Returns the specified string in lowercase.

function Trim(s: string): string;
Removes spaces from start and end of string.

function Length(s: string): LongInt;
Returns string length in characters.

procedure SetLength(var S: string; L: LongInt);

function Padl(s: string; I: LongInt): string;

function Padr(s: string; I: LongInt): string;

function Padz(s: string; I: LongInt): string;

function Replicate(c: Char; I: LongInt): string;

function StringOfChar(c: Char; I: LongInt): string;

function Left(Text: string; Count: Integer): string;
Returns a part of the leftside of a string, the length is specified by Count.

function Right(Text: string; Count: Integer): string;
Returns a part of the rightside of a string, the length is specified by Count.

function Replace(Text, FindStr, ReplaceStr: string): string;
Replaces all instances of FindStr in Text by ReplaceStr.

function GetNumbers(Text: string): string;
Returns all numerical chars found in a string.

function GetLetters(Text: string): string;
Returns all alphabetical chars found in a string.

function GetOthers(Text: string): string;
Returns all non-numerical and non-alphabetical chars in a string.

function TrimNumbers(Text: string): string;
Removes all numerical chars from a string.

function TrimLetters(Text: string): string;
Removes all alphabetical chars from a string.

function TrimOthers(Text: string): string;
Removes all chars that are not numerical and not alphabetical from a string.

function Capitalize(S: string): string;
Will capitalize strings.
Example:
hello world => Hello World

function InStrArr(Str: string; Arr: TStringArray; CaseSensitive: Boolean): Boolean;
Returns true if the string Str is found in the TStringArray Arr, if the CaseSensitive Boolean is true it will compare the strings with casesensitivity, else without.

function PosEx(search, s: string; from: Integer): Integer;
Returns the position of the substring in s searching forwards from from.

function LastPosEx(search, s: string; from: Integer): Integer;
Returns the position of the substring in s searching backwards from from.

function LastPos(search, s: string): Integer;
Returns the position of the substring in s searching backwards from the end of the string.

function StartsWith(prefix, s: string): Boolean;
Returns true if s starts with prefix.

function EndsWith(suffix, s: string): Boolean;
Returns true if s ends with suffix.

function TrimEx(delimiter, s: string): string;
Trims the specified delimiter from the start and end of the string.

function RegexPos(Txt, Regex: string): Integer;
Returns the position of the first found occurence of the regex.

function FindRegex(Txt, Regex: string): string;
Returns the string found by the regex.

function ReplaceRegex(Txt, Regex, ReplaceStr: string): string;
Replaces all occurences of the found regex by ReplaceStr.

function MD5(s: string): string;
Converts a string to an MD5 hash.

function Format(s: string; data: array of const): string;
Formats a string with data.

function Implode(Glue: string; Pieces: TStringArray): string;
Implodes strings into 1 string.

function Explode(Separator, s: string): TStringArray;
Explodes a string into pieces.

function ExplodeEx(Separator, s: string; Limit: Integer): TStringArray;
Explodes a string into pieces with a Limit.

Mouse, keyboard functions

procedure GetMousePos(var x, y: Integer);
Read current mouse position into x, y.

procedure MoveMouse(x, y: Integer);
Simulate mouse movement, move cursor to x, y instantly.

procedure MoveMouseSmooth(x, y: Integer);
Simulate humanlike mouse movement to x, y from current mouse position.

procedure MoveMouseSmoothEx(x, y: Integer; minsleeptime, maxsleeptime, maxdistance, gravity, forces: Integer);
Simulate humanlike mouse movement with more customizable parameters. By default MinSleepTime = 1; MaxSleepTime = 3; MaxDistance = 45; Gravity = 20; Forces = 10. Minsleeptime and Maxsleeptime limit pause between mouse cursor jumps, MaxDistance is maximal allowed distance between mouse jumps, Gravity is how much mouse tends to reach destination, Forces are like random winds, hand shaking simulation.

procedure MoveMouseSmoothFrom(x1, y1, x2, y2: Integer);
Works like MoveMouseSmooth but has starting position specified. Moves mouse cursor smoothly from x1, y1 to x2, y2.

procedure MoveMouseSmoothFromEx(x1, y1, x2, y2: Integer; minsleeptime, maxsleeptime, maxdistance, gravity, forces: Integer);
Works like MoveMouseSmoothEx but has starting position specified. Moves mouse cursor smoothly from x1, y1 to x2, y2.

procedure MoveWindMouse(x, y, rx, ry: Integer);
Moves the mouse in a very humanlike way to the coordinates x and y with their respecive randomness rx and ry.

procedure MoveWindMouseEx(x, y, rx, ry, MouseSpeed: Integer);
Works like MoveWindMouse and allows you to set the MouseSpeed (15 by default).

procedure ClickWindMouse(x, y, rx, ry: Integer; Left: Boolean);
Clicks the mouse in a very humanlike way at the coordinates entered and moves to the coordinates using the MoveWindMouse function.

procedure MouseBox(x1, y1, x2, y2: Integer);
Moves mouse (with WindMouse) to a random coordinate in a box specified by 2 sets of coordinates x1, y1 and x2, y2.

procedure MoveMouseCC(x, y, range, segments, pcount, delay: Integer);
Moves the mouse to the coordinate determined by x and y. The range is the random offset of the destination point. For example, a range of 5 would change the destination of (100, 100) to a point between (95, 95) and (105, 105). The segments are the number of steps the mouse take between each control point. The pcount is the number of control points to generate. And finally the delay is time in milliseconds to pause on each step. Set it higher for slower movement.

procedure ClickMouse(x, y: Integer; Left: Boolean);
Simulate mouse click at x, y.
Example:
ClickMouse(100, 30, True); // Left click at coordinates 100, 30

procedure ClickMouseMid(x, y: Integer);
Simulate a middle mouse click at x, y.

procedure ClickMouseBox(x1, y1, x2, y2: Integer; Left: Boolean);
Simulate random mouse click in a box specified by 2 sets of coordinates x1, y1 and x2, y2.

procedure HoldMouse(x, y: Integer; Left: Boolean);
Holds mouse button. Set parameter Left to true for left button, false for right.

procedure ReleaseMouse(x, y: Integer; Left: Boolean);
Releases mouse button. Set parameter Left to true for left button, false for right.

procedure HoldMouseMid(x, y: Integer);
Holds the middle mouse button.

procedure ReleaseMouseMid(x, y: Integer);
Releases the middle mouse button.

procedure SendKeys(s: string);
Simulate key pressing to send a string to the active window.

procedure TypeKeys(s: string);
Simulate key pressing to send a string to the active window in a very human-like way.

procedure SendKeysWait(Text: string; tWait, tRandom: Integer);
Similates key pressing in a humanlike way by defining the waiting time in ms between each key (tWait) and the randomly added wait (tRandom).

procedure SendKeysSilent(S: string);
Send string to Client's window, if this doesn't work, use SendKeys.

procedure SendArrow(Key: Byte);
Sends arrow to Client's window. For a, 0 = up, 1 = right, 2 = down, 3 = left.

procedure SendArrowWait(Key: Byte; WaitTime: Integer);
Sends an arrow to Client's window like SendArrow and holds it for a given wait time.
Example:
SendArrowSilentWait(1, 10); // Holds "Right" arrow for 10 milliseconds.

procedure SendArrowSilent(a: Byte);
Sends arrow to Client's window. For a, 0 = up, 1 = right, 2 = down, 3 = left.

procedure SendArrowSilentWait(a: Byte; WaitTime: Integer)
Sends an arrow to Client's window like SendArrowSilent and holds it for a given wait time.
Example:
SendArrowSilentWait(1, 10); // Holds "Right" arrow for 10 milliseconds.

procedure SendKeysVB(S: string; Wait: Boolean);
Sends the keys analogically to Visual Basic SendKeys command. Wait parameter specifies if SCAR should wait for the command to complete.

procedure KeyDown(Key: Byte);
Simulates pushing a key.

procedure KeyUp(Key: Byte);
Simulates releasing a key.

procedure KeyDownSilent(Key: Byte);
Simulates pushing a key in silent mode.

procedure KeyUpSilent(Key: Byte);
Simulates releasing a key in silent mode.

function GetKeyCode(Key: Char): Byte;
Get keyboard code of a character.

function IsMouseButtonDown(LeftButton: Boolean): Boolean;
If LeftButton is true, then it checks if the left mouse button is down.
If LeftButton is false, checks if the right mouse button is down.

function IsFunctionKeyDown(Key: Byte): Boolean;
Checks if the given function key is down.
Meanings of Key:
0: SHIFT
1: CONTROL
2: ALT
3: LEFT SHIFT
4: LEFT CONTROL
5: LEFT ALT
6: RIGHT SHIFT
7: RIGHT CONTROL
8: RIGHT ALT

function IsFKeyDown(Num: Byte): Boolean;
Num = 1..12. Checks if F1, F2, ... F11 or F12 key is down corresponding to Num.

function IsArrowDown(Num: Byte): Boolean;
Checks if arrow key is down. Num corresponds to 0 = up, 1 = right, 2 = down, 3 = left.

function IsKeyDown(C: Char): Boolean;
Checks if the given key is down.
Example:
if(IsKeyDown('a'))then
  Writeln('You have pressed "a". Congratulations!');

function IsNumpadKeyDown(Key: Byte): Boolean;
Checks if the entered numpad key is down (you just enter a digit).

functionIsNumpadEnabled: Boolean;
Returns True if the numpad is enabled.

function IsCapsLockEnabled: Boolean;
Returns True if caps lock is turned on.

function GetCursorType: TCursor;
Gets the current cursortype.

Color, bitmap searching and related functions

function LoadBitmap(path: string): Integer;
Loads bitmap (*.bmp) in memory and returns handle to it. Path can be absolute or relative if starts with a dot.
Example:
somepic := LoadBitmap('.\somepic.bmp');

procedure FreeBitmap(bitmap: Integer);
Releases a bitmap and frees the memory.

function BitmapFromString(Width, Height: Integer; data: string): Integer;
Loads bitmap in memory from string data and returns handle to it. (Older method)

function BitmapFromString2(Validate: Boolean; str: string): Integer;
Loads bitmap in memory from string data and returns handle to it. Data strings can be created by clicking menu Tools > Picture To String. If validate is true it'll validate the bitmap.

function BitmapFromMem(Dc: HDC): Integer;
Loads bitmap into the memory from a HDC of another bitmap in the memory.

function CreateBitmapMaskFromText(Text: string; Chars: Integer): Integer;
Creates mask image from text that can be used for searching text. Chars specifies font number returned by LoadChars2 or LoadCharsFromFont2.

function CreateBitmapFromText(Text: string; Chars: Integer; TextColor: Integer): Integer;
Creates mask image from text with a certain color that can be used for searching text. Chars specifies font number returned by LoadChars2 or LoadCharsFromFont2.

function CreateMirroredBitmap(bitmap: Integer): Integer;
Creates mirror image from another bitmap.

function GetColor(x, y: Integer): Integer;
Return color number at x, y.

function GetColors(Coords: TPointArray): TIntegerArray;
Works like GetColor, but allows you to get the color of several points, specified by Coords.

function FindColor(var x, y: Integer; color, xs, ys, xe, ye: Integer): Boolean;
Find color in box specified by xs, ys, xe, ye starting from left to right. Returns True if color found, the coordinates of the color if found is put in x,y.

function FindColorTolerance(var x, y: Integer; color, xs, ys, xe, ye: Integer; Tolerance: Integer): Boolean;
Works like the regular FindColor function but with a tolerance parameter for finding any similar color. Tolerance is used to find a color in range of the color you are looking for. The greater color range you want, the higher the tolerance parameter should be.

function FindColorSpiral(var x, y: Integer; color, xs, ys, xe, ye: Integer): Boolean;
Find color in box specified by xs, ys, xe, ye but start from x,y.

function FindColorSpiralTolerance(var x, y: Integer; color, xs, ys, xe, ye: Integer; Tolerance: Integer): Boolean;
Works like the regular FindColorSpiral but with a tolerance parameter for finding any similar color. Tolerance is used to find a color in range of the color you are looking for. The greater color range you want, the higher the tolerance parameter should be.

function FindColorSpiral2(var x, y: Integer; color, xs, ys, xe, ye: Integer): Boolean;
Find color just like FindColorSpiral, and if there is a big spot of that color then it finds the center of it.

function FindColoredAreaTolerance(var x, y: Integer; color, xs, ys, xe, ye: Integer; MinArea, Tolerance: Integer): Boolean;
Works similar to FindColorTolerance but instead of finding just 1 colored pixel and storing the coordinates into x and y, it finds an area where the colored pixel was found and stores a random coordinate according to the entered MinArea value into x,y. MinArea is specified by the count of pixels it has in an area. To find area in size 10X10 you would enter 100 as MinArea.

function FindColorSkipBox(var x, y: Integer; color, x1, y1, x2, y2: Integer; SkipBox: TBox): Boolean;
Finds a color in an area specified by x1, y1, x2 and y2, while skipping the area specified by the TBox, SkipBox.

If you'd be using a non-spiral findcolor function, the dot in the green area would be found first, but since it is in the green area which is the part where the skipbox overlaps the search area, it will ignore it, so the other dot will be found.

function FindColorSkipBoxTolerance(var x, y: Integer; color, x1, y1, x2, y2, Tolerance: Integer; SkipBox: TBox): Boolean;
Works like the regular FindColorSkipBox function but with a tolerance parameter for finding any similar color. Tolerance is used to find a color in range of the color you are looking for. The greater color range you want, the higher the tolerance parameter should be.

function FindColorSkipBoxArray(var x, y: Integer; color, x1, y1, x2, y2: Integer; SkipBoxes: TBoxArray): Boolean;
Finds a color in an area specified by x1, y1, x2 and y2, while skipping the areas specified by the TBoxArray, SkipBoxes.

function FindColorSkipBoxArrayTolerance(var x, y: Integer; color, x1, y1, x2, y2, Tolerance: Integer; SkipBoxes: TBoxArray): Boolean;
Works like the regular FindColorSkipBoxArray function but with a tolerance parameter for finding any similar color. Tolerance is used to find a color in range of the color you are looking for. The greater color range you want, the higher the tolerance parameter should be.

function FindColorSkipCoords(var x, y: Integer; color, x1, y1, x2, y2: Integer; SkipCoords: TPointArray): Boolean;
Finds a color in an area specified by x1, y1, x2 and y2, while skipping the coordinates specified by SkipCoords.

function FindColorSkipCoordsTolerance(var x, y: Integer; color, x1, y1, x2, y2, Tolerance: Integer; SkipCoords: TPointArray): Boolean;
Works like the regular FindColorSkipCoords function but with a tolerance parameter for finding any similar color. Tolerance is used to find a color in range of the color you are looking for. The greater color range you want, the higher the tolerance parameter should be.

function FindColorCircle(var x, y: Integer; color, mx, my, r: Integer): Boolean;
Finds a color in a circular area specified by a set of coordinates for the midpoint (mx, my) and a radius specified by r.

function FindColorCircleTolerance(var x, y: Integer; color, mx, my, r, Tolerance: Integer): Boolean;
Works like the regular FindColorCircle function but with a tolerance parameter for finding any similar color. Tolerance is used to find a color in range of the color you are looking for. The greater color range you want, the higher the tolerance parameter should be.

function FindColorTriangle(var x, y: Integer; color, x1, y1, x2, y2, x3, y3: Integer): Boolean;
Finds a color in a triangle defined by 3 points (x1, y1), (x2, y2) and(x3, y3). If the function returns true then the color was found. The coordinates of the found color are returned in x, y.

function FindColorTriangleTolerance(var x, y: Integer; color, x1, y1, x2, y2, x3, y3, Tolerance: Integer): Boolean;
Works like the regular FindColorTriangle function but with a tolerance parameter for finding any similar color. Tolerance is used to find a color in range of the color you are looking for. The greater color range you want, the higher the tolerance parameter should be.

function GetBitmapAreaColors(xs, ys, xe, ye: Integer): T2DIntArray;
Returns the colors of the area specified by the points (xs, ys) and (xe, ye) in a 2 dimensional integer array.

function CountColor(Color, x1, y1, x2, y2: Integer): Integer;
Counts the instances found of Color in the area specified by x1, y1, x2 and y2.

function CountColorTolerance(Color, x1, y1, x2, y2, Tolerance: Integer): Integer;
Works like the regular CountColor function but with a tolerance parameter for finding any similar color. Tolerance is used to find a color in range of the color you are looking for. The greater color range you want, the higher the tolerance parameter should be.

function FindColorComp(var x, y: Integer; Comp: Variant; CompType: TColorComp; xs, ys, xe, ye: Integer; Tolerance: Extended): Boolean;
Finds a certain component in the same way as FindColor(Tolerance) finds a color. You can define which colorcomponent you want to search with the CompType paramater (ccRed, ccGreen, ccBlue, ccHue, ccSat, ccLum) and you enter the value of the component you're looking for in the parameter Comp.

function FindBitmap(Bitmap: Integer; var x, y: Integer): Boolean;
Search for the bitmap in client window. If found coordinates are returned in x,y. bitmap contains handle to bitmap generated by LoadBitmap.

function FindBitmapTolerance(Bitmap: Integer; var x, y: Integer; Tol: Integer): Boolean;
Works like FindBitmap but with a tolerance parameter for finding any similar colored bitmap. Tolerance is used to find a colored bitmap in range of the bitmap you are looking for. The greater color range you want, the higher the tolerance parameter should be.

function FindBitmapIn(Bitmap: Integer; var x, y: Integer; x1, y1, x2, y2: Integer): Boolean;
Search for the bitmap in coordinates specified by x1, y1, x2, y2. Bitmap contains handle to bitmap generated by LoadBitmap.

function FindBitmapToleranceIn(Bitmap: Integer; var x, y: Integer; x1, y1, x2, y2: Integer; tolerance: Integer): Boolean;
Works like FindBitmapIn but with a tolerance parameter for finding any similar colored bitmap. Tolerance is used to find a colored bitmap in range of the bitmap you are looking for. The greater color range you want, the higher the tolerance parameter should be.

function FindTransparentBitmap(Bitmap: Integer; var x, y: Integer; TranspCol, x1, y1, x2, y2: Integer): Boolean;
Search for the bitmap in coordinates specified by x1, y1, x2, y2. Bitmap contains handle to bitmap generated by LoadBitmap. The function will match any color for the the transparent color on the bitmap you're trying to find which is entered in the TranspCol variable.

function FindTransparentBitmapTolerance(Bitmap: Integer; var x, y: Integer; TranspCol, x1, y1, x2, y2: Integer; tolerance: Integer): Boolean;
Works like FindTransparentBitmap but with a tolerance parameter for finding any similar colored bitmap. Tolerance is used to find a colored bitmap in range of the bitmap you are looking for. The greater color range you want, the higher the tolerance parameter should be.

function FindBitmapSpiral(bitmap: Integer; var x, y: Integer; x1, y1, x2, y2: Integer): Boolean;
Search for the bitmap in coordinates specified by x1, y1, x2, y2 starting from x, y. Bitmap contains handle to bitmap generated by LoadBitmap.

function FindBitmapSpiralTolerance(bitmap: Integer; var x, y: Integer; x1, y1, x2, y2: Integer; Tolerance: Integer): Boolean;
Works like FindBitmapSpiral but with a tolerance parameter for finding any similar colored bitmap. Tolerance is used to find a colored bitmap in range of the bitmap you are looking for. The greater color range you want, the higher the tolerance parameter should be.

function FindBitmapMaskTolerance(mask: Integer; var x, y: Integer; x1, y1, x2, y2: Integer; Tolerance, ContourTolerance: Integer): Boolean;
Essentially it works like FindBitmapIn except it identifies using the masks/shape of an object in the bitmap. Masks are specified by the colors black and white. ContourTolerance is the minimal tolerance for color difference between shape of a mask and the background in a bitmap, It makes sure the shape differs from the background.
<-- sample mask for finding letter A in any color.

function FindDeformedBitmapToleranceIn(bitmap: Integer; var x, y: Integer; x1, y1, x2, y2: Integer; tolerance: Integer; Range: Integer; AllowPartialAccuracy: Boolean; var accuracy: Extended): Boolean;
Works similar to FindBitmapToleranceIn but allows searching for partially covered or transformed bitmaps. If range is 0, it checks pixels at positions that match bitmap we are looking for; if Range ir 1, it checks neighbor pixels as well, if range is bigger, it checks further. AllowPartialAccuracy allows accuracy that is not 100% match. accuracy returns accuracy of found bitmap to bitmap we are looking for. accuracy = 1.0 means it was 100% perfect match.
Example: we are searching for .
1. Target bitmap:
FindDeformedBitmapToleranceIn(b, x, y, 0, 0, 100, 100, 70, 0, True, acc);
Results: acc = 0.825745682889
FindDeformedBitmapToleranceIn(b, x, y, 0, 0, 100, 100, 70, 1, True, acc);
Results: acc = 1.000000000000
2. Target bitmap:
FindDeformedBitmapToleranceIn(b, x, y, 0, 0, 100, 100, 70, 0, True, acc);
acc = 0.585557299843
FindDeformedBitmapToleranceIn(b, x, y, 0, 0, 100, 100, 70, 1, True, acc);
acc = 0.751962323391

function FindDeformedBitmapToleranceRotationIn(bitmap: Integer; var x, y: Integer; x1, y1, x2, y2: Integer; tolerance: Integer; Range: Integer; var accuracy: Extended; AngleIntervals: Extended; StartAngle, MaxAngle: Extended; var angle: Extended): Boolean;
Works similar to FindDeformedBitmapToleranceIn but allows searching for rotated bitmaps as well. Basically it rotates bitmap, searches in target image, then rotates again, searches again. AngleIntervals specifies by how much it rotates every time, StartAndge specifies initial rotation angle, MaxAngle specifies how far it rotates and angle returns angle of found image. All angles are specified in radians (Pi = 180˚)
Example:
FindDeformedBitmapToleranceRotationIn(minimaptree, x, y, 582, 37, 700, 117, 170, 0, acc, PI/10, 0, 2*PI, angle);

function FindBitmapRotated(bitmap: Integer; var x, y, Angle: Integer; x1, y1, x2, y2: Integer): Boolean;
Works like FindBitmap, but rotates the bitmap after each search by 1 degree and returns the angle of the found bitmap afterwards.

function RotateBitmap(bitmap: Integer; angle: Extended): Integer;
Rotates bitmap by specified angle in radians (Pi = 180˚);

function SimilarColors(col1, col2, tolerance: Integer): Boolean;
Function to test weather two colors are within tolerance range. If they are within range, it returns true, if not false.

function GetTolerance(Col1, Col2: Integer): Integer;
Gets the tolerance required to match 2 colors.

function GetClosestColor(Color: Integer; Colors: TIntegerArray): Integer;
Gets the color from the entered array that resembles the entered Color the most.

procedure PickColor(var Color: TColor; var X, Y: Integer);
This command allows color to be picked directly from script. Color returns color picked and x, y returns coordinates the color was picked at.

function FindColors(var Points: TPointArray; Color, xs, ys, xe, ye, Tol: Integer): Boolean;
Finds all colors in the area specified by xs, ys, xe, ye and returns their coordinates in Points. Will return True if any colors are found.

function FindColorsTolerance(var Points: TPointArray; Color, xs, ys, xe, ye, Tol: Integer): Boolean;
Finds all colors with tolerance in the area specified by xs, ys, xe, ye and returns their coordinates in Points. Will return True if any colors are found.

procedure FindColorsSpiralTolerance(x, y: Integer; var Points: TPointArray; color, xs, ys, xe, ye: Integer; Tolerance: Integer);
Finds all colors in area specified by xs, ys, xe, ye and returns their coordinates into Points.

function FindBitmaps(Bitmap: Integer; var Points: TPointArray; xs, ys, xe, ye: Integer): Boolean;
Returns the coordinates of all instances of the entered Bitmap found in the search area in the Points array.

function FindBitmapsTolerance(Bitmap: Integer; var Points: TPointArray; xs, ys, xe, ye, Tol: Integer): Boolean;
Returns the coordinates of all instances of the entered Bitmap found with tolerance in the search area in the Points array.

function FindTransparentBitmaps(Bitmap: Integer; var Points: TPointArray; TranspCol, xs, ys, xe, ye, Tol: Integer): Boolean;
Returns the coordinates of all instances of the entered Bitmap found in the search area in the Points array. Pixels on the search Bitmap with the color defined by TranspCol will be skipped in the search.

function FindTransparentBitmapsTolerance(Bitmap: Integer; var Points: TPointArray; TranspCol, xs, ys, xe, ye, Tol: Integer): Boolean;
Returns the coordinates of all instances of the entered Bitmap found with tolerance in the search area in the Points array. Pixels on the search Bitmap with the color defined by TranspCol will be skipped in the search.

function CountBitmap(Bitmap: Integer; xs, ys, xe, ye: Integer): Integer;
Counts the number of instances of the entered Bitmap found in the search area.

function CountBitmapTolerance(Bitmap: Integer; xs, ys, xe, ye, Tol: Integer): Integer;
Counts the number of instances of the entered Bitmap found with tolerance in the search area.

function CountTransparentBitmap(Bitmap: Integer; TranspCol, xs, ys, xe, ye: Integer): Integer;
Counts the number of instances of the entered Bitmap found in the search area. Pixels on the search Bitmap with the color defined by TranspCol will be skipped in the search.

function CountTransparentBitmapTolerance(Bitmap: Integer; TranspCol, xs, ys, xe, ye, Tol: Integer): Integer;
Counts the number of instances of the entered Bitmap found with tolerance in the search area. Pixels on the search Bitmap with the color defined by TranspCol will be skipped in the search.

procedure GetBitmapSize(Bitmap: Integer; var Width, Height: Integer);
Returns the size of the entered Bitmap in Width and Height.

function BitmapToString(Bmp: Integer): string;
Returns a bitmapstring for the entered bitmap.

Color conversion functions:

procedure ColortoRGB(Color: TColor; var R, G, B: Byte);
Converts a Color to RGB values.

function RGBtoColor(R, G, B: Integer): TColor;
Converts RGB values to a color.

procedure ColortoHSL(C: TColor; var H, S, L: Extended);
Converts Color to Hue, Saturation and Luminance map.

function HSLtoColor(var H, S, L: Extended): TColor;
Converts Hue, Saturation and Luminance map to a Color.

procedure RGBtoHSL(R, G, B: Integer; var H, S, L: Extended);
Converts RGB values to Hue, Saturation and Luminance map.

procedure HSLtoRGB(H, S, L: Extended; var R, G, B: Integer);
Converts Hue, Saturation and Luminance map to RGB values.

procedure RGBtoXYZ(R, G, B: Integer; var X, Y, Z: Extended);
Converts RGB values to XYZ values of the CIE color space.

procedure XYZtoRGB(X, Y, Z: Extended; var R, G, B: Integer);
Converts XYZ values of the CIE color space to RGB values.

procedure ColortoXYZ(Color: TColor; var X, Y, Z: Extended);
Converts a Color to XYZ values of the CIE color space.

function XYZtoColor(X, Y, Z: Extended): TColor;
Converts XYZ values of the CIE color space to a color.

procedure HSLtoXYZ(H, S, L: Extended; var X, Y, Z: Extended);
Converts HSL values to XYZ values of the CIE color space.

procedure XYZtoHSL(X, Y, Z: Extended; var H, S, L: Extended);
Converts XYZ values of the CIE color space to HSL values.

Text finding and reading functions

function LoadChars2(path: string): Integer;
Load font from folder in memory.
Example:
UpChars:= LoadChars2(AppPath + 'CharsRS22\');
(If you are planning on creating your own character set, make sure bitmap images are named according to their ASCII codes.)

function LoadCharsFromFont2(fontname: string; fontsize: Integer; fontbold, fontitalic, fontunderline, fontstrike: Boolean): Integer;
Load characters from Windows font in memory.
Example:
c := LoadCharsFromFont2('Courier New', 10, False, False, False, False);

procedure FreeChars2(i: Integer);
Unload font from memory.

function GetTextAtEx(x, y: Integer; Tolerance: Integer; Chars: Integer; CheckShadow, CheckOutline: Boolean; MinSpacing, MaxSpacing: Integer; TextColor: Integer; TextLength: Integer; Strict: Boolean; Range: TCharRange): string;
Reads text at position specified by x, y. Tolerance specifies acceptable color range in for characters that are not completely monochrome, Chars specifies font number returned by LoadChars2 or LoadCharsFromFont2, CheckShadow specifies whether function should look for shadow, CheckOutline specifies whether function should verify if character borders are correct, MinSpacing and MaxSpacing are RS1 and RS2 specific parameters for text with changing spacing between characters, in other cases use MinSpacing=0 and MaxSpacing=0,  TextColor specifies text color, if set to -1, will search for text in any color, TextLength - maximal text length to read, if Strict is set to true then it won't find characters that contain additional pixels of character's color in the same area as character is, Range can have following values:
tr_AllChars - read all characters;
tr_BigLetters - read capital Latin letters;
tr_SmallLetters - read lowercase Latin letters;
tr_Digits - read digits;
tr_BigSymbols - read symbols that are big in size, like "=", "%", "$", etc;
tr_SmallSymbols - read small symbols like ".", ",", "'", etc;
tr_SecondTableChars - read symbols with character code above 127;
tr_Letters = tr_BigLetters or tr_SmallLetters;
tr_AlphaNumericChars = tr_Letters or tr_Digits;
tr_Symbols = tr_BigSymbols or tr_SmallSymbols;
tr_NormalChars = tr_AlphaNumericChars or tr_Symbols;
Example:
GetTextAtEx(9, 9, 130, UpChars, True, False, 0, 1, $E0E0E0, 20, False, tr_AlphaNumericChars) - read RS2 upper text in this color.
GetTextAtEx(96, 387, 0, ChatChars, False, False, 0, 0, -1, 20, True, tr_NormalChars) - read RS2 chat text in any color.
UpChars and ChatChars are set up during script initialization like this:
UpChars := LoadChars2(AppPath + 'CharsRS22\');
ChatChars := LoadChars2(AppPath + 'CharsChat2\');

function IsTextAtEx(x, y: Integer; S: string; Tolerance: Integer; Chars: Integer; CheckShadow, CheckOutline: Boolean; MinSpacing, MaxSpacing: Integer; TextColor: Integer): Boolean;
Checks if text specified by S is at location specified by x, y. Tolerance specifies acceptable color range in case characters are not completely monochrome, Chars specifies font number returned by LoadChars2 or LoadCharsFromFont2, CheckShadow specifies whether function should look for shadow, CheckOutline specifies whether function should verify if character borders are correct, MinSpacing and MaxSpacing are RS1 and RS2 specific parameters for text with changing spacing between characters, in other cases use MinSpacing=0 and MaxSpacing=0,  TextColor specifies text color, if set to -1, will search for text in any color.

function IsTextInAreaEx(x1, y1, x2, y2: Integer; var x, y: Integer; S: string; Tolerance: Integer; Chars: Integer; CheckShadow, CheckOutline: Boolean; MinSpacing, MaxSpacing: Integer; TextColor: Integer): Boolean;
Searches for text in area specified by x1, y1, x2, y2. Other parameters match IsTextAtEx.

Deformable template model related functions

function LoadDTM(FileName: string): Integer;
Load deformable template model from file.

function DTMFromString(s: string): Integer;
Load deformable template model from string. Strings can be created in deformable template model editor in menu Tools > DTM editor.

function AddDTM(DTM: TDTM): Integer;
Load a dynamic deformable template model.

procedure FreeDTM(DTM: Integer);
Unload deformable template editor.

function FindDTM(DTM: Integer; var x, y: Integer; x1, y1, x2, y2: Integer): Integer;
Use DTM to find object on client window. x1, y1, x2, y2 specifies box to search in, x, y returns coordinates if found.
Example:
if(FindDTM(rock, x, y, 100, 100, 500, 300)) then
  Writeln('I rock');

Output functions

procedure Writeln(s: string);
Outputs text string to debug box.

procedure Status(s: string);
Shows a message in status bar.

procedure Alert(s: string);
Shows an alert message.

procedure AddToReport(s: string);
Adds a message to the report box.

procedure ClearReport;
Clears all messages sent to the report box

procedure ChangeReportWidth(Width: Integer);
Changes the width of the report box to the given Width.

procedure PlaySound(FileName: string);
Play the specified WAV file.

function CreateMusicPlayer: TMusic;
Creates an instance of SCAR's music file player. Will play wav, mp3, ogg, flac, mp1, mp2, midi and aiff files.

procedure FreeMusicPlayer(Player: TMusic);
Frees an instance of SCAR's music file player.

procedure SaveScreenshot(FileName: string);
Save screenshot of client window in bitmap file.

procedure SaveBitmap(bitmap: Integer; path: string);
Saves a bitmap as a file.

function GetStatus: string;
Returns SCAR window status bar text.

Debug box related functions

procedure ClearDebug;
Clears debug box.

procedure DeleteDebugLine(Line: Integer);
Deletes a line from the debug box.

function GetDebugLineCount: Integer;
Get the number of lines in the debug box.

function GetDebugText: string;
Gets the text in the debugbox.

function GetDebugLine(Line: Integer): string;
Returns a certain given line of the debug box.

procedure ClearDebugLine(Line: Integer);
Clears a certain line of the debug box.

procedure ReplaceDebugLine(Line: Integer; s: string);
Replaces a certain line of the debug box.

function GetDebugParams: TDebugParams;
Retrieves the default make-up settings for the debugbox.

procedure SetDebugParams(Params: TDebugParams);
Sets make-up settings for the next WriteLn to the debugbox.

File functions

function OpenFile(Path: string; Shared: Boolean): Integer;
Opens file for reading and returns file number if successful or negative number if failed. If shared = true then attempts to open files used by other applications as read-only.

function RewriteFile(Path: string; Shared: Boolean): Integer;
Opens file for writing and truncates it. Returns file number if successful or negative number if error.

procedure CloseFile(FileNum: Integer);
Closes file specified by FileNum.

function EndOfFile(FileNum: Integer): Boolean;
Returns true if end of file specified by FileNum reached.

function FileSize(FileNum: Integer): LongInt;
Returns file size in bytes.

function WriteFileByte(FileNum: Integer; b: Byte): Boolean;
Writes a single byte to file.

function WriteFileInt(FileNum: Integer; i: Integer): Boolean;
Writes a single integer to file.

function WriteFileString(FileNum: Integer; s: string): Boolean;
Writes a string to file.

function ReadFileByte(FileNum: Integer; var b: Byte): Boolean;
Reads a single byte from file.

function ReadFileInt(FileNum: Integer; var i: Integer): Boolean;
Reads a single integer from file.

function ReadFileString(FileNum: Integer; var s: string; Length: Integer): Boolean;
Reads Length number of bytes from file into string s.

procedure WriteINI(Section, KeyName, NewString, FileName: string);
Writes data to an ini-structured file.
Structure:
[Section]
KeyName=NewString

function ReadINI(Section, KeyName, FileName: string): string;
Reads data from an ini-structured file.
Structure:
[Section]
KeyName=SomeString

procedure DeleteINI(Section, KeyName, FileName: string);
Deletes a KeyName from an INI file and if you pass an empty string as KeyName it will delete then entire Section.

function DirectoryExists(Directory: string): Boolean;
Returns true if the directory exists.

function FileExists(FileName: string): Boolean;
Returns true if the file exists.

function ExtractFileName(FileName: string): string;
Returns the name of a file from a string.
Example:
C:\somefolder\somefile.ext => somefile.ext

function ExtractFilePath(FileName: string): string;
Returns the filepath from a string.
Example:
C:\somefolder\somefile.ext => C:\somefolder\

function ExtractFileExt(FileName: string): string;
Returns the file extension from a string.
Example:
C:\somefolder\somefile.ext => .ext

function ExtractFileDrive(FileName: string): string;
Returns the file drive from a string.
Example:
C:\somefolder\somefile.ext => C:

function GetFiles(Path, Ext: string): TStringArray;
Returns the files in a directory.

function GetFolders(Path: string): TStringArray;
Returns the folders in a directory.

function SaveToFile(Sender: TObject; FileName: string): Boolean;
Saves the content of certain objects:
TStrings, TStringList, TBitmap, TImage, TPicture, TMemo, TListBox, TComboBox, TRichEdit, TCheckListBox, TGraphic
Returns True if the saving was succesful.

function LoadFromFile(Sender: TObject; FileName: string): Boolean;
Loads the content of certain objects:
TStrings, TStringList, TBitmap, TImage, TPicture, TMemo, TListBox, TComboBox, TRichEdit, TCheckListBox, TGraphic
Returns True if the loading was succesful.

function MD5FromFile(Filepath: string): string;
Returns the MD5 hash value of a file.

function GetFileSize(FileName: string): Int64;
Returns the size of a file without opening it.

Internet functions

function GetPage(URL: string): string;
Return HTTP webpage contents as string.
Example:
s:= GetPage('http://kaitnieks.com');
if(s = '')then
begin
  Writeln('Some kind of connection error');
end else
begin
  ..
end;

procedure OpenWebPage(URL: string);
Opens webpage in default internet browser.

function InitializeHTTPClient(HandleCookies, HandleRedirects: Boolean): Integer;
Creates a new HTTP client in memory and returns handle of the client.

procedure FreeHTTPClient(i: Integer);
Destroys HTTP client in memory.

procedure FreeHTTPClientMulti(HTTPClients: TIntegerArray);
Destroys HTTP client in the memory.

function GetHTTPPage(Client: Integer; URL: string): string;
Return HTTP page contents using specified client.

procedure SetHTTPUserAgent(Client: Integer; Agent: string);
Change HTTP agent value of HTTP client.

function PostHTTPPage(Client: Integer; Url: string; PostData: string): string;
Do POST request of page specified by Url, where POST variables are in string PostData.

function PostHTTPPageEx(Client: Integer; Url: string): string;
Do POST request of page specified by Url, where POST variables are added prior using ClearPostData and AddPostVariable.

procedure ClearPostData(Client: Integer);
Clears POST variables list (for PostHTTPPageEx).

procedure AddPostVariable(Client: Integer; VarName, VarValue: string);
Adds new POST variable (for PostHTTPPageEx).

function GetRawHeaders(Client: Integer): string;
Displays raw response headers of HTTP client.

function OpenConnection(Host: string; Port, TimeOut: Integer): Integer;
Creates new socket connection to specified host and port. Returns connection handle if successful.

function ReadConnectionData(Connection: Integer; var s: string): Boolean;
Reads data from connection into string s.

function SendConnectionData(Connection: Integer; s: string): Boolean;
Sends data to connection.

function IsConnectionOpen(Connection: Integer): Boolean;
Checks if connection is connected. 

procedureAddSSLHandler(Connection: Integer; HTTP: Boolean);
Adds an SSL handler to the Connection.

procedure SetProxyDetails(Connection: Integer; IP: string; Port: Integer);
Sets proxy details on the Connection.

RS2 specific functions

function rs_GetUpText: string;
Gets the text displayed in the upper left corner of the screen.

function rs_GetCustomSizeUpText: string;
Gets the text displayed in the upper left corner of the screen when you're using a custom sized RS client.

function rs_GetUpTextAt(x, y, TextLength: Integer): string;
Gets the text with the specified length (TextLength) (in UpText font) from the coordinates x, y. Check the UpText chars for where you have to pick the y coordinate (the top pixelrow of the char. For the x coordinate pick the column where the first pixel of the character occurs.

SCAR form control, form and object functions

function GetCanvas: TCanvas;
Get reference to game client window's Canvas.

function GetBitmapCanvas(bitmap: Integer): TCanvas;
Get reference to bitmap's Canvas.

function GetDebugCanvas: TCanvas;
Returns a canvas of the debug image window.

procedure CopyCanvas(Source, Dest: TCanvas; sxs, sys, sxe, sye, dxs, dys, dxe, dye: Integer);
Copy image from Source canvas to Dest canvas. Area to be copied from is specified by sxs, sys, sxe, sye, area to be copied to is specified by dxs, dys, dxe, dye.

function CreateForm: TForm;
Creates form. The difference from standard TForm.Create(Application); is that forms created with CreateForm will be destroyed after SCAR script finishes or crashes. Also this function is thread-safe.
Example:
F := CreateForm;
FreeForm(F);

procedure FreeForm(Form: TForm);
Destroys forms created with CreateForm.

procedure LoadDebugBitmap(path: string);
Loads bitmap and displays it in debug image window.

procedure DisplayDebugImgWindow(Width, Height: Integer);
Brings up the debug image window. This window can be used for drawing so you don't have to create your own.

procedure HideDebugImgWindow;
Hides the debug window.

function TBitmapFromBmp(Bitmap: TBitmap; Bmp: Integer): Boolean;
Copies a Bmp from SCAR bitmap system to a TBitmap control.

Client control functions

procedure FindWindow(Title: string);
Finds Client window with specified title. Character case of Title must match that in window title exactly.

function FindWindowTitlePart(Title: string; CaseSensitive: Boolean): Boolean;
Finds window that contains text specified by Title parameter in window caption.

function FindWindowBySize(Width, Height: Integer): Boolean;
Finds window with specified size.

procedure ActivateClient;
Activate client window.

function GetClientWindowHandle: Integer;
Get Windows handle value of active client window.

procedure SetClientWindowHandle(H: Integer);
Set active client window to handle H.
Example:
H:= GetClientWindowHandle;
//specify another client window
FindWindow('Debug Image');
...
//return to previous client
SetClientWindowHandle(H);

procedure SetDesktopAsClient;
Sets the desktop (default window) as selected client.

procedure SetTargetBitmap(bitmap: Integer);
Sets bitmap as target for all color/bitmap searching functions. After calling SetTargetBitmap all functions won't be working with client but with specified bitmap.
Example:
SetTargetBitmap(flagstaff);
if(FindColor(x, y, $000066, 0, 0, 3, 2))then
 ...
The sample above will not search on client screen but in bitmap "flagstaff" instead.

procedure GetClientDimensions(var Width, Height: Integer);
Get client width and height.

procedure CopyClientToBitmap(bitmap: Integer; xs, ys, xe, ye: Integer);
Copy client screen part to bitmap specified.

procedure SetTargetDc(Dc: HDC);
Sets and external device context as target for SCAR's colorfinding functions.

function GetTargetDC: HDC;
Returns the DC of the currently selected window/bitmap.

procedure ResetDc;
Sets the device context of SCAR's selected window as target for SCAR's colorfinding functions.

function GetBitmapDc(Bmp: Integer): HDC;
Returns the device contect of the entered bitmap.

Script control functions

procedure Wait(ms: Integer);
Waits ms milliseconds (Wait(1000) - wait 1 second).

procedure Sleep(ms: Integer);
Alias of Wait.

function SetTimeout(secs: Integer; procname: string): Integer;
Set timed procedure. After secs seconds a procedure with name procname will be called. The procedure should have no parameters and it's only called once (you can SetTimeout again in the procedure).
Example:
SetTimeout(1,'StartPlaying'); will set procedure StartPlaying on timer and it will be called after 1 second.
Declaration:
procedure StartPlaying;
begin
  ...
end;

function ThreadSafeCall(ProcName: string; var V: TVariantArray): Variant;
Calls function or procedure in thread-safe way. SCAR scripts operate in separate thread to prevent main form freezing and as a rule threads are not allowed to create, modify or even access forms or controls directly. That means scripts can't create or use forms or controls directly, operate with debug image directly etc. Most of SCAR functions that access forms (Writeln, Status, Readln, LoadDebugImg, ect) are thread-safe already. However if you're operating with debug window canvas directly for an example, you're risking to make SCAR unstable or crash it.
Example:
var
  Params: TVariantArray;

procedure ChangeTitle(s: string);
begin
  GetSelf.Caption:= s;
end;
....
setarraylength(Params, 1);
Params[0]:= 'Test';
ThreadSafeCall('ChangeTitle', Params);

function CallProc(ProcName: string; var V: TVariantArray): Variant;
Works like ThreadSafeCall but it isn't thread-safe. Do not use this for form interaction.

procedure ClearTimeout(s: string);
Cancels a single timed procedure set with SetTimeout.

procedure ClearTimeouts;
Cancels all timed procedures set with SetTimeout.

procedure TerminateScript;
Immediately terminates the currently running script.

Conversion functions

function inttostr(i: LongInt): string;
Converts integer to string.

function strtoint(s: string): LongInt;
Converts string to integer.

function strtointdef(s: string; def: Longint): Longint;
The StrToIntDef function converts an Integer string, s such as '123' into an Integer value, with a Default if the conversion fails.

function StrToFloat(s: string): Extended;
Converts string to floating pointnumber.

function FloatToStr(e: Extended): string;
Converts floating point number to string.

function IntToPoint(x, y: Integer): TPoint;
Returns the values x and y in a TPoint.

function BoolToStr(Bool: Boolean): String;
Returns a string from a boolean.

function StrToBool(Str: String): Boolean;
Returns a boolean from a string.

function PointToBox(p1, p2: TPoint): TBox;
Returns a TBox defined by 2 points, p1 and p2.

function IntToBox(x1, y1, x2, y2: Integer): TBox;
Returns a TBox specified by 2 sets of integer coordinates, x1, y1, x2 and y2.

function StrToFloatDef(s: string; def: Extended): Extended;
Converts a string to an extended value and returns the default entered value if an error occurs.

function StrToBoolDef(s: string; def: Boolean): Boolean;
Converts a string to an boolean and returns the default entered value if an error occurs.

Random functions

function Random(Range: Integer): Integer;
Returns random 0 <= number < Range. Random(5) will return any of values 0, 1, 2, 3, 4. Random(5) + 1 will return values 1..5.

function RandomRange(From, To: Integer): Integer;
Returns a random value between From and To.

function RBool: Boolean;
Returns a random boolean.

function Rand: Extended;
Returns a random extended value between 0 and 1.

function RBoolEx(Chance: Integer): Boolean;
Returns a True with a chance of 1/Chance.

Time functions

function GetSystemTime: Integer;
Returns the current time in milliseconds.

function GetTickCount: Integer;
Returns the current time in milliseconds.

function GetTimeRunning: Integer;
Returns the ammounts of ms that the script has been running.

procedure ConvertTime(Ms: Integer; var H, M, S: Integer);
Converts miliseconds to hours, minutes and seconds.

Mathematical, number and evaluation functions

function Pow(Base, Exponent: Extended): Extended;
Returns the power of the Base with the given Exponent.

function IntPow(Base: Extended; Exponent: Integer): Extended;
Returns the power of the Base with the given Exponent. Whole number exponents only.

function Max(a, b: Integer): Integer;
Returns biggest of two integer values.

function MaxE(a, b: Extended): Extended;
Returns biggest of two extended values.

function Min(a, b: Integer): Integer;
Returns smallest of two integer values.

function MinE(a, b: Extended): Extended;
Returns smallest of two extended values.

function SameValue(a, b: Extended): Boolean;
Checks if the given Extended numbers are equal.

function Sqrt(e : Extended): Extended;
Returns the square root of e.

function Sqr(X: Extended): Extended;
Returns X² or X*X.

function Round(e: Extended): LongInt;
Rounds and converts floating point number to integer.

function Trunc(e: Extended): LongInt;
Rounds down and converts to integer.

function Int(e: Extended): LongInt;

function Pi : Extended;
Returns the value of Pi (3.14...)

function Abs(e: Extended): Extended;
Returns absolute value (converts negative number to positive).

function Sin(e : Extended): Extended;
The Sin function is a mathematical function giving the Sine value of X given in radians.

function Cos(e : Extended): Extended;
The Cos function is a mathematical function giving the Cosine value of X given in radians.

function Tan(X: Extended): Extended;
The Tan function is a mathematical function giving the Tangent value of X in radians.

function ArcTan(X: Extended): Extended;
The ArcTan function is a mathematical function giving the value in radians of the Arc Tangent of X.

function ArcSin(X: Extended): Extended;
The ArcSin function is a mathematical function giving the value in radians of the Arc Sine of X.

function ArcCos(X: Extended): Extended;
The ArcCos function is a mathematical function giving the value in radians of the Arc Cosine of X.

function ArcTan2(Y, X: Extended): Extended;
ArcTan2 calculates ArcTan(Y/X), and returns an angle in the correct quadrant.
IN: |Y| < 2^64, |X| < 2^64, X <> 0
OUT: [-PI..PI] radians

function Cotan(X: Extended): Extended;
1 / tan(X), X <> 0

function Secant(X: Extended): Extended;
1 / cos(X)

function Cosecant(X: Extended): Extended;
1 / sin(X)

function Hypot(X, Y: Extended): Extended;
Sqrt(X**2 + Y**2)

function Cot(X: Extended): Extended;
Alias for Cotan.

function Sec(X: Extended): Extended;
Alias for Secant.

function Csc(X: Extended): Extended;
Alias for Cosecant.

function Cosh(X: Extended): Extended;
Hyperbolic cosine.

function Sinh(X: Extended): Extended;
Hyperbolic sine.

function Tanh(X: Extended): Extended;
Hyperbolic tangent.

function CotH(X: Extended): Extended;
Hyperbolic cotangent.

function SecH(X: Extended): Extended;
Hyperbolic secant.

function CscH(X: Extended): Extended;
Hyperbolic cosecant.

function ArcCot(X: Extended): Extended;
Inversed cotangent.

function ArcSec(X: Extended): Extended;
Inversed secant.

function ArcCsc(X: Extended): Extended;
Inversed cosecant.

function ArcCosh(X: Extended): Extended;
Inversed hyperbolic cosine.

function ArcSinh(X: Extended): Extended;
Inversed hyperbolic sine.

function ArcTanh(X: Extended): Extended;
Inversed hyperbolic tangent.

function ArcCotH(X: Extended): Extended;
Inversed hyperbolic cotangent.

function ArcSecH(X: Extended): Extended;
Inversed hyperbolic secant.

function ArcCscH(X: Extended): Extended;
Inversed hyperbolic cosecant.

function LnXP1(X: Extended): Extended;
Return ln(1 + X). Accurate for X near 0.

function Log10(X: Extended): Extended;
The Log10 function returns the logarithm to base 10 of X.

function Log2(X: Extended): Extended;

function LogN(Base, X: Extended): Extended;

function Exp(Number: Extended): Extended;
The Exp function takes an integer or floating point Number and raises e (2.72) to that power.

function Factorial(number: Int64): Int64;
Returns the factorial (!) of number.

function BinCoe(a, b: LongInt): Extended;
Returns the binomial coefficient of a and b (a over b).

function InRange(Value, Min, Max: Integer): Boolean;

function Distance(x1, y1, x2, y2: Integer): Integer;
Returns Distance between Points.

function Degrees(Radians: Extended): Extended;
Returns radians in 0-360 degree form.

function Radians(Degrees: Extended): Extended;
Returns the degrees in 0 to 2Pi radian form.

function Inversus(E: Extended): Extended;
Returns the E, inversed.

function Floor(X: Extended): Integer;
Rounds down X to the lowest integer.
Example:
Floor(5.4) = 5

function Ceil(X: Extended): Integer;
Rounds down X to the highest integer.
Example:
Ceil(5.4) = 6

function DecRet(E: Extended): Extended;
Returns the decimal part of E.
Example:
DecRet(28.4678) = 0.4678

function InCircle(x, y, mx, my, r: Integer): Boolean;
Returns true if x and y are in or on a circle specified by the midpoints mx, my and the radius r.

procedure Inc(var X);
Increases X with 1.

procedure IncEx(var X; N: Integer);
Increases X with N.

procedure Dec(var X);
Decreases X with 1.

procedure DecEx(var X; N: Integer);
Decreases X by N.

function IntInBox(x, y: Integer; Box: TBox): Boolean;
Returns true if the coordinate x, y is inside the Box.

function PointInBox(Point: TPoint; Box: TBox): Boolean;
Returns true if the Point is in the Box.

function Hypot(X, Y: Extended): Extended;
Hypot returns the length of the hypotenuse of a right triangle. Specify the lengths of the sides adjacent to the right angle in X and Y.

function InTriangle(x, y, x1, y1, x2, y2, x3, y3: Integer): Boolean;
Returns true if the coordinate x, y is in the truangle defined by the coordinates: (x1, y1) (x2, y2) (x3, y3).

function FixD(Degrees: Extended): Extended;
Returns Degrees in 0-360 form.

function AdjustD(Angle, Adjustment: Extended): Extended;
Adds Adjustment to Angle and returns the angle in 0-360 form.

function FixR(Radians: Extended): Extended;
Returns Radians in 0 to 2Pi form.

function AdjustR(Angle, Adjustment: Extended): Extended;
Adds Adjustment to Angle and returns in 0 to 2Pi form.

function AMin(Data: TIntegerArray): Integer;
Returns the smallest integer value of all values in Data.

function AMinE(Data: TExtendedArray): Extended;
Returns the smallest extended value of all values in Data.

function AMax(Data: TIntegerArray): Integer;
Returns biggest integer value of all values in Data.

function AMaxE(Data: TExtendedArray): Extended;
Returns biggest extended value of all values in Data.

function iAbs(Number: Integer): Integer;
Returns absolute value of an integer (converts negative number to positive).

function ToCart(Point: PPoint): TPoint;
Returns the Cartesian Point of Polar Point point relative to the origin.

function ToCartOffset(Point: PPoint; offset: TPoint): TPoint;
Returns the Cartesian Point of Polar Point point, relative to the offset.
Note: The Polar Point is relative to offset, the Cartesian Point is Relative to the origin.

function ToPolar(Point: TPoint): PPoint;
Returns the Polar Point, relative to the origin, of Cartesian Point point.

function ToPolarOffset(Point, offset: TPoint): PPoint;
Returns the Polar Point, relative to the offset, of Cartesian Point point.
Note: The Polar Point is relative to the offset, the point and offset are Relative to the origin.
Note2: To turn the result back to cartesian use: ToCartOffset(result, offset).

procedure Swap(var A, B: Integer);
Swaps the values A and B.

procedure BubbleSort(var Values: TIntegerArray);
Sorts the values in the entered array from small to large using the BubbleSort algorithm.

procedure BubbleSortB(var Values: TIntegerArray);
Sorts the values in the entered array from large to small using the BubbleSort algorithm.

procedure QuickSort(var Values: TIntegerArray);
Sorts the values in the entered array from small to large using the QuickSort Algorithm.

function Average(Values: TExtendedArray): Extended;
Returns the average of the entered Values.

Communication functions

procedure SendInterSCARMessage(id, message: string);
Sends a string to another script. The ID is used for both scripts to communicate with each other by sending and reading the string/messages. Example: SendInterScarMessage('control', 'Please stop taking my chips');

function ReadInterSCARMessage(id: string): string;
Reads string/messages sent by another script by means of an ID.
Example:
if(ReadInterScarMessage('control') = 'Please stop taking my chips') then
  Writeln('But I already ate them!');

function ReadInterSCARInteger(id: string): Integer;
Reads an integer value from an interscarmessage, like ReadInterSCARMessage.

procedure SendInterSCARInteger(id: string; Int: Integer);
Sends an integer value trough an interscarmessage, like SendInterSCARMessage.

function ReadInterSCARBoolean(id: string): Boolean;
Reads a booleanfrom an interscarmessage, like ReadInterSCARMessage.

procedure SendInterSCARBoolean(id: string; Bool: Boolean);
Sends a boolean trough an interscarmessage, like SendInterSCARMessage.

function ReadInterSCARExtended(id: string): Extended;
Reads an extended value from an interscarmessage, like ReadInterSCARMessage.

procedure SendInterSCARExtended(id: string; Numb: Extended);
Sends an extended value trough an interscarmessage, like SendInterSCARMessage.

function ReadInterSCARInt64(id: string): Int64;
Reads an int64 value from an interscarmessage, like ReadInterSCARMessage.

procedure SendInterSCARInt64(id: string; Numb: Int64);
Sends an int64 value trough an interscarmessage, like SendInterSCARMessage.

Fast drawing functions

procedure SetTransparentColor(bitmap, color: Integer);
Set specified color in bitmap to be transparent for FastDraw functions.

procedure SetTransparencyFromBitmap(Bitmap, AlphaMaskBitmap: Integer);
Sets transparency from bitmap specified by AlphaMaskBitmap, which should be grayscale image, but currently only blue color channel is used. Supports halftones as well.

procedure FastDrawTransparent(x, y: Integer; SourceBitmap, TargetBitmap: Integer);
Draws source bitmap to target bitmap at coordinates specified by x, y.

procedure FastDrawSizeTransparent(x1, y1, x2, y2: Integer; sourcebitmap, targetbitmap: Integer);
Draws source bitmap to target bitmap and stretches to rectangle specified by x1, y1, x2, y2.

procedure FastDrawClear(bitmap: Integer; Color: TColor);
Fills bitmap with a single color.

procedure SafeDrawBitmap(Source: Integer; Dest: TCanvas; x, y: Integer);
Draws Source bitmap to Dest canvas thread-safely at coordinates specified by x, y.

procedure SafeCopyCanvas(Source, Dest: TCanvas; sx1, sy1, sx2, sy2, dx1, dy1, dx2, dy2: Integer);
Acts like CopyCanvas, but is thread-safe.

function FastGetPixel(bitmap: Integer; x, y: Integer): TColor;
Gets color at x, y on bitmap.

procedure FastSetPixel(bitmap: Integer; x, y: Integer; c: TColor);
Puts pixel on bitmap at x, y.

procedure FastReplaceColor(bmp: Integer; OldColor, NewColor: Integer);
Replaces all of the pixels of a certain color (OldColor) in a bitmap with NewColor.

procedure FastReplaceColorTolerance(bmp: Integer; OldColor, NewColor, Tolerance: Integer);
Replaces all of the pixels of a certain color (OldColor) in a bitmap with NewColor, while seaching for OldColor with the given Tolerance.

TPA functions

function TPAInTPA(TPA1, TPA2: TPointArray): Boolean;
Returns true if TPA1 is found completely in TPA2.

function GetTPABounds(TPA: TPointArray): TBox;
Returns a TBox with the boundries of TPA.

function MiddleTPA(TPA: TPointArray): TPoint;
Returns the average of the X and Y values of each TPoint in TPA.

function MiddleTPAEx(TPA: TPointArray; var x, y: Integer): Boolean;
Works the same like MiddleTPA, but returns the averages in the x and y variables. Returns False if the length of TPA is 0.

procedure InvertTPA(var TPA: TPointArray);
Inverts the content of the TPointArray, TPA.

function CombineTPA(TPA1, TPA2: TPointArray): TPointArray;
Combines 2 TPointArrays and returns the result.

Other functions

function AppPath: string;
Get SCAR folder path.

function ScriptPath: string;
Get path of currently active script.

procedure ColorToleranceSpeed(x: Integer);
Sets the speed of tolerance comparisons. ColorToleranceSpeed(1) is a little slower then 0 but more accurate. ColorToleranceSpeed(0) is faster but not as accurate as 1. ColorToleranceSpeed(2) uses Hue, Saturation and Lightness to determine color similarity. ColorToleranceSpeed(3) uses the CIE colorspace to compare colors (XYZ), it's usually fairly slower than the other modes but it's extremely accurate.

function GetColorToleranceSpeed: Integer;
Returns the current tolerancespeed.

procedure SetColorspeed2Modifiers(huemodifier, saturationmodifier: Extended);
These work when ColorToleranceSpeed(2) has been set. Normally Tolerance parameter in this mode applies to Luminance directly. For an example, SimilarColors(c1, c2, 10) would work if both colors differ by 10 max luminance. After calling SetColorspeed2Modifiers(0.2, 2) it would mean that SimilarColors(c1, c2, 10) would check for Hue in range of 2 and Saturation in range of 20. Default huemodifier and saturationmodifier is 0.2.

procedure GetColorspeed2Modifiers(var huemodifier, saturationmodifier: Extended);
Gets the current Colorspeed2 modifiers.

procedure SetColorspeed3Modifiers(Sensitivity: Integer);
This works when ColorToleranceSpeed(3) has been set. This sets the Sensitivity of the 3th color comparison mode. The default Sensitivity is 4. (Note that this is carefully chosen and will be sufficient in most cases.)

procedure GetColorspeed3Modifiers(var Sensitivity: Integer);
Gets the current Colorspeed2 modifiers.

function IsFontSmoothingEnabled: Boolean;
Checks if Windows font smoothing is enabled

procedure SetFontSmoothing(Enable: Boolean);
Sets or unsets Windows font smoothing according to Enable parameter.

function GetSCARVersion: Integer;
Returns current SCAR version.

procedure Disguise(Caption: string);
Changes SCAR's title to Caption.

procedure DisguiseClient(Caption: string);
Changes the client window's title to Caption.

procedure MoveToTray;
Moves SCAR to the systemtray.

procedure SetClientPos(OnTop: Boolean);
Set's the selected client's windowposition.

procedure ShowMessage(Msg: string);
Toggles a messagebox with the text defined by Msg.

procedure ShowMessagePos(Msg: string; X, Y: Integer);
Works like ShowMessage, but allows to choose the coordinates where the box appears.

function GetSoundDuration(FileName: string): Integer;
Gets the duration of a WAV file in ms.

procedure MakeWindowTransparent(Window, Transparency: Integer);
Sets the transparancy of a window, 0 being completely invisible and 255 being completely visible.

function GetSelf: TScar;
Returns a reference to the TScar object, used to influence the main SCAR form.

function GetApplication: TScarApp;
Returns a reference to the TScarApp object, used to influence SCAR's application.

procedure SetOnTop(Window: Integer; Top: Boolean);
Sets a Window ontop if Top is true.

 

Using forms.
Just follow this step by step tutorial and you will get the idea. Preconditions: you should know something about SCAR scripting.
1. Create new script and press SCAR menu Script > Form Editor
2. Drop a button on form somewhere.
3. Save the form and close form editor
4. Press SCAR menu Script > Load DFM form
5. You will get bunch of things in debug box. Copy variable declarations before begin.
6. Create new procedure before main begin
procedure InitForm;
begin
end;
7. Copy the rest form debug box into this procedure starting with frmDesign := CreateForm;
8. Declare new procedure
procedure SafeInitForm;
var
  v: TVariantArray;
begin
  setarraylength(V, 0);
  ThreadSafeCall('InitForm', v);
end;
9. Put call to SafeInitForm in main script
10. Run the script.
11. Ok, let's make it a bit more useful. Declare two procedures:
procedure ShowFormModal;
begin
  frmDesign.ShowModal;
end;

procedure SafeShowFormModal;
var
  v: TVariantArray;
begin
  setarraylength(V, 0);
  ThreadSafeCall('ShowFormModal', v);
end;

12. Put call to SafeShowFormModal in main script so it looks like this:
begin
  SafeInitForm;
  SafeShowFormModal;
end.
13. Remove form visibility. Find line frmDesign.Visible := True; and change True to False.
14. Run script. As you see form is modal and SCAR will freeze while form is open.
15. Let's make button do something. Declare procedure before InitForm declaration:
procedure buttonclick(sender: TObject);
begin
  Writeln('Button pressed!');
  frmDesign.Caption:= frmDesign.Caption + '.';
end;
16. Add line after Button1 := TButton.Create(frmDesign):
Button1.OnClick:= @buttonclick;
17. Run the script. Now when you press the button, it will Writeln and change window title.
18. If you want window to close when button is pressed, add line inside procedure buttonclick:
frmDesign.ModalResult:= mrOk;

Here is my final code

program New;
var
  frmDesign : TForm;
  Button1 : TButton;

procedure buttonclick(sender: TObject);
begin
  Writeln('Button pressed!');
  frmDesign.Caption:= frmDesign.Caption + '.';
  frmDesign.ModalResult:= mrOk;
end;

procedure InitForm;
begin
  frmDesign := CreateForm;
  frmDesign.Left := 259;
  frmDesign.Top := 132;
  frmDesign.Width := 354;
  frmDesign.Height := 254;
  frmDesign.Caption := 'frmDesign';
  frmDesign.Color := clBtnFace;
  frmDesign.Font.Color := clWindowText;
  frmDesign.Font.Height := -11;
  frmDesign.Font.Name := 'MS Sans Serif';
  frmDesign.Font.Style := [];
  frmDesign.Visible := False;
  frmDesign.PixelsPerInch := 96;
  Button1 := TButton.Create(frmDesign);
  Button1.OnClick:= @buttonclick;
  Button1.Parent := frmDesign;
  Button1.Left := 69;
  Button1.Top := 61;
  Button1.Width := 75;
  Button1.Height := 25;
  Button1.Caption := 'Button1';
  Button1.TabOrder := 8;
end;

procedure SafeInitForm;
var
  v: TVariantArray;
begin
  setarraylength(V, 0);
  ThreadSafeCall('InitForm', v);
end;

procedure ShowFormModal;
begin
  frmDesign.ShowModal;
end;

procedure SafeShowFormModal;
var
  v: TVariantArray;
begin
  setarraylength(V, 0);
  ThreadSafeCall('ShowFormModal', v);
end;

begin
  SafeInitForm;
  SafeShowFormModal;
end.

© 2010-2011 Frédéric Hannes