Posts
Search
Contact
Cookies
About
RSS

LWJGL everywhere even from javascript...

Added 25 Oct 2015, 9:02 p.m. edited 19 Jun 2023, 2:53 a.m.
Its rather useful to have a game "engine" that's directed from a language like JavaScript. Scripting languages have a number of advantages they are great for quickly nailing together logic while some other component does the heavy lifting. This power also allows third parties greater accessibility, allowing people to "mod" a game while the core game remains unabused! Embedded scripting has come a very long way and accessing Java classes and methods from JavaScript couldn't be easier, add to that the fact that Nashorn is several orders of magnitude faster than the previous engine, and you have a powerful combination. While you probably wouldn't want to write a whole game in Javascript, leaving some key resources and objects public and having a few hooks that evaluate custom scripts, is fairly trivial stuff considering the customisation potential you are handing your end users, its often the "modding" community that drives the extended sales of games especially in the indie arena. Actually executing a script from Java is not a difficult exercise
import javax.script.*;

public class Test1 {
  public void run() {
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("nashorn");
    System.out.println(engine.getFactory().getEngineName());
    try { engine.eval(new java.io.FileReader("script.js")); } 
    catch (ScriptException se) { System.out.println(se.getMessage()); } 
    catch (java.io.FileNotFoundException fe) { System.out.println("can't find the script!"); }
  }
  public static void main(String[] args) { new Test1().run(); }
}
not really much that needs explaining the interesting bits are in the script itself... the first thing we need is to reference the various bits of LWJGL we need to access
var Sys = Java.type("org.lwjgl.Sys")
var GLFW = Java.type("org.lwjgl.glfw.GLFW")
var GL = Java.type("org.lwjgl.opengl.GL")
var GL11 = Java.type("org.lwjgl.opengl.GL11")
as you'd expect a great deal of LWJGL's functions are static so you can just set off using them immediately
if (GLFW.glfwInit() != GL11.GL_TRUE) {
  print("couldn't spin up GLFW - oh the humanity!")
  return
}
and it really is that straight forward ! I've made a project that's an adaptation of the hello world LWJGL example, you'll need to add the jar and native folders from the LWJGL archive. You can download it here Oh and the Makefile....??? well I was lazy! (it was a very quick hack!) Enjoy!