Blog

Logic Nodes and JavaScript

2017-07-27

Blend4Web features an outstanding visual logic editor which you can use to develop programs without even leaving Blender. This is enough for projects of lesser complexity. However, you can do so much more with JavaScript with its direct access to the engine API.

This brings us to the question: is there a way to combine the simplicity of visual programming with sheer power of the JavaScript code? And, as it turns out, there certainly is. The developers of Blend4Web have provided us with such an option. So why don’t we take a look at it?

Node-Based Logic

The main element to connect node logic with JavaScript is the JS Callback node. This node is used to call a specified function from the program code and to pass parameters to it. As the function performs its work, JS Callback patiently waits for it to finish. After the task is complete, the function returns control back to the JS Callback node, and the logic node chain continues its work.

Let’s take a look on a most simple example of an interaction like this.

Let’s assume that our scene contains an object that should run a certain function when selected. The code of the function will also receive a text message, something like “Hello World!”… or maybe “Hello Script!” will be more appropriate.

First, let’s make a logic chain that creates a variable and monitors if the object is selected.

This is a very simple logic setup. First of all, it initializes the R1 register and assigns the “Hello Script!” text as its value. After this, the control is passed to the Switch Select node that waits for the object Cube to be selected. If it is selected, control is passed to the next node; if it isn’t, the node continues to wait.

The next stop is the JS Callback node itself!

First, we need to specify the name of the function that the node will call. This should be done in the Callback ID field. If you need some data to be passed to the function, you should add it to the In Params field.

Each variable occupies a separate slot; slots can be added with the “+” button. JS Callback can pass not only variables, but entire scene objects as well (in the form of arrays). In our case, we need to set the R1 register in the first slot.

Now, let’s assume that the JS Callback node has finished its work and received some output from the function it called. Now, just to be sure, let’s output the value of the R1 register to the browser console using the Console Print node.

The complete logic node setup should look like this:

JavaScript Code

As a specific module is required for JavaScript and node logic to interact, we have to import this module first.

var m_logic = require("logic_nodes");

Now, let’s register our function. This should be done before the scene itself is loaded:

m_logic.append_custom_callback("node", node_cb);

As you can see, it has the “node” identifier that has been mentioned in the JS Callback node, and the name of the function as well.

And here is the function itself:

function node_cb(input, output) {
    console.log (input[0]);
    output[0] = "Hey Logic!";
}

Note that the JS Callback node passes and receives values as an array. The Input[0] variable here contains the value of the R1 register that will be shown in the browser console. Then, the function returns output[0] with some text message.

The JS Callback node receives the result, while the next node Console Print outputs the text to the browser console.

And here is the complete listing of the script:

"use strict"

// register the application module
b4w.register("logic_nodes_js_main", function(exports, require) {

// import modules used by the app
var m_app       = require("app");
var m_cfg       = require("config");
var m_data      = require("data");
var m_preloader = require("preloader");
var m_ver       = require("version");
var m_logic     = require("logic_nodes");

// detect application mode
var DEBUG = (m_ver.type() == "DEBUG");

// automatically detect assets path
var APP_ASSETS_PATH = m_cfg.get_assets_path("logic_nodes_js");

/**
 * export the method to initialize the app (called at the bottom of this file)
 */
exports.init = function() {
    m_app.init({
        canvas_container_id: "main_canvas_container",
        callback: init_cb,
        show_fps: DEBUG,
        console_verbose: DEBUG,
        autoresize: true
    });
}

/**
 * callback executed when the app is initialized 
 */
function init_cb(canvas_elem, success) {

    if (!success) {
        console.log("b4w init failure");
        return;
    }

    m_preloader.create_preloader();

    // ignore right-click on the canvas element
    canvas_elem.oncontextmenu = function(e) {
        e.preventDefault();
        e.stopPropagation();
        return false;
    };
    m_logic.append_custom_callback("node", node_cb);
    load();
}

/**
 * load the scene data
 */
function load() {
    m_data.load(APP_ASSETS_PATH + "logic_nodes_js.json", load_cb, preloader_cb);
}

/**
 * update the app's preloader
 */
function preloader_cb(percentage) {
    m_preloader.update_preloader(percentage);
}

/**
 * callback executed when the scene data is loaded
 */
function load_cb(data_id, success) {

    if (!success) {
        console.log("b4w load failure");
        return;
    }

    m_app.enable_camera_controls();

    // place your code here

}

function node_cb(input,output) {
    console.log (input[0]);
    output[0] = " Hey Logic!";
}

});

// import the app module and start the app by calling the init method
b4w.require("logic_nodes_js_main").init();
Comments
15 jul. 2023 12:59
It is very difficult to understand completely in programming, especially in languages. I had problems with assembly language, but I found a way out of the situation. I must say, I am incredibly impressed with the exceptional service provided by ProgrammingAssignment for assembly language homework help (https://www.programmingassignment.net/services/assembly-language-homework-help/)! The website's user-friendly interface makes it effortless to navigate through their offerings, ensuring a smooth and hassle-free experience for students seeking assistance.
08 aug. 2023 13:39
I use Frase to find certain keywords. Then, I get suggestions to help improve my chances of ranking higher. After that, I use an AI essay writer like ChatGPT to make content. This way, I have a better shot at ranking well for those keywords. It's really effective if I do it for each article, and it helps me become an expert in my field! 🤗
09 aug. 2023 13:38
Thanks for your details. You may also learn vari0us programming with https://www.sevenmentor.com
10 aug. 2023 11:08
This piece will tell you more about what's going on. I want to find out more about that here io games unblocked
14 aug. 2023 11:16
As the language matured, JavaScript developers established libraries, frameworks, and programming practices, and started using the language outside of web browsers. Today, you can use JavaScript to do development both on the client smash karts and server side.
25 sep. 2023 21:48
When delving into the world of logic nodes and JavaScript, it's a bit like navigating the intricate strategies of slot games at Sugar Casino, one of the best casinos https://sugarcasinos.com/ in the Netherlands. Just as logic nodes serve as the building blocks for complex programming tasks, the spinning reels of a slot machine are composed of various elements that must align perfectly to trigger a win. In both cases, understanding the underlying mechanisms and making strategic choices can lead to success. Just as a programmer meticulously crafts code, a seasoned slot player employs strategies to maximize their chances of hitting that coveted jackpot.
22 nov. 2023 04:31
This gives me a higher chance of ranking highly for those keywords. If I do that for each article, it's quite effective, and it helps me become an expert in my geometry dash subzero subject!
18 dec. 2023 09:12
Combining logic nodes with JavaScript is a potent synergy for dynamic and responsive programming. Logic nodes provide a visual, intuitive interface, while JavaScript injects flexibility and spectrum tv billing problems complex functionalities. This hybrid approach bridges accessibility and power, offering developers a versatile toolkit for crafting interactive and sophisticated applications with efficiency and precision.
31 mar. 2024 14:29
Thanks for your post and waiting for more exciting response from members.
18 may. 2024 04:23
Explore a world of colorful levels and challenging obstacles in Pixel Speedrun, the online running game that's easy to learn but difficult to master.
Please register or log in to leave a reply.