nodepp icon indicating copy to clipboard operation
nodepp copied to clipboard

Contributing/coffee/question

Open binaryduke opened this issue 1 year ago • 1 comments

Hi. I love this library. Serves my purposes very well.

  1. I'd like to contribute via the BuyMeACoffee link that's mentioned in the blog posts but they seem to be non-functional. This library has potential to support some commercial work that's underway so I'm open to regular support.
  2. Please could you provide some explanation about the use of onMain() - this is a new approach for me and I can't find documentation anywhere about this. My intended usage is:
  • standalone c++ desktop apps using nodepp and Dear ImGUI (so the raylib examples are quite useful)
  • c++ add-ons for existing desktop tools in standalone DLLs. These don't have a main() function

So in both cases, a little explanation around the architecture would be appreciated. Thanks!

binaryduke avatar Jun 21 '25 10:06 binaryduke

Dude, i'm really exited to read your kind words!. It's incredibly rewarding to know that Nodepp is serving your purposes well and that you`re finding it valuable enough to consider contributing. Your interest in regular support for your commercial work is particularly exciting and truly helps in the ongoing development and maintenance of this library.

Regarding the Buy Me a Coffee link, I sincerely apologize for the inconvenience! It seems there might be an issue with the link in some of the older blog posts. i'm actively working on updating all mentions and ensuring that the donation channels are fully functional. In the meantime, the best way to contribute directly is through kofi. I truly appreciate your patience and generosity!

Now, let's talk about onMain() and the architecture behind it, as it's a fundamental concept in Nodepp:

Understanding onMain() in Nodepp

Old school C++ programmers might not like this, but this library isn't for them. Nodepp was designed to bridge the gap between high-level, asynchronous programming paradigms (familiar to developers from languages like JavaScript or Python) and the power of C++. It aims to provide an intuitive, "headache-free" experience for building high-performance, asynchronous applications, even close to the hardware.

Now, The onMain() function is a cornerstone of this philosophy. While traditional C++ programs use main() as their explicit entry point, Nodepp introduces onMain() which is a clever way of setting up your application's entry point and kicking off its powerful Event Loop. It wraps the standard C++ main() function, injecting the necessary Nodepp initialization and cleanup steps automatically.

this is how onMain() function works under the hood

  • Nodepp Desktop | wasm
#define onMain INIT(); int main( int argc, char** args ) { \
    process::start( argc, args ); INIT(); \
    while( !process::empty() ) { \
            process::next(); \
    }   return 0; \
} void INIT
  • Nodepp Arduino
#define onMain loop(){ process::next(); } void setup

Let's break down what each part does:

  • process::start( argc, args )

This is the first essential step in your Nodepp application. process::start() handles the command-line arguments passed to your program, making them incredibly easy to access within your Nodepp environment. It can smartly parse both traditional arguments and environment variables you define directly in the command line.

Imagine you want to set some configuration variables or flags when you launch your app. You can do it like this:

./main ?env_var1=10 ?env_var2=20 arg1 arg2

Now, within your onMain() function, you can retrieve these values:

void onMain(){ 

    process::env::init("./env");

    console::log( "Env Variables:",
        process::env::get("env_var1"), // Outputs: "10" (as string_t)
        process::env::get("env_var2")  // Outputs: "20" (as string_t)
    );

    console::log( "Arguments:",
        process::args[0], // Outputs: "./main" (the program name)
        process::args[1], // Outputs: "arg1" (as string_t)
        process::args[2]  // Outputs: "arg2" (as string_t)
    );
}

This makes managing application configurations and dynamic inputs super straightforward, without needing complex parsing logic on your end.

  • INIT() This is where your application's specific setup code goes! The INIT() is where you`d place the core logic you want to execute when your Nodepp application starts.

  • while( !process::empty() ) and process::next() Is the event loop. This function keeps your application running, continuously processing asynchronous tasks, timers, and I/O operations until all tasks are complete or process::exit() is explicitly called to shut down the application gracefully.

It ensures that your Nodepp application efficiently handles multiple concurrent operations without blocking, making the most of your hardware resources.

Going Deeper: Manual Event Loop Control

now, what if you want to manually control the nodepp's internal event loop?.

Well, since onMain() simplifies the setup, Nodepp also provides the flexibility to manage the Event Loop yourself. This is useful if you have highly specialized needs or want a deeper understanding of how Nodepp operates at a lower level.

You can explicitly control the Event Loop using process::add() to queue tasks and process::next() to advance the loop.

there are also other kind of task's queues like:

  • process::task::add(): used for microtasks. ( timer, promices, etc )
  • process::poll::add(): used for IO files.
  • process::loop::add(): used for normal tasks. ( process::add() )
#include <nodepp/nodepp.h>

using namespace nodepp;

int main(){

    // Add an asynchronous task to the process queue
    process::add([=](){
        coStart // Marks the beginning of a coroutine block

        coDelay(1000); // Asynchronously waits for 1000 milliseconds (1 second)
        console::log( "Hello world!"); // Logs a message
        coGoto(0); // Reschedules this task to run again from the beginning (creates a loop)

        coStop // Marks the end of a coroutine block
    });

    // Manually run the event loop until there are no more pending tasks
    while( !process::empty() ) {
            process::next(); // Processes the next available event in the queue
    }

    return 0;
}

In this example, we directly define and start a task using process::add() (which uses Nodepp's coroutine syntax coStart/coStop). The while loop continuously calls process::next() to drive the Event Loop, ensuring tasks are processed until the queue is empty.

This level of control demonstrates Nodepp's versatility, allowing you to choose between simplified setup with onMain() or granular control over the Event Loop when needed.

Your Intended Usage Scenarios & Architectural Guidance:

When integrating with GUI libraries like Dear ImGUI or Raylib, which typically have their own blocking event loops for rendering and input, you have two primary patterns:

Nodepp Driving the UI Loop

This pattern positions Nodepp's Event Loop as the primary orchestrator of your application, including UI updates. It's ideal when your application's core logic is heavily asynchronous, and you want Nodepp to manage the entire lifecycle.

If a GUI library's main loop (e.g., while(!WindowShouldClose()) in Raylib) is non-blocking or can be integrated into callbacks, you can let Nodepp's Event Loop be the primary driver. You`ll initialize the GUI library within your onMain() and then use Nodepp's coroutines or timers to continuously trigger your rendering, game logic updates, and ImGUI frame processing. This requires careful management to ensure the UI remains responsive while Nodepp handles all asynchronous tasks.

Example: Raylib Integration with Nodepp Driving

This example shows how Nodepp can directly manage the game loop for a Raylib application. The rendering and game logic are handled within a process::add() coroutine, which process::next() will schedule in the event loop.

#include <nodepp/nodepp.h> // include necessary core Nodepp functionality

// Include Raylib headers without conflicts by using a namespace
namespace rl {
#include <raylib/raylib.h>
#include <raylib/raymath.h> // For any math functions if needed
}

using namespace nodepp; // To use Nodepp functions without prefix

// Define custom events for clarity and modularity
event_t<>      onClose;  // Event for when the window should close
event_t<float> onLoop;   // Event for game logic updates, passing delta time
event_t<>      onDraw;   // Event for drawing operations

void onMain() {
    // 1. Initialize Raylib window settings
    rl::InitWindow(300, 400, "Snake Game");
    rl::SetTargetFPS(60); // Cap frame rate

    // 2. Attach callbacks to your custom events
    onLoop([](float delta) { /* Your game logic goes here, using `delta` for frame-independent updates */ });
    onDraw([]() { rl::ClearBackground(BLACK); /* Your drawing commands go here */ });
    onClose([]() {
        console::log("Window closing, exiting Nodepp...");
        process::exit(1); // Signal Nodepp to shut down gracefully
    });

    // 3. Add the main game loop as a Nodepp coroutine
    process::add([]() {
        // Check if the window close button is pressed
        if (rl::WindowShouldClose()) {
            onClose.emit(); // Emit the close event
        }

        coStart // Marks the beginning of this coroutine's execution block

        // Emit onLoop event with frame time for game state updates
        onLoop.emit(rl::GetFrameTime());
        coNext; // Yield control back to the Event Loop, then resume here on next tick

        // Begin drawing for the current frame
        rl::BeginDrawing();
        // Emit onDraw event for rendering calls
        onDraw.emit();
        // End drawing for the current frame
        rl::EndDrawing();

        coGoto(0); // Loop back to the beginning of this coroutine for the next frame

        coStop // Marks the end of the coroutine's execution block
    });
    // Nodepp's main loop (implicitly started by the onMain macro) will now manage this coroutine.
}

Nodepp on a Separate Thread

This pattern is often more straightforward for complex GUI applications where the GUI framework has a dedicated, blocking main loop that needs to run on a thread.

In this scenario, you can leverage Nodepp's worker threads to run your GUI framework on a dedicated thread. Meanwhile, Nodepp's main event loop can operate on the primary thread, handling background tasks like network communication, file operations, or heavy computations. This setup ensures your GUI remains responsive while Nodepp efficiently manages your application's asynchronous operations.

Example: Tcl/Tk Integration with Nodepp on a Worker Thread

This example demonstrates how Nodepp can be used to manage background tasks while a Tcl/Tk GUI runs on a separate thread.

#include <nodepp/nodepp.h> // Core Nodepp functionalities
#include <nodepp/worker.h> // For worker thread management

#include <tcl.h> // Tcl library headers
#include <tk.h>  // Tk library headers

using namespace nodepp; // To use Nodepp functions without prefix

void onMain(){

    // Initialize Tcl and Tk libraries
    // Tcl_FindExecutable helps Tcl locate its necessary files
    Tcl_FindExecutable(process::args[0]);
    // Create a new Tcl interpreter instance
    Tcl_Interp *interp = Tcl_CreateInterp();

    // --- Your Tcl/Tk GUI Logic ---

    worker::add([=]() { // The lambda captures `interp` by value
        coStart // Marks the beginning of the worker coroutine

        // Tk_MainLoop() is a blocking function that starts the Tk event loop.
        // It will run until the Tk window is closed or an exit command is issued.
        Tk_MainLoop();
        console::log("Tk_MainLoop has exited.");

        // Clean up the Tcl interpreter once the Tk_MainLoop finishes
        Tcl_DeleteInterp(interp);
        console::log("Tcl interpreter deleted.");

        coStop // Marks the end of the worker coroutine
    });

    // Any Nodepp asynchronous tasks defined here in onMain() will run
    // on Nodepp's main event loop, concurrently with the Tk_MainLoop
    // running on the worker thread.
    process::add([=](){
    coStart
        console::log("Nodepp is now running alongside Tk GUI.");
    coStop
    });

}

NOTE: remember include pthread in your compilation command.

This pattern demonstrates how Nodepp provides flexible concurrency, allowing it to manage background tasks while other libraries handle their own blocking loops on separate threads.

C++ Add-ons for Existing Desktop Tools (DLLs)

This is where Nodepp's Event Loop truly shines for background tasks within a DLL, as DLLs, by definition, don't have their own main() function and must not block the host application. Nodepp is perfectly suited to power the asynchronous operations of your add-on without complex explicit lifecycle management.

Just Drive the Event Loop

Unlike a standalone application, when Nodepp runs within a DLL, you don't necessarily need to explicitly call process::start() for initialization or nodepp::exit() for shutdown. Nodepp's internal components, being C++ objects, handle their own setup via constructors when your DLL is loaded and cleanup via destructors when it's unloaded.

The core mechanism to keep Nodepp active and processing tasks is to repeatedly execute process::next(). This advances Nodepp's internal Event Loop, ensuring that all scheduled asynchronous operations (timers, network events, coroutines, etc.) are processed efficiently.

extern "C" __declspec(dllexport) bool TriggerAsyncAction() {
    // Schedule a task on Nodepp's event loop from the host thread
    process::next(); 
    // to know if there are available task
    return process::empty();
}

This simplified architecture allows your Nodepp add-on to run complex asynchronous logic entirely in the background, processing events as long as the process::next() call is made, without interfering with the host application's responsiveness.

I truly hope this detailed explanation, incorporating the "under the hood" mechanics, clarifies the role of onMain() and provides a solid foundation for your commercial projects. Please don't hesitate to reach out if you have any more questions as you delve deeper. i'm excited to see what you build with Nodepp!

EDBC.

EDBCREPO avatar Jun 21 '25 23:06 EDBCREPO