js2glsl icon indicating copy to clipboard operation
js2glsl copied to clipboard

Translating JavaScript classes to GLSL

Open jarble opened this issue 5 years ago • 0 comments

I recently discovered a way to translate JavaScript classes into GLSL, but it seems that js2glsl cannot do this yet.

A JavaScript class could be written like this:

class Stuff{
    
    constructor(a,b){
        this.a=a;
        this.b=b;
    }
    
    add(){
        return this.a + this.b;
    }
}

And then JS2GLSL could generate a struct with a "constructor" and an "instance method:"

struct Stuff{
    float a;
    float b;
};
Stuff new(int a,int b){
    Stuff self;
    self.a=a;
    self.b=b;
    return self;
}
    
int add(Stuff self){
    return self.a+self.b;
}

Then a "class" could be initialized in GLSL:

Stuff an_instance = new(1.0,2.0);

GLSL allows functions to be overloaded, so it's possible to define multiple "classes" and "constructors" in this way. Since this is a reserved word in GLSL, I replaced it with self.

jarble avatar May 21 '19 17:05 jarble