Combine RGSS with ruby-c dll and speed up the game like a boss

WARNING:
This post is not suitable for newbies, perhaps also not applied to the game that doesn't have a performance issue.

It's suggested to know the following knowledge to fully understand how it works:
  • RMVA Scripting experience(most important one, required)
  • Basic C/C++ knowledge
  • Familiar with Ruby and C/C++
  • PE(portable executable) and DLL(Dynamic Link Library)
Don't panic if you're not familiar with C/C++, I'll try my best to explain anyway.
A very basic thing that you should know is the datatype of all ruby object in C level is 'VALUE', a pointer to the object except some very basic object, like Fixnum, and you can see this part in ruby.c:
Code:
#define INT2FIX(i) ((VALUE)(((SIGNED_VALUE)(i))<<1 | FIXNUM_FLAG))
in this line, SIGNED_VALUE generally is LONG(aka int) and FIXNUM_FLAG is 1, so you can think Fixnum is encoded by (n * 2 + 1) instead of the pointer. However, the VALUE of String and Float are both pointers. And you can get the object's address by:
Code:
obj.object_id << 1
(as known as multiply the object_id by 2)
we'll need that to pass the object from Game.exe to our dll later
------------------------I'm a random split line------------------------
Currently, I'm making a unique engine for my game, and as larger as it gets, the performance issue comes up...(duh)

Just like Python, one of the popular way to resolve this problem in interpreter language is mixing it with C-level code to speed up and improve the calculation significantly.


Before getting started, you will need:
- Ruby 1.9.2-p0 source code (download here), this is the ruby version that rgss using
- A C/C++ IDE, Visual Studio is a common option, but I also using Code::Blocks, VS is using for debugging DLL
- (optional) A debugger (I use VS), because the game will crash silently if something wrong with the dll

Once got the software running and prepared the DLL project, the next step is telling the compiler to know what's Ruby object, notice that we don't have to compile the ruby source code itself. Since RubyVM is running inside RGSS301.dll so we only need to declare necessary functions and datatypes and call RGSS301.dll while building up the dynamic link library. But if you're as silly as I am...managed to include the whole ruby to the dll and using the ruby function... Congratulations! You'll get ruby_vm_current_ptr is nullptr and the game crashes! (I f*cking even compile the whole ruby natively and it took me ages to build successfully...)

If you don't want to copy, edit and post the ruby source code, you can go download header files here and put them in the project folder, then include "ruby.h", this way you should have no trouble using VALUE in your C/CPP file. So the .hpp or .h file should like:
Code:
#include <windows.h>
#include "ruby.h"

Next, we're heading to the example, and what I gonna show here is how to improve the projectile collide detection, here're also some extra tips you should know while writing c code:
- Access VALUE as less as possible, the dll is slower than getting VALUE in RGSS
- Don't wrap the functions that frequently calling other methods into dll, the reason is above
- From 2 above, things needed to write into C-level are calculation-heavy functions
- Since Float are pointers, so using Fixnum if you can, and convert them to int and store in your C code
- avoid using std::vector, using new int [] if need to deal with fixed-length array

since the time complexity of simplest collide detection is O(n^2), only need O(n) time to access VALUE data, also not affect gameplay much if the projectile colliding effect is delayed by 1 frame so it's good to put that into C.

Before jump into the demo and explain the code, here's the result of my little experiment, I also used Theo's Anti-Lag to make the result better due to the fact that tons of projectiles also means tons of active sprites(unfortunately RMVA is not good at graphics processing), and the measurement is making a constantly updated event run from A point to B point 10 times, since the lag will slow the entire game down, so the one take less time is the better result.

Experiment Info:
> Using collision box as collide detection
> Distance of A to B: 10 tiles
> Measurement Event: x4 Faster Speed, Highest Frequency, through
> 5 projectiles are generated per frame update
> Maximum visible sprites number is 100/1000000000 (over will become invisible projectile lol)
> Total events: 277
> Total battler event: 65
※The result will vary on different hardware, tested using I5-6200U/4GB laptop


Spoiler: Result (text only)
No projectile:
Average 1.0149 seconds in 10 runs

100 sprite limit, no dll nor anti-lag script:
Average 5.4282 seconds in 10 runs; lim -> 5.98 seconds with around 620 projectiles

100 sprite limit, with dll only:
Average 3.1801 seconds in 10 runs; lim -> 3.38 seconds with around 620 projectiles


100 sprite limit, with ATL only:
Average 3.3929 seconds in 10 runs; lim -> 3.92 seconds with around 676 projectiles


100 sprite limit, with both dll and ATL:
Average 1.3161 seconds in 10 runs; lim -> 1.39 seconds with around 676 projectiles


1,000,000,000 sprite limit, with dll only:
Average 4.3676 seconds in 10 runs; lim -> 5.11 seconds with around 650 projectiles

1,000,000,000 sprite limit, with ATL only:
Average 4.0854 seconds in 10 runs; lim -> 4.92 seconds with around 693 projectiles


1,000,000,000 sprite limit, with both dll and ATL:]

Average 2.3111 seconds in 10 runs; lim -> 3.09 seconds with around 693 projectiles


Spoiler: Result (with images)
No projectile:
Ma7gokA.png


No anti-lag, native ruby collision detection, 100 sprite limit
wujLFQQ.png


with anti-lag, native ruby code, 100 sprite limit
lQWb4uc.png

1000000000 limit:
qQQWcA1.png


no anti-lag, C-level collide detection code, 100 sprite limit
kgDH5hh.png

1000000000 limit:
gpfg1yz.png


with anti-lag and C-level code, 100 sprite limit
VYj9HVl.png

1000000000 limit:
gOujwkb.png

Download the source code of DLL project: https://github.com/ken1882/RGSS-Ext
Download the Demo: https://mega.nz/#!AlZiAK6A!cCybazZERTQmkT0TELzZpAu6I2AnUZTf1nCRAnDsPPA (Google Drive tends to think executable is infected virus for some reason)

<next: building dll>
[Building the DLL]
Starting from "main.hpp", here I use '.hpp' instead of '.h' because '.hpp' is allowed to write the implementation.
If you haven't downloaded the necessary ruby dependency you can download [here], and of course, you can also copy, edit and paste them from the ruby-source code.

[Headers]
the #include <libpath> works kinda like require in ruby, however when loading native library the path should enclosed with " " instead of < >
and in my .hpp it has included some the common library that we often use

Code:
#include <windows.h> // required to build DLL
#include "ruby.h"    // to tell the compile what's ruby datatypes, functions etc.
#include <iostream>  // C++ header
#include <cmath>     // Mathmatical calculation like Trigonometric functions
#include <algorithm> // Handy algorithm library such as std::sort
#include <vector>    // Only use this when need to delete/insert array often
                     // for fixed-length array you should use int* array = new int[len]
#include <map>       // You can use it like the Hash in ruby
#include <queue>     // or <priority_quque>, handy to use while dealing Graphic-Theory related prolem, popular one is pathfinding
#include <stack>     // Good to reversing stuff
#include <string>    // Convenient string operation functions
all details of these libraies could be found at http://www.cplusplus.com/reference/

Next down to bunch of terrifying letters:
Code:
typedef VALUE(*VALUE_P)(); // ignore this

typedef VALUE(*rgss_obj_ivar_get_proto)(VALUE, VALUE);
typedef VALUE(*rgss_obj_ivar_set_proto)(VALUE, VALUE, VALUE);
typedef VALUE(*rgss_ary_at_proto)(VALUE, VALUE);
typedef VALUE(*rgss_ascii_new_cstr_proto)(const char*);
here we using typedef to declare function prototype that we are going to use, take one as example and it should be clear:
Code:
typedef VALUE(*rgss_obj_ivar_get_proto)(VALUE, VALUE);

          ↑                 ↑             ↑      ↑
   return datatype          ↑        function arguments
               typename of the function pointer
as you can notice here, unlike ruby, datatypes are necessary for C, each datatype occupies different memory space, computer also operates them differently.
For instance, int(or same as LONG in most of modern machine) eats 4bytes of memory and uint_64_t(or QWORD) eats 8 bytes; both int and float use 4bytes, but how they represented in memory and calculated has a very significant difference.
However, all of Ruby objects have same datatype, it will certainly require other stuff to tell the machine how to find and deal with them, and this is one reason why Ruby/Python is slow.

After declare the function prototypes, then we can define the functions:
Code:
static rgss_obj_ivar_get_proto rgss_obj_ivar_get;     // instance_variable_get
static rgss_obj_ivar_set_proto rgss_obj_ivar_set;     // instance_variable_set
static rgss_ary_at_proto rgss_ary_at;                 // Query array index
static rgss_ascii_new_cstr_proto rgss_ascii_new_cstr; // convert char* to VALUE
static int init_ok = false;  // Flag of whether DLL is initialized (should be bool but I used int here)
wait, another creepy word appears! what heck is the 'static'? Well, short answer: the variable with static prefix will always exist in entire program, so it won't randomly disappear when we call them from our game next time.
Now, with these functions, finally we can access the instance variable in our game from dll, but I'll introduce them later.

Reaches the end of the header file:
Code:
void DLL_EXPORT Initialize(HMODULE){ ... }
DWORD DLL_EXPORT InitOK();
VALUE DLL_EXPORT HelloWorld();
The keyword 'DLL_EXPORT' is using in code::blocks, in VS it's __declspec(dllexport). Anyway, the purpose is rather simple here: the function with DLL_EXPORT keyword can be called outside, whereas called from the game.

[main.cpp]
For sake of tutorial, I didn't separate different function into files.

First, we take a look at those 2 simple functions
Code:
DWORD DLL_EXPORT InitOK() {
    return init_ok;
}

VALUE DLL_EXPORT HelloWorld() {
    if (!init_ok) { return -1; }
    return rgss_ascii_new_cstr("Hello World from RGSS-Extension!");
}
Yep, as you guessed, yet another hello world program but essential to test whether it runs steadily. The InitOK is just using in rgss to check whether the dll is initialized

After grabbing the compiled dll to your game's root folder (or System/ even other paths as you desired), now we gotta set up inside our script -- and we need to use Win32API to load the dll.
Some of the code below is taken from "Scripts/Collision.rb"
Code:
# path to rgss.dll
RGSSPath = "System/RGSS301.dll"

# path to our dll
RGSSExtPath = "RGSSExt.dll"

# necessary windows function call
LoadLibrary = Win32API.new('kernel32', 'LoadLibraryA', 'p', 'i')
GetLastError = Win32API.new('kernel32', 'GetLastError', 'v', 'l')
If you're not familiar with Win32API, here's a quick intro:
Spoiler
Win32API.new('DLL_Name', 'Function_Name', 'argument datatype', 'return datatype')
datatypes are:
v - void
p - pointer
i - int
l - long
if the function has more arguments, such as (LPSTR, int), then the string of argument datatype should be 'pi'

Loading the dll:
Code:
RGSSDLL = LoadLibrary.call(RGSSPath)
if RGSSDLL == 0
  raise LoadError, "Failed to load #{RGSSPath}, error code: #{GetLastError.call()}"
else
  puts "#{RGSSPath} loaded at 0x#{RGSSDLL.to_s(16)} (#{RGSSDLL})"
end
#-----------------------------------------------------------------------------
RGSSEXTDLL = LoadLibrary.call(RGSSExtPath)
if RGSSEXTDLL == 0
  raise LoadError, "Failed to load #{RGSSPath}, error code: #{GetLastError.call()}"
else
  puts "#{RGSSExtPath} loaded at 0x#{RGSSEXTDLL.to_s(16)} (#{RGSSEXTDLL})"
end
If the dll is loaded successfully, it should return the memory address where the dll is loaded at, otherwise you'll need to check the error code and google the solution.

Then finally:
Code:
#==============================================================================
# Transfer received address back to ruby object
def VALUE2obj(cvalue)
  return ObjectSpace._id2ref(cvalue >> 1);
end

Win32API.new(RGSSExtPath, "Initialize", 'l', 'v').call(RGSSDLL)
puts VALUE2obj(Win32API.new(RGSSExtPath, "HelloWorld", 'v', 'l').call())
The value that we received from out dll is the string address of the "Hello World!", to transfer it back to ruby object, we need to use ObjectSpace._id2ref(object_id).
For now, you should be able to see the Hello World in the RGSS console.

<next: access the data in game from dll>
@ken1882 Blue text is reserved for Moderator message only. You can see the Forum Rules here. Please edit your posts to black text.
Howdy.

I didn't read through everything, but this system seems to be about speeding up the general performance of RM VX Ace. That's pretty nice but let me tell you that I've downloaded the demo and the game is running at a constant 59 FPS, but it's actually as laggy as if it were only 3 FPS or even less which is kinda strange. Well, sometimes the whole movement even stops completely for a few seconds.

Just wanted to leave this as a feedback. Maybe it helps. Don't know what you're trying to do exactly.

Greetings,
Tw0Face
actually as laggy as if it were only 3 FPS
That's because of the config.

Go into the scripts and change the fireballtimer to a higher number like 5, and lower the spritelimit to something like 100,000
First thing first, the black font tag makes the entire thread unreadable in the dark theme in this forum. Maybe you should make the text untagged with font color so it will automatically be converted into white when using the dark theme and black when using the light theme.

Second, because I'm unable to read the whole thread, does it solve the problem of lag/frameskip when loading any audio files like playing SE? It's the huge factor of why I couldn't make a fluid action based games in RGSS3, every time I load a SE, it hiccups a bit especially when a smooth frame update is crucial.
Howdy.

I didn't read through everything, but this system seems to be about speeding up the general performance of RM VX Ace. That's pretty nice but let me tell you that I've downloaded the demo and the game is running at a constant 59 FPS, but it's actually as laggy as if it were only 3 FPS or even less which is kinda strange. Well, sometimes the whole movement even stops completely for a few seconds.

Just wanted to leave this as a feedback. Maybe it helps. Don't know what you're trying to do exactly.
As @Roninator2 said, adjust the Config parameters until the game is running smoothly while both DLL and ATL enabled.

The purpose of the demo is allowing you to do the test by yourself and play around with it, you can also try writing something else in both C and ruby to compare the difference. Just remember what's C's advantage to ensure it really speed up the game.

First thing first, the black font tag makes the entire thread unreadable in the dark theme in this forum. Maybe you should make the text untagged with font color so it will automatically be converted into white when using the dark theme and black when using the light theme.

Second, because I'm unable to read the whole thread, does it solve the problem of lag/frameskip when loading any audio files like playing SE? It's the huge factor of why I couldn't make a fluid action based games in RGSS3, every time I load a SE, it hiccups a bit especially when a smooth frame update is crucial.
Color tags removed, though I would recommend using a dark-theme add-on/extension to make all web pages "darken" 😛
Currently, I'm using a workaround: preload all audio, set the volume to 0 and play them silently at loading screen of my startup (in my game they only lag for the first time play). Maybe another way is calling Audio.se_play in C-level and using another Thread in Ruby then use it call the dll function.
[Access the data in game from DLL]
As the first post mentioned, we can get the memory address of the ruby object by obj.object_id << 1, except Fixnum and Symbol, former one which is basically n * 2 + 1 and the latter one is kinda tricky, see ID2SYM and SYM2ID below.
in ruby.h:

Code:
enum ruby_special_consts {
    RUBY_Qfalse = 0,
    RUBY_Qtrue  = 2,
    RUBY_Qnil   = 4,
    RUBY_Qundef = 6,

    // the value that start with 0x stands for hex number
    RUBY_IMMEDIATE_MASK = 0x03,
    RUBY_FIXNUM_FLAG    = 0x01,
    RUBY_SYMBOL_FLAG    = 0x0e,
    RUBY_SPECIAL_SHIFT  = 8
};

#define ID2SYM(x) ( ( (VALUE)(x)<<RUBY_SPECIAL_SHIFT ) | SYMBOL_FLAG )
#define SYM2ID(x) RSHIFT((unsigned long)(x),RUBY_SPECIAL_SHIFT) // ((ulong)x) >> RUBY_SPECIAL_SHIFT

So in order to get the address of ruby object conveniently, we write some code in our script:
Code:
# Ruby Constants
RUBY_Qfalse = 0
RUBY_Qtrue  = 2
RUBY_Qnil   = 4
RUBY_Qundef = 6

RUBY_IMMEDIATE_MASK = 0x03
RUBY_FIXNUM_FLAG    = 0x01
RUBY_SYMBOL_FLAG    = 0x0e
RUBY_SPECIAL_SHIFT  = 8

# Get address of the object
class Object
  def ptr; object_id << 1; end
end

class TrueClass
  def ptr; return RUBY_Qtrue; end
end

class FalseClass
  def ptr; return RUBY_Qfalse; end
end

class NilClass
  def ptr; return RUBY_Qnil; end
end

# Object id is already VALUE's value (int)
class Fixnum
  def ptr; object_id; end
end

class Symbol
  def ptr; object_id; end
end

# Transfer received address back to ruby object
def VALUE2obj(cvalue)
  return ObjectSpace._id2ref(cvalue >> 1);
end

# Transfer received address back to Symbol
def ID2SYM(cvalue)
  return ObjectSpace._id2ref(cvalue >> RUBY_SPECIAL_SHIFT);
end
this way we only need to call the 'ptr' method while passing that object into our dll, also defined methods transfer the address back to Ruby object, nicely done!....wait, also the C side to handle:
Code:
VALUE load_int(VALUE obj, char* name){
    int re = rgss_obj_ivar_get(obj, rgss_ascii_new_cstr(name));
    return re >> 1;
}

VALUE load_obj(VALUE obj, char* name){
    return rgss_obj_ivar_get(obj, rgss_ascii_new_cstr(name));
}

VALUE set_obj(VALUE obj, char* name, VALUE val){
    return rgss_obj_ivar_set(obj, rgss_ascii_new_cstr(name), val);
}
here rgss_obj_ivar_get is equivalent to instance_variable_get, and rgss_obj_ivar_set is instance_variable_get. Since we'll need them to access the object's instance variable every time we call the function, so we certainly not want to write that long code every time.
Notice that if you want to set the instance variable as Fixnum, you should call INT2FIX(n) or LONG2FIX(n) to get that number back to Ruby style, and the load_int is just also transforming the Fixnum to int after the instance variable load. If you don't want that ">> 1", notice that you should call FIX2LONG instead of FIX2INT.
(
OK, finally we have known the most of essential things, feel free to ask any questions...hope this helps!
I know this is the worst crap shoot in the world here, but I missed the train by several years... Do you still have that demo?

Original thread: https://forums.rpgmakerweb.com/threads/combine-rgss-with-ruby-c-dll-and-speed-up-the-game-like-a-boss.107006/