Ilu' simple scripts

O Ilusionista

Captain 100K
Updated November 2026:
Finally, after a long time, I’ve managed to update this code, incorporating programming best practices and making it more secure.
Now, all functions include guard clauses that follow the "early bailing" (or "fail-fast") principle—in other words, a function or loop will halt execution and return immediately upon encountering an error, an invalid case, or a trivial scenario.

In simpler instances, it will log a message noting that something is missing. But in more critical cases, it initiates a shutdown process while logging the details of what occurred. And thanks to Damon Current for the tips!

Note: keep in mind all those functions were made for V3.0, I haven't tested them in 4.0 yet and some may not work in 4.0

---

Hi everyone.

During the development of my projects, I just stop creating simple codes several tasks. Even I do not have the same level of programmers as BB and DC, I think it does not hurt to share, they can be useful :) And you will see that I am a random fan :)


All those codes should be saved in a file and called in ANIMATIONSCRIPT.
Some of those codes are based in codes from other coders, remember to credit then also, ok?


1. anichangeattack​


Useful when you need to change from one animation to another, where an attack will be performed.

Based on anichangee function (I forgot the author).
Note: there are some cases where anichange should be used, thanks to the flags. Read more about it here

C-like:
void anichangeattack(int Ani)
{
    // Douglas Baldan / O Ilusionista
    // version 1.0 - 23/07/13
    // Animation changer into attacks
    if (typeof(Ani) != openborconstant("VT_INTEGER"))
    {
        shutdown(1, "\n\n ERROR: anichangeattack(Ani) - Missing or invalid parameter.\n");
    }

    void self = getlocalvar("self");

    if (!self)
    {
        return;
    }

    performattack(self, Ani); //Change the animation
}



Usage:
@cmd anichangeattack openborconstant("ANI_FOLLOW5")
(yes, the part openborconstant() is mandatory)

This will make the entity go to FOLLOW5 animation.

2. randomJump​


Useful to make the entity to do a jump into random directions. One of the nice ways to use it is to put this in your itens when they are spawned from obstacles

C-like:
void randomJump(int vx, int vy)
{
    // Douglas Baldan / O Ilusionista
    // version 2.0 - 26.11.26
    // version 1.0 - 23/07/13
    // makes the entity execute a jump into a random direction
    if (!isRandRangeOrEmpty(vx) || !isRandRangeOrEmpty(vy))
    {
        shutdown(1, "\n\n ERROR: randomJump(vx, vy) - Missing or invalid parameter.\n");
    }

    void vSelf = getlocalvar("self"); // Gets the caller

    if (!vSelf)
    {
        return;
    }

    void Xr = NULL();
    void Yr = NULL();

    if (typeof(vx) != openborconstant("VT_EMPTY"))
    {
        Xr = rand() % vx + 0.5; // Random X vel, between the chosen velocity
    }

    if (typeof(vy) != openborconstant("VT_EMPTY"))
    {
        Yr = 2 + rand() % vy; // Random Y vel, to ensure a vertical jump, between the chosen velocity

        if (Yr < 0) // If the Y is negative,
        {
            Yr = Yr * -1; // Make it positive
        }

        Yr = Yr + 1;
    }

    changeentityproperty(vSelf, "velocity", Xr, NULL(), Yr); // Change entity velocity
}


int isRandRangeOrEmpty(void v)
{// 1 if v is empty or a number >= 1 (valid as a rand() divisor %) 
int t = typeof(v); 

if (t == openborconstant("VT_EMPTY")) 
{ 
return 1; 
} 

if (t == openborconstant("VT_INTEGER") || t == openborconstant("VT_DECIMAL")) 
{ 
if (v >= 1) 
{ 
return 1; 
} 
} 

return 0;
}

Usage:

@cmd randomJump 3 4

3 - X velocity

4 - Y velocity
The usage is the same as before, but your animationscript need to have the funcion isRandRangeOrEmpty() provided on the same code block


3. randomJumpZ​


The same case as above, but including the Z axis too.


C-like:
void randomJumpZ(int vx, int vy, int vz)
{
    // Douglas Baldan / O Ilusionista
    // version 2.0 - 26/11/26 
    // version 1.0 - 23/07/13
    // makes the entity execute a jump into a random direction
    if (!isRandRangeOrEmpty(vx) || !isRandRangeOrEmpty(vy) || !isRandRangeOrEmpty(vz))
    {
        shutdown(1, "\n\n ERROR: randomJumpZ(vx, vy, vz) - Missing or invalid parameter.\n");
    }

    void vSelf = getlocalvar("self"); // Gets the caller

    if (!vSelf)
    {
        return;
    }

    void Xr = NULL();
    void Yr = NULL();
    void Zr = NULL();

    if (typeof(vx) != openborconstant("VT_EMPTY"))
    {
        Xr = rand() % vx + 0.5; // Random X vel, between the chosen velocity
    }

    if (typeof(vy) != openborconstant("VT_EMPTY"))
    {
        Yr = 2 + rand() % vy; // Random Y vel, to ensure a vertical jump, between the chosen velocity

        if (Yr < 0) // If the Y is negative,
        {
            Yr = Yr * -1; // Make it positive
        }

        Yr = Yr + 1;
    }

    if (typeof(vz) != openborconstant("VT_EMPTY"))
    {
        Zr = rand() % vz; // Random Z vel, between the chosen velocity
    }

    changeentityproperty(vSelf, "velocity", Xr, Zr, Yr); // Change entity velocity
}



Usage:

@cmd randomJumpZ 3 4 2

3 - X velocity

4 - Y velocity

2 - Z velocity
4 - Y velocity
The usage is the same as before, but your animationscript need to have the funcion isRandRangeOrEmpty() provided on the first code block


4. changeName​


Useful for changing the entity name.

NOTE: There is a limitation in this code - it won't work on the first frame of spawn/respawn animation.

You need to put it on the second frame.



C-like:
void changeName(char iName)
// Change entity name
// 24.09.2013 - Douglas Baldan - The Illusionist
{ 
if (typeof(iName) != openborconstant("VT_STR")) 
{ 
shutdown(1, "\n\n ERROR: changeName(iName) - Missing or invalid parameter.\n"); 
} 

if (strlength(iName) >= 50) // name[MAX_NAME_LEN] = 50: the setter's strcpy would overflow the buffer 
{ 
shutdown(1, "\n\n ERROR: changeName(iName) - Name too long (max 49 characters).\n"); 
} 

void vSelf = getlocalvar("self"); 

if (!vSelf) 
{ 
return; 
} 

changeentityproperty(vSelf, "name", iName);
}

Usage:

@cmd changeName "New_Name"
Same as before, but failing to provide "New_name" will cause a shutdown.
Also, "New_Name" is limited to 50 characters. Any value beyond this will cause a shutdown
5. unbind

If you use a binded entity to another entity and need to unbind it, this code is useful for that.

C-like:
void unbind()
// unbind entity
// 24.09.2013 - Douglas Baldan - O Ilusionista
{
    void vSelf = getlocalvar("self");

    if (!vSelf)
    {
        return;
    }

    bindentity(vSelf, NULL());
}

Usage:

@cmd unbind
Same as before

6. spawnRandom​


Spawns another entity (which needs to be loaded first) at random X and Y positions, giving a very cool looking.
This code uses the Spawn01 function by Damon Caskey and you need that function to make it works.

C-like:
void spawnRandom(char vName, int vx, int vy)
// Spawn entity at random places
// 24.09.2013 - Douglas Baldan - O Ilusionista
// Based in Damon Caskey "spawn01" function, and you need that function to make it works.
// vx = maximum X position range
// vy = maximum Y position range
{
    if (typeof(vName) != openborconstant("VT_STR")
        || !isRandRange(vx)
        || !isRandRange(vy))
    {
        shutdown(1, "\n\n ERROR: spawnRandom(vName, vx, vy) - Missing or invalid parameter.\n");
    }

    int Xr = rand() % vx; // Random X pos
    int Yr = rand() % vy; // Random Y pos

    spawn01(vName, vx + Xr, vy + Yr, 0);
}

Usage:

@cmd spawnRandom "name" 50 100
Requires isRandRange() and spawn01() to work
Keep in mind that the given value will work from its negative value to the positive value. IOW, 50 pixels means "from -50 to 50 pixels"

This is the customized version of spawn01 function I am using.
It's the same of the original but:
1 - have guards
2 - will automatically set the caller as parent of the spawned entity
C-like:
void spawn01(void vName, float fX, float fY, float fZ)
{
    /* Guards */
    if (typeof(vName) != openborconstant("VT_STR")
    || (typeof(fX) != openborconstant("VT_INTEGER") && typeof(fX) != openborconstant("VT_DECIMAL"))
    || (typeof(fY) != openborconstant("VT_INTEGER") && typeof(fY) != openborconstant("VT_DECIMAL"))
    || (typeof(fZ) != openborconstant("VT_INTEGER") && typeof(fZ) != openborconstant("VT_DECIMAL") && typeof(fZ) != openborconstant("VT_EMPTY")))
    {
        shutdown(1, "\n\n ERROR: spawn01(vName, fX, fY, fZ) - Missing or invalid parameter.\n");
    }

    // fZ (optional, default 0): omitted in the @cmd = no depth adjustment.
    if (typeof(fZ) == openborconstant("VT_EMPTY"))
    {
        fZ = 0;
    }

    // spawn01 (Generic spawner)
    // Damon Vaughn Caskey
    // 07/06/2007
    //
    // Spawns entity next to caller.
    //
    // vName: Model name of entity to be spawned in.
    // fX: X location adjustment.
    // fY: Y (altitude) location adjustment.
    // fZ: Z (depth) location adjustment.

    // --- Category A: self supplied by the engine (animationscript) ---
    void self = getlocalvar("self");
    if (!self)
    {
        log("\nError: spawn01 empty value= self");
        return NULL();
    }

    // --- Extra check: empty vName (passes typeof but fails on setspawnentry) ---
    if (!vName)
    {
        log("\nError: spawn01 empty value= vName");
        return NULL();
    }

    // --- Cache self properties (optimization) ---
    int iDirection = getentityproperty(self, "direction");
    float baseX = getentityproperty(self, "x");
    float baseA = getentityproperty(self, "a");
    float baseZ = getentityproperty(self, "z");

    // Facing left: reverse X adjustment to match facing
    if (iDirection == 0)
    {
        fX = -fX;
    }

    clearspawnentry();
    setspawnentry("name", vName);

    // --- Category C: newly created handle (exists check not needed) ---
    void vSpawn = spawn();
    if (!vSpawn)
    {
        log("\nError: spawn01 empty value= vSpawn (spawn failed for model: " + vName + ")");
        return NULL();
    }

    changeentityproperty(vSpawn, "position", baseX + fX, baseZ + fZ, baseA + fY);
    changeentityproperty(vSpawn, "direction", iDirection);
    changeentityproperty(vSpawn, "parent", self);

    return vSpawn;
}


7. spawnRandomZ​


The same case of above, but works for X, Y and Z axis.
This code was based on a modified version of Damon Caskey's Spawn01 function, that doesn't cares for direction, called spawn000. You need that spawn000 function to make this work. Also requires isRandRangeOrEmpty() provided on the first code block


spawn000

C-like:
void spawn000(char vName, float fX, float fY, float fZ)
{
    //spawn01 (Generic spawner) without direction
    //Damon Vaughn Caskey
    //07/06/2007 -- Modified by Douglas Baldan/O Ilusionista
    //
    //Spawns entity next to caller.
    //
    //vName: Model name of entity to be spawned in.
    //fX: X location adjustment.
    //fZ: Y location adjustment.
    //fY: Z location adjustment.
    if (typeof(vName) != openborconstant("VT_STR")
        || !isNumberOrEmpty(fX)
        || !isNumberOrEmpty(fY)
        || !isNumberOrEmpty(fZ))
    {
        shutdown(1, "\n\n ERROR: spawn000(vName, fX, fY, fZ) - Missing or invalid parameter.\n");
    }

    void self = getlocalvar("self"); //Get calling entity.

    if (!self)
    {
        log("\nError: spawn000 empty value= self");
        return NULL();
    }

    void vSpawn; //Spawn object.

    if (typeof(fX) == openborconstant("VT_EMPTY"))
    {
        fX = 0;
    }

    if (typeof(fY) == openborconstant("VT_EMPTY"))
    {
        fY = 0;
    }

    if (typeof(fZ) == openborconstant("VT_EMPTY"))
    {
        fZ = 0;
    }

    fX = fX + getentityproperty(self, "x"); //Get X location and add adjustment.
    fY = fY + getentityproperty(self, "a"); //Get Y location and add adjustment.
    fZ = fZ + getentityproperty(self, "z"); //Get Z location and add adjustment.

    clearspawnentry(); //Clear current spawn entry.
    setspawnentry("name", vName); //Acquire spawn entity by name.
    vSpawn = spawn(); //Spawn in entity.
    clearspawnentry();

    if (!vSpawn)
    {
        log("\nError: spawn000 empty value= vSpawn (spawn failed for model: " + vName + ")");
        return NULL();
    }

    changeentityproperty(vSpawn, "position", fX, fZ, fY); //Set spawn location.

    return vSpawn; //Return spawn.
}


spawnRandomZ

C-like:
void spawnRandomZ(char vName, int vx, int vy, int vz)
// Spawn entity at random places
// 24.09.2013 - Douglas Baldan - O Ilusionista
// Based in Damon Caskey "spawn01" function, and you need that function to make it works.
// vx = maximum X position range
// vy = maximum Y position range
// vz = maximum Z position range
{
    if (typeof(vName) != openborconstant("VT_STR")
        || !isRandRange(vx)
        || !isRandRange(vy)
        || !isRandRange(vz))
    {
        shutdown(1, "\n\n ERROR: spawnRandomZ(vName, vx, vy, vz) - Missing or invalid parameter.\n");
    }

    int Xr = rand() % vx; // Random X pos
    int Yr = rand() % vy; // Random Y pos
    int Zr = rand() % vz; // Random Z pos

    spawn000(vName, Xr, Yr, Zr);
}

Usage:

@cmd spawnRandom "name" 50 100 120
Same as before

8. refill​


Refill the MP bar with the desired value.


C-like:
void refill(int iValue)
//Refill the health with the desired value.
//Douglas Baldan
{
    if (typeof(iValue) != openborconstant("VT_INTEGER"))
    {
        shutdown(1, "\n\n ERROR: refill(iValue) - Missing or invalid parameter.\n");
    }

    void self = getlocalvar("self");

    if (!self)
    {
        return;
    }

    int Health = getentityproperty(self, "health"); //get health
    changeentityproperty(self, "health", Health + iValue);
}


Usage:

@cmd refill 50

Same as before. Refill 50 points of MP


9. mpcost​


Spend some MP


C-like:
void mpcost(int MCost)
{// Spend some mp
    if (typeof(MCost) != openborconstant("VT_INTEGER"))
    {
        shutdown(1, "\n\n ERROR: mpcost(MCost) - Missing or invalid parameter.\n");
    }

    void self = getlocalvar("self");

    if (!self)
    {
        return;
    }

    int MPower = getentityproperty(self, "mp"); //get mp
    changeentityproperty(self, "mp", MPower - MCost); //consume mp
}

Usage:

@cmd mpcost 50
Same as before. Drains 50 points of MP

--------------------------------------

I have many other codes to share, I will edit this post once I have time.
See ya,

O Ilusionista.
 
Last edited:
Thanks O', I'm not clued up when it comes to scripts..in actual fact I don't know how to even start using a pre provided 1.
But when I do figure it out one day, these scripts you provided here would be most helpful.
 
Thanks for share, sure they will be usefull.

And i add other script that results indispensable to me:

Code:
void aniframe(void Ani, int Frame){	
	// Animation changer
    void self = getlocalvar("self"); // Get self

    changeentityproperty(self, "animation", openborconstant(Ani));
	// Change to desired animation
	changeentityproperty(self, "animpos", Frame);
	// Change to desired frame
}

It changes to other anim, but you can choose the frame you want to switch to.
Frames are indexed, so starts from 0. Frame 1 = 0.

This other version changes to attack anim anim:

Code:
void aniframe(void Ani, int Frame){	
	// Animation changer
    void self = getlocalvar("self"); // Get self

    changeentityproperty(self, "animation", openborconstant(Ani));
	// Change to desired animation
	changeentityproperty(self, "animpos", Frame);
	// Change to desired frame
}

How to use:
Call it on frame, like this
@cmd aniframe "ANI_IDLE" 0
 
Oi Ilusionista! Queria fazer um pile drive estilo Haggar (Final Fight 2 pro SNES), que também atinge outros inimigos que estão por perto. Como posso fazer isso? Qual a maneira mais prática?
 
*Sergio, welcome. But in this forum, you need to post in english only.
(Sergio, bem-vindo. Mas neste fórum, vc tem que postar em inglês apenas)

You need to open a new topic to ask this.
 
O Ilusionista said:
*Sergio, welcome. But in this forum, you need to post in english only.
(Sergio, bem-vindo. Mas neste fórum, vc tem que postar em inglês apenas)

You need to open a new topic to ask this.

He already DID ask, here.

Sergio, I am losing my patience. You are making non English posts, posting off topic questions in active threads, and asking the same question in multiple places. I already warned you once about the latter. Do not do it again or you will be muted.

DC
 
Damon, I don't know him too much, he poped at my channel asking for help, I helped him and suggested him to join here.
But, sure, he needs to follow the rules.

(Sergio, por favor, siga as regras do fórum).
 
Ok Damon. I will open a new topic. Don´t loose your patience. I didn´t mean to disrespect your forum. I just want to know from other programmers some tips.
But now that i know i cant do the same question to many people, i won´t do it again. Sorry! No rudeness needed!
 
Maybe it's because of the persistence, but don't get me wrong, you might be a nice guy. He's not being rude, you're just making actions that make people think that you're impatient.

Sometimes it's best to just wait for the answer, since most of the people here have other lives other than OpenBOR and couldn't attend to your problem sooner.  ;)

Just saying.

... And It's better to make another topic on OpenBOR help on the Help & Resources section. It's much more cleaner and clearer that way.
 
No problem CRxTRDude! I just want to learn more from this awesome platform, and make cool games faithful to some well know games.
Thanks for the advice anyway!
 
mpcostAnim
Spend some MP within a desired value. If MP is less than the cost, changes to a desired animation.
Useful to recreate the ANI_CANT which is not working in v3.0

Copy this function to your animationscript file:
C-like:
void mpcostAnim(int MCost, int Ani)
{// Spend some MP with the desired value. If MP is less than the cost, changes to a desired animation.
// V2.0 - 26/11/26
// Douglas Baldan / The Illusionist - 01/12/2018
if (typeof(MCost) != openborconstant("VT_INTEGER") || typeof(Ani) != openborconstant("VT_INTEGER")) {
shutdown(1, "\n\n ERROR: mpcostAnim(MCost, Ani) - Missing or invalid parameter.\n");
}

if (MCost < 0) {
shutdown(1, "\n\n ERROR: mpcostAnim(MCost, Ani) - Missing or invalid parameter.\n");
}

void self = getlocalvar("self");

if (self == NULL()) {
log("\nError: mpcostAnim empty value= self");
return NULL();
}

int iMPower = getentityproperty(self, "mp");

if (iMPower < MCost) {
performattack(self, Ani); // Insufficient MP: switch to desired animation
return;
}

changeentityproperty(self, "mp", iMPower - MCost); // consumes MP
}

Usage
@cmd mpcostAnim 10 openborconstant("ANI_RUNATTACK")
Usage had changed. Watch out for the case change - the function is called "mpcostAnim", not "mpcostanim".
Script is case sensitive.
 
Last edited:
I’ve created a useful function to heal all players and NPCs currently on screen. You can choose whether it simply heals them or if an effect (entity) appears over the target.
You can also pass negative values for the HP, which will cause damage. However, the function only reduces health down to 0; it does not kill the entity.

Usage:
@cmd bmt_cure_all 60
(heal only)

@cmd bmt_cure_all -30
(hurt only)

@cmd bmt_cure_all 60 1 "flash4" 0 20
(heal + effect)

HP = amount added to the target's health (required, negative values deal damage)
control = 0/NULL/omitted: effect, offsetX and offsetY are ignored
>= 1: effect routine runs
effect = name of the entity spawned at the target (must be cached. remember that funcions are case sensitive)
offsetX = X offset from the target (positive adds, negative subtracts)
offsetY = Y (altitude) offset from the target (positive adds, negative subtracts)
C-like:
void bmt_cure_all(float HP, int control, char effect, float offsetX, float offsetY)
{
    // Heals (or damages, if HP is negative) every existing player and every active NPC.
    // Optionally spawns an effect entity at each affected target.
    //
    // Author: Douglas Baldan + Claude
    // Date: 2026.11.15 - updated in 26.11.26
    //
    // Usage:
    //   @cmd bmt_cure_all 60                       (heal only)
    //   @cmd bmt_cure_all 60 1 "flash4" 0 20       (heal + effect)
    //
    // HP      = amount added to the target's health (required, negative values deal damage)
    // control = 0/NULL/omitted: effect, offsetX and offsetY are ignored
    //           >= 1: effect routine runs
    // effect  = name of the entity spawned at the target (must be cached)
    // offsetX = X offset from the target (positive adds, negative subtracts)
    // offsetY = Y (altitude) offset from the target (positive adds, negative subtracts)
    int  iPlayer;
    int  iIndex;
    int  iMax;
    int  iNpcType;
    int  iHealth;
    int  iControl;
    int  iSpawn;
    float fOffsetX;
    float fOffsetY;
    float fX;
    float fZ;
    float fA;
    void ent;
    void fx;

    // Guards
    if (typeof(HP) != openborconstant("VT_INTEGER") && typeof(HP) != openborconstant("VT_DECIMAL"))
    {
        shutdown(1, "\n\n ERROR: bmt_cure_all(HP, control, effect, offsetX, offsetY) - Missing or invalid parameter.\n");
    }

    if (typeof(control) != openborconstant("VT_INTEGER") && typeof(control) != openborconstant("VT_EMPTY"))
    {
        shutdown(1, "\n\n ERROR: bmt_cure_all(HP, control, effect, offsetX, offsetY) - Missing or invalid parameter.\n");
    }

    if (typeof(effect) != openborconstant("VT_STR") && typeof(effect) != openborconstant("VT_EMPTY"))
    {
        shutdown(1, "\n\n ERROR: bmt_cure_all(HP, control, effect, offsetX, offsetY) - Missing or invalid parameter.\n");
    }

    if (typeof(offsetX) != openborconstant("VT_INTEGER") && typeof(offsetX) != openborconstant("VT_DECIMAL") && typeof(offsetX) != openborconstant("VT_EMPTY"))
    {
        shutdown(1, "\n\n ERROR: bmt_cure_all(HP, control, effect, offsetX, offsetY) - Missing or invalid parameter.\n");
    }

    if (typeof(offsetY) != openborconstant("VT_INTEGER") && typeof(offsetY) != openborconstant("VT_DECIMAL") && typeof(offsetY) != openborconstant("VT_EMPTY"))
    {
        shutdown(1, "\n\n ERROR: bmt_cure_all(HP, control, effect, offsetX, offsetY) - Missing or invalid parameter.\n");
    }

    // Effect setup (only when control >= 1), resolved once outside the loops
    iControl = 0;
    iSpawn   = 0;
    fOffsetX = 0;
    fOffsetY = 0;

    if (typeof(control) == openborconstant("VT_INTEGER"))
    {
        iControl = control;
    }

    if (iControl >= 1)
    {
        iSpawn = 1;
    }

    if (iSpawn == 1)
    {
        if (typeof(effect) != openborconstant("VT_STR"))
        {
            log("\nError: bmt_cure_all empty value= effect");
            iSpawn = 0;
        }
    }

    if (iSpawn == 1)
    {
        if (typeof(offsetX) != openborconstant("VT_EMPTY"))
        {
            fOffsetX = offsetX;
        }

        if (typeof(offsetY) != openborconstant("VT_EMPTY"))
        {
            fOffsetY = offsetY;
        }
    }

    // Players (slots 0 to 3)
    for (iPlayer = 0; iPlayer < 4; iPlayer++)
    {
        ent = getplayerproperty(iPlayer, "entity");

        if (ent == NULL())
        {
            continue;
        }

        if (!getentityproperty(ent, "exists"))
        {
            continue;
        }

        if (getentityproperty(ent, "dead"))
        {
            continue;
        }

        iHealth = getentityproperty(ent, "health");

        if (iHealth <= 0)
        {
            continue;
        }

        changeentityproperty(ent, "health", iHealth + HP);

        if (iSpawn == 1)
        {
            fX = getentityproperty(ent, "x");
            fZ = getentityproperty(ent, "z");
            fA = getentityproperty(ent, "a");

            clearspawnentry();
            setspawnentry("name", effect);
            setspawnentry("coords", fX + fOffsetX, fZ, fA + fOffsetY);
            fx = spawn();

            if (fx == NULL())
            {
                log("\nError: bmt_cure_all spawn empty value= " + effect);
                iSpawn = 0;
            }
        }
    }

    // Active NPCs
    iMax     = openborvariant("ent_max");
    iNpcType = openborconstant("TYPE_NPC"); // resolved once, outside the loop

    for (iIndex = 0; iIndex < iMax; iIndex++)
    {
        ent = getentity(iIndex);

        if (ent == NULL())
        {
            continue;
        }

        if (!getentityproperty(ent, "exists"))
        {
            continue;
        }

        if (getentityproperty(ent, "dead"))
        {
            continue;
        }

        if (getentityproperty(ent, "type") != iNpcType)
        {
            continue;
        }

        iHealth = getentityproperty(ent, "health");

        if (iHealth <= 0)
        {
            continue;
        }

        changeentityproperty(ent, "health", iHealth + HP);

        if (iSpawn == 1)
        {
            fX = getentityproperty(ent, "x");
            fZ = getentityproperty(ent, "z");
            fA = getentityproperty(ent, "a");

            clearspawnentry();
            setspawnentry("name", effect);
            setspawnentry("coords", fX + fOffsetX, fZ, fA + fOffsetY);
            fx = spawn();
        }
    }
}

The code includes safety guards that may simply write the error to a log or shut down the engine, while recording what occurred in the log in the event that something unusual took place.

The usage is the same, but there is an important change—beyond the guard clauses: the use of `ENT_MAX` instead of `COUNT_ENTITIES`. I explain this in detail here.
 
Last edited:
Updated November 2026:
Finally, after a long time, I’ve managed to update this code, incorporating programming best practices and making it more secure.
Now, all functions include guard clauses that follow the "early bailing" (or "fail-fast") principle—in other words, a function or loop will halt execution and return immediately upon encountering an error, an invalid case, or a trivial scenario.

In simpler instances, it will log a message noting that something is missing. But in more critical cases, it initiates a shutdown process while logging the details of what occurred. And thanks to @DCurrent for the tips!

Note: keep in mind all those functions were made for V3.0, I haven't tested them in 4.0 yet and some may not work in 4.0

I explained the changes in usage—case by case—related to safety guards; however, one of these changes stems from an error I only discovered thanks to Claude’s help: the mystery of why loops using "count_entities" would fail when there were many entities on screen. used in bmt_cure_all()

All information provided here was extracted using the source code from V3.0 build 6391; it is not an AI hallucination or an estimate—it is a reading of the source code.

At first glance, it might seem that using `COUNT_ENTITIES` would be faster—after all, if there are only 10 entities on screen, you only need to iterate 10 times. However, there is a crucial factor here that caused another piece of code I had to fail: "gaps" in the list.

I had a script that used `count_entities` to loop through active entities, locate a specific one, and modify a property—for instance, designating it as a "boss." Although a level can contain multiple "bosses," this code is incomplete in V3.0 and doesn't function correctly; as a result, the slowdown triggered by a boss's death never ends—it persists until you defeat a second boss or manually disable the effect.

I realized something: when there are few enemies or players on screen, the function can successfully query all present entities, perform the necessary checks, and update the "boss" property. But when there are multiple players or a large number of entities on screen, the script isn't "fast enough", and the code fails.

The reason lies in how `count_entities` actually works: `openborvariant("count_entities")` returns the total number of existing entities, but `getentity(i)` accesses the engine's list of slots—which can contain "gaps." When there are few entities, they occupy the initial slots, and a loop running up to `count_entities` will reach them. However, when more players and enemies are present, entities are removed and their slots are reused; consequently, a boss might end up at an index higher than the value returned by `count_entities`. The loop finishes before it ever reaches that boss. This explains why the failure only occurs when there are many entities on screen. Why `count_entities` results in an incorrect count

Example with 10 active entities at positions 0 through 9:

position: 0 1 2 3 4 5 6 7 8 9
exists: 1 1 1 1 1 1 1 1 1 1 count_entities = 10, ent_max = 10

A projectile at position 3 leaves the screen, and `kill_entity` removes it:
posição: 0 1 2 3 4 5 6 7 8 9
exists: 1 1 1 0 1 1 1 1 1 1 count_entities = 9, ent_max = 10

`for(i = 0; i < openborvariant("count_entities"); i++)` iterates from 0 to 8.
It skips the empty slot at position 3—which is expected—but it also fails to reach position 9, where an active entity resides. That entity is left out.

`for(i = 0; i < openborvariant("ent_max"); i++)` iterates from 0 to 9. It correctly identifies all 9 active entities, provided the loop checks for existence at each slot.

With a large number of entities, the error is compounded:

Every "gap" hides an entity; with N gaps, the last N active entities are excluded from the loop.
A higher number of entities leads to more removals per tick—projectiles, effects, particles, and disappearing enemies can all create multiple gaps within the same tick.
The entities that get left out are the most recently added ones, as they occupy the end of the list. This is why the failure appears random and occurs more frequently when there is a lot happening on screen.

How Gaps Appear

The entity list (`ent_list`) is an array of slots. Each slot has an `exists` flag, which indicates whether it is currently in use.

When an entity is killed, `kill_entity` sets the `exists` flag for that slot to false and decrements the total count of active entities, but it does not alter the order of the list. The slot remains empty at its original position, with active entities potentially located after it—this is what constitutes a "gap."

Events that trigger `kill_entity` include:
  • death resulting in the removal of the entity's body;
  • a projectile or entity leaving the screen, or reaching the end of its lifespan (handled by `check_lost` within `update_ents`);
  • a call to `killentity()` via a script;
  • a spawn event that occurs when a stage exceeds its `spawnoverride` limit—in this case, an entity with lower priority is killed to free up its slot.
Gaps are closed only within `arrange_ents()`.
The engine calls this function exactly once, at the end of `update_ents()`.
It shifts all active entities to the beginning of the list, leaves the empty slots at the end, and updates `ent_max` to match the total number of active entities.
Spawning an entity does not resolve these gaps; it simply occupies the first available empty slot starting from the beginning of the list. While this fills one gap, it does not reorganize the rest of the list.

In short, a gap persists from the moment an entity disappears until the end of the current tick's update process. Any script that executes during this interval—such as `updatescript`, `thinkscript`, `animationscript`, `ondeathscript`, `onkillscript`, `takedamagescript`, or any other script called within `update_ents`—will perceive the list as containing gaps. Furthermore, scripts that run outside of this process (for instance, those related to rendering) may also encounter gaps created after the most recent reorganization.
 
Back
Top Bottom