### Full Example of Simba Object Usage Source: https://github.com/villavu/simba/blob/simba2000/DocGen/source/tutorials/Objects.md A comprehensive example demonstrating the definition, construction, and destruction of Simba objects. It includes creating objects within a loop and shows how the 'Destroy' method is automatically invoked. ```pascal type TMyObject = object magic: Integer; end; function TMyObject.Construct(magic: Integer): TMyObject; static; begin Result.magic := magic; end; procedure TMyObject.Destroy; begin WriteLn('Object ', Self.magic, ' is being destroyed'); end; procedure Test(obj: TMyObject); var i: Integer; begin obj := new TMyObject(1); for i := 2 to 4 do obj := new TMyObject(i); end; begin WriteLn('Should free objects 1..4'); Test(new TMyObject(0)); WriteLn('Done'); WriteLn('Should free object 0'); end; ``` -------------------------------- ### Implement KeySend Functionality - Pascal Source: https://github.com/villavu/simba/blob/simba2000/DocGen/source/tutorials/plugins/plugin-target.md Provides an example implementation of the SimbaPluginTarget_KeySend function. This function simulates typing by sending key presses and releases, with configurable delays between each action to control typing speed. ```pascal procedure SimbaPluginTarget_KeySend(Text: PChar; TextLen: Integer; SleepTimes: PInt32); procedure DoSleep; begin PreciseSleep(SleepTimes^); Inc(SleepTimes); end; var I: Integer; begin for I := 0 to TextLen - 1 do begin PressTheKey(); DoSleep(); ReleaseTheKey(); DoSleep(); end; end; ``` -------------------------------- ### Performance Timing with TStopWatch in Pascal Source: https://context7.com/villavu/simba/llms.txt Illustrates the use of the TStopWatch record for measuring code execution time. It shows how to start, pause, resume, and retrieve elapsed time in milliseconds and formatted seconds. ```pascal var StopWatch: TStopWatch; begin StopWatch.Start(); // Code to time Sleep(Random(1500, 3000)); StopWatch.Pause(); // Get elapsed time in different formats WriteLn('Milliseconds: ', StopWatch.Elapsed); WriteLn('Seconds: ', StopWatch.ElapsedFmt('s')); // Resume timing StopWatch.Start(); Sleep(500); StopWatch.Pause(); WriteLn('Total time: ', StopWatch.Elapsed, 'ms'); end. ``` -------------------------------- ### Registering Simba Plugins Source: https://github.com/villavu/simba/blob/simba2000/DocGen/source/tutorials/plugins/writing-plugins.md The entry point for a Simba plugin. This procedure is exported by the plugin and provides Simba with access to plugin information and methods. It receives pointers to TSimbaInfomation and TSimbaMethods structures. ```pascal procedure RegisterSimbaPlugin(Infomation: PSimbaInfomation; Methods: PSimbaMethods); cdecl; ``` -------------------------------- ### Simba Plugin Function Registration in C++ Source: https://github.com/villavu/simba/blob/simba2000/DocGen/source/tutorials/plugins/plugin-cpp.md Exposes the functions available in the Simba plugin. GetFunctionCount returns the total number of functions, and GetFunctionInfo provides the address and definition of a specific function based on its index. ```c++ int GetFunctionCount() { return 3; } int GetFunctionInfo(int Index, void** Address, char** Definition) { switch(Index) { case 0: strcpy(*Definition, "function GetIntArray(Count: Int32): array of Int32; native;"); *Address = (void*)GetIntArray; break; case 1: strcpy(*Definition, "function GetRecord: TMyRecord; native;"); *Address = (void*)GetRecord; break; case 2: strcpy(*Definition, "function GetArrayOfRecord: array of TMyRecord; native;"); *Address = (void*)GetArrayOfRecord; break; } return Index; } ``` -------------------------------- ### Memory Read/Write Utilities in C++ Source: https://github.com/villavu/simba/blob/simba2000/DocGen/source/tutorials/plugins/plugin-cpp.md Provides generic functions MemWrite and MemRead for reading and writing data of any type to/from memory pointers. These functions utilize memcpy for efficient memory operations and are marked noexcept for performance. ```c++ #include "main.h" #include "stdio.h" #include template void MemWrite(void* ptr, int offset, T item) noexcept { memcpy((char*)ptr+offset, &item, sizeof(T)); } template T MemRead(void* ptr) noexcept { T result; memcpy(&result, ptr, sizeof(T)); return result; } ``` -------------------------------- ### GUI Form Creation with TLazForm in Pascal Source: https://context7.com/villavu/simba/llms.txt Demonstrates building a graphical user interface using Simba's TLazForm components. This example shows how to create a form, add buttons and list boxes, handle events like button clicks and selection changes, and display the form. ```pascal var Form: TLazForm; Button: TLazButton; List: TLazListBox; procedure DoButtonClick(Sender: TLazObject); begin WriteLn('Button clicked: ', TLazButton(Sender).Caption); if TLazButton(Sender).Caption = 'Close' then Form.Close(); end; procedure DoSelectionChange(Sender: TLazObject; User: Boolean); begin WriteLn('Selected: ', TLazListBox(Sender).GetSelectedText()); end; begin Form := TLazForm.Create(); Form.Caption := 'My Simba Form'; Form.Width := 400; Form.Height := 300; Form.Position := ELazFormPosition.ScreenCenter; Form.Color := Colors.DARK_GREY; Form.BorderStyle := ELazFormBorderStyle.Single; Button := TLazButton.Create(Form); Button.Parent := Form; Button.SetBounds(150, 200, 100, 30); Button.Caption := 'Close'; Button.OnClick := @DoButtonClick; List := TLazListBox.Create(Form); List.Parent := Form; List.SetBounds(50, 50, 300, 120); List.Items.Add('Item 1'); List.Items.Add('Item 2'); List.Items.Add('Item 3'); List.OnSelectionChange := @DoSelectionChange; Form.ShowModal(); WriteLn('Form closed'); end. ``` -------------------------------- ### Simba Plugin Type Information in C++ Source: https://github.com/villavu/simba/blob/simba2000/DocGen/source/tutorials/plugins/plugin-cpp.md Provides functions to retrieve information about the types exposed by the Simba plugin. GetTypeCount returns the number of types, and GetTypeInfo provides the name and definition of a specific type by its index. ```c++ int GetTypeCount() { return 1; } int GetTypeInfo(int Index, char** Name, char** Definition) { switch(Index) { case 0: strcpy(*Name, "TMyRecord"); strcpy(*Definition, "record i: Int32; str: String; end;"); break; } return Index; } ``` -------------------------------- ### Simba Plugin Initialization and Type Registration in C++ Source: https://github.com/villavu/simba/blob/simba2000/DocGen/source/tutorials/plugins/plugin-cpp.md Handles the initialization of the Simba plugin by setting global pointers for Simba information and methods. It also registers a custom record type 'TMyRecord' and an array of 'TMyRecord' with Simba, retrieving their type information, size, and field offsets. ```c++ void* ARR_TYPEINFO = 0; void* REC_TYPEINFO = 0; NativeUInt REC_SIZE = 0; NativeUInt REC_STR_OFFSET = 0; void RegisterSimbaPlugin(TSimbaInfo* Info, TSimbaMethods* Methods) { SIMBA_INFO = Info; SIMBA_METHODS = Methods; REC_TYPEINFO = SIMBA_METHODS->GetTypeInfo(SIMBA_INFO->Compiler, (char*)"TMyRecord"); REC_SIZE = SIMBA_METHODS->GetTypeInfoSize(REC_TYPEINFO); REC_STR_OFFSET = SIMBA_METHODS->GetTypeInfoFieldOffset(REC_TYPEINFO, (char*)"str"); ARR_TYPEINFO = SIMBA_METHODS->GetTypeInfo(SIMBA_INFO->Compiler, (char*)"array of TMyRecord"); } ``` -------------------------------- ### Simba Package Configuration (.simbapackage) Source: https://github.com/villavu/simba/blob/simba2000/PACKAGES.md Configuration options for a Simba package, defined in a .simbapackage file. These options control installation behavior, ignored files/directories, and script/example inclusions. ```plaintext path=Includes/TestPackage flat=false ignore=dir ignore=bad.simba ignore=.git script=script.simba script=script2.simba example=example.simba example=example2.simba ``` -------------------------------- ### Simba Function: GetRecord in C++ Source: https://github.com/villavu/simba/blob/simba2000/DocGen/source/tutorials/plugins/plugin-cpp.md Implements the GetRecord function for the Simba plugin. This function creates and returns a 'TMyRecord' structure, setting an integer field to a fixed value and a string field to 'Hello world'. ```c++ void GetRecord(void** Params, void** Result) { MemWrite(Result, 0, 123456); MemWrite(Result, REC_STR_OFFSET, SIMBA_METHODS->AllocateString((char*)"Hello world")); } ``` -------------------------------- ### Network Communication with TInternetSocket in Pascal Source: https://context7.com/villavu/simba/llms.txt Demonstrates establishing TCP network connections using Simba's TInternetSocket. This example connects to an IRC server, sends basic commands, and receives/processes responses, including handling PING/PONG messages. ```pascal var Sock: TInternetSocket; begin // Create socket connection (host, port, SSL) Sock := TInternetSocket.Create('irc.example.net', 6667, False); Sock.Connect(); // Send data Sock.WriteString('NICK SimbaBot' + #13#10); Sock.WriteString('USER SimbaBot * * *' + #13#10); // Receive data while True do begin if Sock.HasData() then begin var Response := Sock.ReadString(); for var Line in Response.Split(#13#10) do begin WriteLn(Line); // Respond to PING if Line.StartsWith('PING') then Sock.WriteString(Line.Replace('PING', 'PONG') + #13#10); end; end; Sleep(100); end; Sock.Free(); end. ``` -------------------------------- ### Simba 2.0 Property Declaration and Usage in Pascal Source: https://github.com/villavu/simba/blob/simba2000/DocGen/source/tutorials/Properties.md Demonstrates how to declare and use getter and setter properties in Pascal for Simba 2.0. This example shows a read-write property 'SomeValue' that converts between an Integer and a String within a record type. ```pascal type TMyRecord = record Str: String; end; property TMyRecord.SomeValue: Integer; begin Result := StrToInt(Self.Str); end; property TMyRecord.SomeValue(NewValue: Integer); begin Self.Str := IntToStr(NewValue); end; var myRecord: TMyRecord; begin myRecord.SomeValue := 123; WriteLn myRecord.SomeValue; end; ``` -------------------------------- ### Simba Plugin C++ Header Definitions Source: https://github.com/villavu/simba/blob/simba2000/DocGen/source/tutorials/plugins/plugin-cpp.md This C++ header file defines the core structures and function prototypes for a Simba plugin. It includes platform-specific export macros, type definitions for native integers, and packed structures for Simba information and methods. These are crucial for the Simba runtime to interact with the plugin. ```cpp #ifndef __MAIN_H__ #define __MAIN_H__ #include #if defined(_WIN32) || defined(_WIN64) #define EXPORT __declspec(dllexport) #else #define EXPORT [[gnu::visibility("default")]] #endif #if INTPTR_MAX == INT32_MAX typedef int32_t NativeInt; typedef uint32_t NativeUInt; #else typedef int64_t NativeInt; typedef uint64_t NativeUInt; #endif struct __attribute__((__packed__)) TSimbaInfo { int SimbaVersion; int SimbaMajor; char* FileName; void* Compiler; }; struct __attribute__((__packed__)) TSimbaMethods { void (*RunOnMainThread)(void(*TMainThreadMethod)(void*), void* data); void* (*GetMem)(std::size_t size); void (*FreeMem)(void* ptr); void* (*AllocMem)(std::size_t size); void* (*ReAllocMem)(void** ptr, std::size_t size); std::size_t (*MemSize)(void* ptr); void(*RaiseException)(const char* message); void* (*GetTypeInfo)(void* Compiler, const char* Type); void* (*GetTypeInfoSize)(void* TypeInfo); std::size_t (*GetTypeInfoFieldOffset)(void* TypeInfo, const char* FieldName); void* (*AllocateRawArray)(std::size_t element_size, std::size_t length); void (*ReAllocateRawArray)(void** array, std::size_t element_size, std::size_t new_length); void* (*AllocateArray)(void* TypeInfo, std::size_t length); void* (*AllocateString)(const char* data); void* (*AllocateUnicodeString)(const wchar_t* data); void (*SetArrayLength)(void* TypeInfo, void** var, std::size_t new_len); std::size_t (*GetArrayLength)(void* array); void* (*ExternalImage_Create)(bool AutoResize); void (*ExternalImage_SetMemory)(void* img, void* bgra_data, std::int32_t width, std::int32_t height); void (*ExternalImage_Resize)(void* img, std::int32_t new_width, std::int32_t new_height); void (*ExternalImage_SetUserData)(void* img, void* userdata); void* (*ExternalImage_GetUserData)(void* img); }; TSimbaInfo* SIMBA_INFO = {0}; TSimbaMethods* SIMBA_METHODS = {0}; extern "C" { EXPORT int GetTypeCount(); EXPORT int GetTypeInfo(int Index, char** Name, char** Definition); EXPORT int GetFunctionCount(); EXPORT int GetFunctionInfo(int Index, void** Address, char** Definition); EXPORT void RegisterSimbaPlugin(TSimbaInfo* Information, TSimbaMethods* Methods); } #endif // __MAIN_H__ ``` -------------------------------- ### FindColor with TColorTolerance Record (Pascal) Source: https://github.com/villavu/simba/wiki/Colorfinding This Pascal method simplifies color searching by accepting a single TColorTolerance record, which encapsulates color, tolerance, colorspace, and multipliers. This is useful for storing and reusing search configurations. The example demonstrates initializing and using this method. ```pascal Target.FindColor(Color: TColorTolerance; Bounds: TBox = [-1,-1,-1,-1]): TPointArray; TColorTolerance = record Color: TColor; Tolerance: Single; Colorspace: EColorSpace; Multipliers: array [0..2] of Single; end; var SimbaIcon: TColorTolerance; TPA: TPointArray; begin SimbaIcon := ColorTolerance($1044BE, 10.592, EColorSpace.HSL, [1.073, 1.138, 0.791]); TPA := Target.FindColor(SimbaIcon, [0,0,400,400]); if Length(TPA) > 0 then begin WriteLn('Found: ', Length(TPA), ' points'); end; end. ``` -------------------------------- ### Importing Simba Code Source: https://github.com/villavu/simba/blob/simba2000/DocGen/source/tutorials/plugins/writing-plugins.md Exports functions to allow Simba to import code from plugins. GetCode retrieves the code as a character pointer, and GetCodeLength returns the length of the code. These are essential for incorporating custom logic into Simba scripts. ```pascal procedure GetCode(var Code: PChar); cdecl; function GetCodeLength: Integer; cdecl; ``` -------------------------------- ### Importing Simba Functions Source: https://github.com/villavu/simba/blob/simba2000/DocGen/source/tutorials/plugins/writing-plugins.md Exports functions that provide Simba with information about available functions. GetFunctionInfo retrieves details for a specific function index, while GetFunctionCount returns the total number of functions. The cdecl calling convention is mandatory for these functions. ```pascal function GetFunctionInfo(Index: Integer; var Address: Pointer; var Header: PChar): Integer; cdecl; function GetFunctionCount: Integer; cdecl; ``` -------------------------------- ### Simba Function: GetArrayOfRecord in C++ Source: https://github.com/villavu/simba/blob/simba2000/DocGen/source/tutorials/plugins/plugin-cpp.md Implements the GetArrayOfRecord function for the Simba plugin. This function creates and returns an array of 'TMyRecord' structures. Each record in the array is populated with an integer and a string, demonstrating dynamic string allocation within the array. ```c++ void GetArrayOfRecord(void** Params, void** Result) { char str0[] = "Hello in array index 0"; char str1[] = "Hola in array index 1"; char str2[] = "Bonjour in array index 2"; void* mem = SIMBA_METHODS->AllocateArray(ARR_TYPEINFO, 3); for (int i=0; i<3; i++) { void* str = nullptr; switch (i) { case 0: str = SIMBA_METHODS->AllocateString((void*)str0); break; case 1: str = SIMBA_METHODS->AllocateString((void*)str1); break; case 2: str = SIMBA_METHODS->AllocateString((void*)str2); break; } // write arr[i].i MemWrite(mem, i*REC_SIZE, i); // write arr[i].str MemWrite(mem, (i*REC_SIZE)+REC_STR_OFFSET, str); } MemWrite(Result, 0, mem); } ``` -------------------------------- ### SleepUntil Example: Waiting for Random Condition (Simba Pascal) Source: https://github.com/villavu/simba/blob/simba2000/DocGen/source/tutorials/Sleep Until.md Demonstrates using SleepUntil to wait for a random number to equal 1 within a 5-second timeout, checking every 50 milliseconds. This showcases a simple boolean expression as the condition. ```pascal if SleepUntil(Random(100) = 1, 50, 5000) then WriteLn('Random(100) returned 1 within 5 seconds (checked every 50ms)!'); ``` -------------------------------- ### TSimbaInfomation Structure Source: https://github.com/villavu/simba/blob/simba2000/DocGen/source/tutorials/plugins/writing-plugins.md A packed record containing information about the Simba environment. It includes the Simba version, major version, the script file name, and a pointer to the compiler. ```pascal TSimbaInfomation = packed record SimbaVersion: Integer; SimbaMajor: Integer; FileName: PChar; Compiler: Pointer; end; ``` -------------------------------- ### Simba Function: GetIntArray in C++ Source: https://github.com/villavu/simba/blob/simba2000/DocGen/source/tutorials/plugins/plugin-cpp.md Implements the GetIntArray function for the Simba plugin. This function takes a count as input and returns a dynamically allocated array of integers, where each element is initialized with its index. ```c++ void GetIntArray(void** Params, void** Result) { int Count = MemRead(*Params); void* Arr = SIMBA_METHODS->AllocateRawArray(sizeof(int32_t), Count); for (int i=0; i(Result, 0, Arr); } ``` -------------------------------- ### Constructing a Simba Object Source: https://github.com/villavu/simba/blob/simba2000/DocGen/source/tutorials/Objects.md Demonstrates how to create a new object instance using the 'new' keyword in Simba Pascal. This is the standard way to instantiate objects that are automatically managed. ```pascal obj := new TMyObject(); ``` -------------------------------- ### TSimbaMethods Structure Source: https://github.com/villavu/simba/blob/simba2000/DocGen/source/tutorials/plugins/writing-plugins.md A packed record containing pointers to various Simba methods accessible by plugins. This includes memory management, exception handling, type information retrieval, array manipulation, and image handling. ```pascal TSimbaMethods = packed record RunOnMainThread: procedure(Method: TMainThreadMethod; Data: Pointer = nil); cdecl; GetMem: function(Size: NativeUInt): Pointer; cdecl; FreeMem: function(P: Pointer): NativeUInt; cdecl; AllocMem: function(Size: NativeUInt): Pointer; cdecl; ReAllocMem: function(var P: Pointer; Size: NativeUInt): Pointer; cdecl; MemSize: function(P: Pointer): NativeUInt; cdecl; RaiseException: procedure(Message: PChar); cdecl; GetTypeInfo: function(Compiler: Pointer; Typ: PChar): Pointer; cdecl; GetTypeInfoSize: function(TypeInfo: Pointer): NativeInt; cdecl; GetTypeInfoFieldOffset: function(TypeInfo: Pointer; FieldName: PChar): NativeInt; cdecl; AllocateRawArray: function(ElementSize, Len: NativeInt): Pointer; cdecl; ReAllocateRawArray: procedure(var Arr: Pointer; ElementSize, NewLen: NativeInt); cdecl; AllocateArray: function(TypeInfo: Pointer; Len: NativeInt): Pointer; cdecl; AllocateString: function(Data: PChar): Pointer; cdecl; AllocateUnicodeString: function(Data: PUnicodeChar): Pointer; cdecl; SetArrayLength: procedure(TypeInfo: Pointer; var AVar: Pointer; NewLen: NativeInt); cdecl; GetArrayLength: function(AVar: Pointer): NativeInt; cdecl; ExternalImage_Create: function(AutoResize: Boolean): Pointer; cdecl; ExternalImage_SetMemory: procedure(Img: Pointer; Data: PColorBGRA; AWidth, AHeight: Integer); cdecl; ExternalImage_Resize: procedure(Img: Pointer; NewWidth, NewHeight: Integer); cdecl; ExternalImage_SetUserData: procedure(Img: Pointer; UserData: Pointer); cdecl; ExternalImage_GetUserData: function(Img: Pointer): Pointer; cdecl; end; ``` -------------------------------- ### Library Loading and Checking with Pascal Preprocessor Source: https://github.com/villavu/simba/blob/simba2000/DocGen/source/tutorials/Preprocessor.md Illustrates using {$IF FINDLIB}, {$loadlib}, and {$IF LOADEDLIB} directives in Pascal to manage external libraries during compilation. ```pascal {$IF FINDLIB(libremoteinput)} {$loadlib libremoteinput} {$ELSE} WriteLn('Cannot find libremoteinput!'); {$ENDIF} {$IF LOADEDLIB(libremoteinput)} WriteLn('libremoteinput is loaded'); {$ELSE} WriteLn('libremoteinput is *not* loaded'); {$ENDIF} ``` -------------------------------- ### Simba Properties: Getter and Setter Methods for Records/Objects Source: https://context7.com/villavu/simba/llms.txt Illustrates how to define properties in Simba using getter and setter methods for records and objects. This allows field-like syntax for accessing and modifying underlying data, providing encapsulation and controlled data access. ```pascal type TMyRecord = record _value: String; end; property TMyRecord.NumericValue: Integer; begin Result := StrToInt(Self._value); end; property TMyRecord.NumericValue(NewValue: Integer); begin Self._value := IntToStr(NewValue); end; var rec: TMyRecord; begin rec.NumericValue := 42; // Calls setter WriteLn(rec.NumericValue); // Calls getter, outputs: 42 WriteLn(rec._value); // Direct access, outputs: '42' end. ``` -------------------------------- ### FindColor with Full Parameters (Pascal) Source: https://github.com/villavu/simba/wiki/Colorfinding This Pascal method searches for a specific color within a target area using detailed parameters. It allows precise control over color, tolerance, colorspace, channel multipliers, and search bounds. Dependencies include TColor, TChannelMultipliers, TBox, and EColorSpace types. ```pascal Target.FindColor(Color: TColor; Tolerance: Single; ColorSpace: EColorSpace; Multipliers: TChannelMultipliers; Bounds: TBox = [-1,-1,-1,-1]): TPointArray; ``` -------------------------------- ### JSON Parsing and Creation in Pascal Source: https://context7.com/villavu/simba/llms.txt Demonstrates how to parse JSON strings into TJSONItem objects and create new JSON structures using Simba's built-in JSON support. It covers accessing values by key, iterating through items, and constructing complex JSON objects and arrays. ```pascal const SOME_JSON = '{ "streetAddress": "456 Main St", ' + ' "postalCode": 12345, ' + ' "open": true }'; var json, jsonArr, jsonObj: TJSONItem; parser: TJSONParser; street: String; postal: Int64; begin // Parse JSON string parser := new TJSONParser(); parser.Parse(SOME_JSON); // Get values by key with type checking if parser.GetString('streetAddress', street) then WriteLn('Address: ', street); if parser.GetInt('postalCode', postal) then WriteLn('Postal: ', postal); // Direct item access WriteLn(parser.Item['streetAddress'].AsString); WriteLn(parser.Item['postalCode'].AsInt); // Iterate over items for var I := 0 to parser.Count - 1 do begin WriteLn('Key: ', parser.Key[I], ' Type: ', parser.Item[I].Typ); end; // Create JSON structure json := new TJSONObject(); json.AddString('name', 'Simba'); json.AddInt('version', 2000); json.AddFloat('pi', 3.14159); json.AddBool('active', True); jsonArr := new TJSONArray(); jsonArr.AddInt('', 1); jsonArr.AddInt('', 2); jsonArr.AddInt('', 3); json.AddArray('numbers', jsonArr); jsonObj := new TJSONObject(); jsonObj.AddString('key', 'value'); json.AddObject('nested', jsonObj); WriteLn(json.Format()); end. ``` -------------------------------- ### Simba Keyboard Input with KeySend and KeyPress Source: https://context7.com/villavu/simba/llms.txt Simulates human-like keyboard typing with configurable key press durations. `KeySend` types text naturally, while `KeyPress`, `KeyDown`, and `KeyUp` offer low-level key control. Supports keyboard shortcuts and checking key states. ```pascal begin // Configure key timing for natural typing Target.KeyOptions.MinPressTime := 30; Target.KeyOptions.MaxPressTime := 80; // Type text naturally (handles shift for uppercase automatically) Target.KeySend('Hello World!'); // Single key press with automatic timing Target.KeyPress(EKeyCode.ENTER); // Manual key hold for precise control Target.KeyDown(EKeyCode.SHIFT); Sleep(50); Target.KeyUp(EKeyCode.SHIFT); // Keyboard shortcuts Target.KeyDown(EKeyCode.CTRL); Target.KeyPress(EKeyCode.C); // Copy Target.KeyUp(EKeyCode.CTRL); // Check key state if Target.KeyPressed(EKeyCode.A) then WriteLn('A key is pressed'); end. ``` -------------------------------- ### Simulate Keyboard Key Press and Release (Pascal) Source: https://github.com/villavu/simba/blob/simba2000/DocGen/source/tutorials/Mouse & Keyboard.md Manually simulates pressing and releasing the SHIFT key with a fixed delay of 50 milliseconds between the press and release events. ```pascal Target.KeyDown(EKeyCode.SHIFT) Sleep(50); Target.KeyUp(EKeyCode.SHIFT); ``` -------------------------------- ### Importing Simba Types Source: https://github.com/villavu/simba/blob/simba2000/DocGen/source/tutorials/plugins/writing-plugins.md Exports functions to provide Simba with type information. GetTypeInfo retrieves details for a specific type index, and GetTypeCount returns the total number of types. These functions must be exported before function and code importing functions. ```pascal function GetTypeInfo(Index: Integer; var Name: PChar; var Str: PChar): Integer; cdecl; function GetTypeCount: Integer; cdecl; ``` -------------------------------- ### SleepUntil Example: Complex Condition (Simba Pascal) Source: https://github.com/villavu/simba/blob/simba2000/DocGen/source/tutorials/Sleep Until.md Illustrates a more complex condition for SleepUntil, combining two random number checks with a time-based condition. The execution waits until the sum of two random numbers equals 5 AND the running time exceeds 500 milliseconds. ```pascal SleepUntil((Random(5)+Random(5) = 5) and (GetTimeRunning() > 500), 50, 5000); ``` -------------------------------- ### Simulate Mouse Press and Release (Pascal) Source: https://github.com/villavu/simba/blob/simba2000/DocGen/source/tutorials/Mouse & Keyboard.md Manually simulates pressing and releasing the left mouse button with a fixed delay of 50 milliseconds between the press and release events. ```pascal Target.MouseDown(EMouseButton.LEFT); Sleep(50); Target.MouseUp(EMouseButton.LEFT); ``` -------------------------------- ### FindColor with Full Parameters (Pascal) Source: https://github.com/villavu/simba/blob/simba2000/DocGen/source/tutorials/Color Finding.md This method allows for precise color searching by accepting individual parameters for color, tolerance, colorspace, multipliers, and bounds. It returns an array of points where the color is found. The `Bounds` parameter defines the search area. ```pascal finder.FindColor(Color: TColor; Tolerance: Single; ColorSpace: EColorSpace; Multipliers: TChannelMultipliers; Bounds: TBox = [-1,-1,-1,-1]): TPointArray; ``` -------------------------------- ### Generate Random Numbers with Various Distributions - Pascal Source: https://context7.com/villavu/simba/llms.txt Simba provides diverse random number generators for creating human-like behavior in scripts. These include uniform, left-weighted, right-weighted, mean-weighted (bell curve), and mode-weighted distributions. Examples demonstrate generating floats, integers, and testing distributions. ```pascal var Hits: TIntegerArray; I: Integer; begin // Uniform distribution WriteLn('Random float 0-1: ', Random); WriteLn('Random int 0-99: ', Random(100)); WriteLn('Random float 5.0-10.0: ', Random(5.0, 10.0)); WriteLn('Random int 50-100: ', Random(50, 100)); // Weighted towards minimum value WriteLn('RandomLeft 0-100: ', RandomLeft(0, 100)); // Weighted towards maximum value WriteLn('RandomRight 0-100: ', RandomRight(0, 100)); // Weighted towards mean (bell curve) WriteLn('RandomMean 0-100: ', RandomMean(0, 100)); // Weighted towards specific mode value WriteLn('RandomMode 25 in 0-100: ', RandomMode(25, 0, 100)); // Distribution test SetLength(Hits, 10); for I := 1 to 100000 do Hits[RandomLeft(0, 10)] += 1; for I := 0 to High(Hits) do WriteLn(I, ': ', Round((Hits[I] / 100000) * 100, 2), '%'); end. ``` -------------------------------- ### Declare and Use TTarget Variables for Window Interaction Source: https://github.com/villavu/simba/blob/simba2000/DocGen/source/tutorials/Targets.md Demonstrates how to declare custom TTarget variables, set them to specific window handles, and perform operations like counting colors within the target window. Requires a valid window handle. ```pascal var MyOtherTarget: TTarget; begin MyOtherTarget.SetWindow(12345); // some window handle WriteLn MyOtherTarget.CountColor($0000FF, 10); // Count a red color, with 10 tolerance. end; ``` -------------------------------- ### FindColor with Full Parameters Source: https://github.com/villavu/simba/wiki/Colorfinding Searches for a specific color within a target area using detailed parameters for color, tolerance, colorspace, multipliers, and bounds. ```APIDOC ## POST /villavu/simba/FindColor ### Description Searches for a specific color within a target area using detailed parameters for color, tolerance, colorspace, multipliers, and bounds. ### Method POST ### Endpoint /villavu/simba/FindColor ### Parameters #### Request Body - **Color** (Integer) - Required - The color to search for. - **Tolerance** (Single) - Required - The tolerance needed to find color shades. - **ColorSpace** (EColorSpace) - Required - Defines the colorspace's distance metric used in the search (RGB, HSL, HSV, XYZ, LAB, LCH, DeltaE). - **Multipliers** (TChannelMultipliers) - Required - Defines the channel multipliers. - **Bounds** (TBox) - Optional - The search area on the target `left, top, right, bottom`. Defaults to `[-1,-1,-1,-1]`. ### Request Example ```json { "Color": "0x1044BE", "Tolerance": 10.592, "ColorSpace": "HSL", "Multipliers": [1.073, 1.138, 0.791], "Bounds": [0, 0, 400, 400] } ``` ### Response #### Success Response (200) - **TPointArray** (Array of Points) - An array of points where the color was found. #### Response Example ```json { "Points": [ {"X": 10, "Y": 20}, {"X": 30, "Y": 40} ] } ``` ``` -------------------------------- ### Simba 2.0 Preprocessor Directives and Compile-Time Macros Source: https://context7.com/villavu/simba/llms.txt Demonstrates Simba 2.0's preprocessor directives like {$DEFINE}, {$IF}, {$ENDIF}, {$ELSE}, {$FILEEXISTS}, and compile-time macros such as {$MACRO LINE}, {$MACRO FILE}, {$MACRO DIR}, {$MACRO NOW}, and {$MACRO ENV}. These allow for conditional compilation and access to build-time information. ```pascal {$DEFINE DEBUG} const VERSION = 2; begin {$IF VERSION >= 2} WriteLn('Running Simba 2.0 or later'); {$ENDIF} {$IF DECLARED(VERSION) and DEFINED(DEBUG)} WriteLn('Debug mode enabled, version: ', VERSION); {$ELSE} WriteLn('Release mode'); {$ENDIF} {$IF FILEEXISTS(Data\settings.ini)} WriteLn('Settings file found'); {$ENDIF} // Compile-time macros WriteLn('Line number: ', {$MACRO LINE}); WriteLn('Current file: ', {$MACRO FILE}); WriteLn('Current directory: ', {$MACRO DIR}); WriteLn('Timestamp: ', {$MACRO NOW}); WriteLn('User profile: ', {$MACRO ENV(USERPROFILE)}); {$UNDEF DEBUG} end. ``` -------------------------------- ### External Package Version Data (JSON) Source: https://github.com/villavu/simba/blob/simba2000/PACKAGES.md JSON array defining version-specific data for an external package. Each object includes download URL, options URL, release notes, timestamp, and version name. ```json [ { "download_url" : "www.test.com/files.zip", "options_url" : "www.test.com/.simbapackage", "notes" : "notes about this version", "time" : "unixtimestamp", "name" : "versionname" }, { "download_url" : "www.test.com/files.zip", "options_url" : "www.test.com/.simbapackage", "notes" : "notes about this version", "time" : "unixtimestamp", "name" : "versionname" } ] ``` -------------------------------- ### FindColor with Default Adjusters Source: https://github.com/villavu/simba/wiki/Colorfinding Searches for a specific color using default colorspace and multipliers. Requires color, tolerance, and bounds. ```APIDOC ## POST /villavu/simba/FindColor ### Description Searches for a specific color using default colorspace and multipliers. Requires color, tolerance, and bounds. ### Method POST ### Endpoint /villavu/simba/FindColor ### Parameters #### Request Body - **Color** (Integer) - Required - The color to search for. - **Tolerance** (Single) - Required - The tolerance needed to find color shades. - **Bounds** (TBox) - Optional - The search area on the target `left, top, right, bottom`. Defaults to `[-1,-1,-1,-1]`. ### Request Example ```json { "Color": "0x1044BE", "Tolerance": 10.592, "Bounds": [0, 0, 400, 400] } ``` ### Response #### Success Response (200) - **TPointArray** (Array of Points) - An array of points where the color was found. #### Response Example ```json { "Points": [ {"X": 10, "Y": 20}, {"X": 30, "Y": 40} ] } ``` ``` -------------------------------- ### Load Plugin Target - Pascal Source: https://github.com/villavu/simba/blob/simba2000/DocGen/source/tutorials/plugins/plugin-target.md Loads a plugin DLL and sets it as the target for script operations. The plugin must export specific functions for interaction. Arguments can be passed to the plugin during loading. ```pascal Target.SetPlugin('myplugin.dll', 'someargs') ``` -------------------------------- ### Compile-time Macro Insertion in Pascal Source: https://github.com/villavu/simba/blob/simba2000/DocGen/source/tutorials/Preprocessor.md Demonstrates the use of various {$MACRO} directives in Pascal to insert compile-time constants such as function names, line numbers, timestamps, file paths, and environment variables. ```pascal procedure Test; begin WriteLn('Func=', {$MACRO FUNC}); // current function name end; begin Test(); end; ``` ```pascal begin WriteLn {$MACRO LINE}; // The line number WriteLn {$MACRO TICKCOUNT}; // GetTickCount WriteLn {$MACRO NOW}; // TDateTime.Now() WriteLn {$MACRO FILE}; // current file WriteLn {$MACRO DIR}; // directory the current file is in WriteLn {$MACRO ENV(USERPROFILE)}; // environment variable WriteLn {$MACRO INCLUDEDFILES}; // all included files (as a TStringArray) WriteLn {$MACRO LOADEDLIB(libremoteinput)}; // if lib "libremoteinput" is loaded, return the filename of the lib. WriteLn {$MACRO LOADEDLIBS}; // all loaded libs (as a TStringArray) WriteLn {$MACRO FINDLIB(libremoteinput)}; // try to find a lib, returning the path end; ``` -------------------------------- ### Simulate Mouse Click with Variable Duration (Pascal) Source: https://github.com/villavu/simba/blob/simba2000/DocGen/source/tutorials/Mouse & Keyboard.md Simulates a mouse click using the left button. The duration the button is held down is randomized between TTarget.MouseOptions.MinClickTime and TTarget.MouseOptions.MaxClickTime. ```pascal Target.MouseClick(EMouseButton.LEFT); ``` -------------------------------- ### Find Edges on an Image using TTarget Source: https://github.com/villavu/simba/blob/simba2000/DocGen/source/tutorials/Targets.md Shows how to target an image using TTarget and then find edges within that image. This can be done by explicitly setting the image to the target or by using the TImage.Target property. ```pascal var MyTarget: TTarget; MyTarget.SetImage(MyImage); Edges := MyTarget.FindEdges(5); ``` ```pascal Edges := MyImage.Target.FindEdges(5); ``` -------------------------------- ### Simulate Keyboard Press with Variable Duration (Pascal) Source: https://github.com/villavu/simba/blob/simba2000/DocGen/source/tutorials/Mouse & Keyboard.md Simulates pressing the SHIFT key. The duration the key is held down is randomized between TTarget.KeyOptions.MinPressTime and TTarget.KeyOptions.MaxPressTime. ```pascal Target.KeyPress(EKeyCode.SHIFT); ``` -------------------------------- ### Declaring Construct and Destructor Methods for Simba Objects Source: https://github.com/villavu/simba/blob/simba2000/DocGen/source/tutorials/Objects.md Illustrates how to declare and define the 'Construct' and 'Destroy' methods for a Simba object. The 'Construct' method is used for initialization and returns the object instance, while 'Destroy' is called automatically when the object goes out of scope. ```pascal function TMyObject.Construct(magic: Integer): TMyObject; static; begin Result.magic := magic; end; procedure TMyObject.Destroy; begin WriteLn('Object ', Self.magic, ' is being destroyed'); end; ``` -------------------------------- ### Detect Keyboard and Mouse Button State (Pascal) Source: https://github.com/villavu/simba/blob/simba2000/DocGen/source/tutorials/Mouse & Keyboard.md Checks and prints the current pressed state of the 'A' keyboard key and the left mouse button. ```pascal WriteLn Target.KeyPressed(EKeyCode.A); WriteLn Target.MousePressed(EMouseButton.LEFT) ``` -------------------------------- ### External Package Metadata (JSON) Source: https://github.com/villavu/simba/blob/simba2000/PACKAGES.md JSON structure for defining metadata of a package hosted outside of Github. This includes general information about the package. ```json { "name" : "My package name", "full_name" : "Something/My package name", "description" : "This is a test package", "homepage_url" : "www.test.com" } ``` -------------------------------- ### Object Auto-Destruction in Pascal (Simba 2.0) Source: https://context7.com/villavu/simba/llms.txt Explains and demonstrates Simba 2.0's feature of ref-counted objects with automatic constructor and destructor calls. This eliminates manual memory management for custom object types, ensuring resources are freed automatically when objects go out of scope. ```pascal type TMyObject = object Name: String; Value: Integer; end; function TMyObject.Construct(AName: String; AValue: Integer): TMyObject; static; begin Result.Name := AName; Result.Value := AValue; WriteLn('Created: ', AName); end; procedure TMyObject.Destroy; begin WriteLn('Destroyed: ', Self.Name); end; procedure ProcessObjects; var obj: TMyObject; begin obj := new TMyObject('First', 1); obj := new TMyObject('Second', 2); // First is auto-destroyed WriteLn('Processing: ', obj.Name); end; // Second is auto-destroyed when going out of scope begin ProcessObjects(); WriteLn('All objects cleaned up automatically'); end. ``` -------------------------------- ### Conditional Compilation with Basic Expressions in Pascal Source: https://github.com/villavu/simba/blob/simba2000/DocGen/source/tutorials/Preprocessor.md Demonstrates conditional compilation using {$DEFINE}, {$IF}, {$ELSE}, {$ENDIF}, and {$UNDEF} directives in Pascal. It checks constant values and defined symbols. ```pascal {$DEFINE TEST} const XYZ = 100; begin {$IF XYZ = 100} WriteLn('XYZ = 100'); {$ENDIF} {$IF XYZ*2+1 > 200} WriteLn('XYZ*2 > 200'); {$ENDIF} {$IF DECLARED(XYZ) and DEFINED(TEST)} WriteLn('True'); {$ELSE} WriteLn('False'); {$ENDIF} {$UNDEF TEST} {$IF DECLARED(XYZ) and DEFINED(TEST)} WriteLn('True'); {$ELSE} WriteLn('False'); {$ENDIF} end; ``` -------------------------------- ### Define RGB Multiplier in Pascal Source: https://github.com/villavu/simba/blob/simba2000/DocGen/source/tutorials/Color Finding.md Demonstrates how to define a multiplier for the RGB colorspace in Pascal. This allows for weighting different color channels to influence the distance calculation. The multiplier values can be interpreted as percentages, indicating the relative importance of each channel to the overall color difference. ```pascal MyRGBMultiplier := [2, 0.1, 2]; ``` ```pascal MyRGBMultiplier := [60, 10, 30]; ``` -------------------------------- ### Simba Mouse Control with MouseMove and MouseClick Source: https://context7.com/villavu/simba/llms.txt Provides instant and human-like mouse movement. `MouseTeleport` moves the cursor instantly, while `MouseMove` simulates natural movement using the WindMouse algorithm. Supports configurable click timing and actions like single click, press, and release. ```pascal begin // Instant teleport to position Target.MouseTeleport([100, 100]); // Human-like mouse movement with customizable parameters Target.MouseOptions.Speed := 15; Target.MouseOptions.Gravity := 9; Target.MouseOptions.Wind := 3; Target.MouseMove([500, 300]); // Configure click timing for natural clicks Target.MouseOptions.MinClickTime := 40; Target.MouseOptions.MaxClickTime := 120; // Single click Target.MouseClick(EMouseButton.LEFT); // Manual press and release for precise control Target.MouseDown(EMouseButton.LEFT); Sleep(50); Target.MouseUp(EMouseButton.LEFT); // Check if mouse button is currently pressed if Target.MousePressed(EMouseButton.LEFT) then WriteLn('Left mouse button is pressed'); end. ``` -------------------------------- ### File Existence Check with Pascal Preprocessor Source: https://github.com/villavu/simba/blob/simba2000/DocGen/source/tutorials/Preprocessor.md Shows how to use the {$IF FILEEXISTS} directive in Pascal to conditionally check if a file exists at compile time. ```pascal {$IF FILEEXISTS(Data\settings.ini)} WriteLn('Settings file exists'); {$ELSE} WriteLn('Settings file does not exist'); {$ENDIF} ``` -------------------------------- ### Demonstrate Variant Data Type Usage in Pascal Source: https://github.com/villavu/simba/blob/simba2000/DocGen/source/tutorials/Variant Data Type.md This snippet showcases how to use the variant data type in Pascal. It demonstrates assigning different base types (string, Int64, Double) to a variant variable and checking its assigned status and type. It requires no external dependencies beyond the Pascal compiler. ```pascal var v: Variant; begin WriteLn('Should be unassigned: ', not v.IsAssigned()); WriteLn(); v := 'I am a string'; Writeln('Now should *not* be unassigned: ', v.IsAssigned()); WriteLn('And should be string:'); WriteLn(v.VarType, ' -> ', v); WriteLn(); v := Int64(123); WriteLn('Now should be Int64:'); WriteLn(v.VarType, ' -> ', v); WriteLn(); v := 0.123456; WriteLn('Now should be Double:'); WriteLn(v.VarType, ' -> ', v); end; ``` -------------------------------- ### FindColor with Default Adjusters (Pascal) Source: https://github.com/villavu/simba/blob/simba2000/DocGen/source/tutorials/Color Finding.md This overload of `FindColor` simplifies the search by omitting colorspace and multiplier adjustments, using default values instead. It requires the color to search for, a tolerance level, and the search bounds. It returns an array of points matching the criteria. ```pascal finder.FindColor(Color: TColor; Tolerance: Single: Bounds: TBox = [-1,-1,-1,-1]): TPointArray; ``` -------------------------------- ### Keyboard Typing Source: https://github.com/villavu/simba/blob/simba2000/DocGen/source/tutorials/Mouse & Keyboard.md Simulate keyboard input, including typing text and pressing individual keys. Customizable delays and key press durations provide human-like typing behavior. ```APIDOC ## Keyboard Typing ### Description Simulates keyboard input. `TTarget.KeySend` types text with human-like delays and key holding. `TTarget.KeyDown`, `TTarget.KeyUp`, and `TTarget.KeyPress` allow for individual key manipulation. ### Methods - `TTarget.KeySend(text: String)`: Types the given string character by character, simulating human typing. - `TTarget.KeyDown(key: EKeyCode)`: Presses down the specified key. - `TTarget.KeyUp(key: EKeyCode)`: Releases the specified key. - `TTarget.KeyPress(key: EKeyCode)`: Simulates a press and release action for the specified key, using `MinPressTime` and `MaxPressTime` for duration. ### Enum `EKeyCode` (Refer to specific key code documentation for available keys, e.g., `SHIFT`, `A`, `CTRL`, `ENTER`) ### Options for Keyboard Input - `TTarget.KeyOptions.MinPressTime` (Integer): Minimum milliseconds to hold a key down. - `TTarget.KeyOptions.MaxPressTime` (Integer): Maximum milliseconds to hold a key down. ### Request Example ```pascal // Type the string 'Hello World!' Target.KeySend('Hello World!') // Press and release the SHIFT key for 50 milliseconds Target.KeyDown(EKeyCode.SHIFT); Sleep(50); Target.KeyUp(EKeyCode.SHIFT); // Perform a standard SHIFT key press with default timing Target.KeyPress(EKeyCode.SHIFT); // Set custom key press timing Target.KeyOptions.MinPressTime = 30; Target.KeyOptions.MaxPressTime = 80; Target.KeyPress(EKeyCode.ENTER); ``` ### Response No explicit response body for keyboard actions. Success is indicated by the absence of errors. ```