13#include "common/config.h"
19#if EVENGINE_CMDLINE_DEVTOOLS && !defined(EVENGINE_ANDROID) && !defined(EVENGINE_IOS) && !defined(__EMSCRIPTEN__)
24#include <simplesquirrel/simplesquirrel.hpp>
34#if defined(__EMSCRIPTEN__)
35#include <emscripten.h>
48ssq::VM* gFrameVm =
nullptr;
49ssq::Function* gFrameFunc =
nullptr;
55void webgpuFrameTick() {
56 if (!gFrameVm || !gFrameFunc || gFrameFunc->isEmpty())
return;
59 EM_ASM({
if (
window.hideEVELoading)
window.hideEVELoading(); });
62 ssq::Object
r = gFrameVm->callFunc(*gFrameFunc, *gFrameVm);
63 if (
r.getType() == ssq::Type::BOOL) keep =
r.toBool();
64 }
catch (
const std::exception& e) {
65 fprintf(stderr,
"EVEngine: eve_frame error: %s\n", e.what());
68 if (!keep) emscripten_cancel_main_loop();
81constexpr SQInteger kPlaygroundResultCap = 8192;
82char gPlaygroundResult[kPlaygroundResultCap];
84const char* setPlaygroundResult(
const char*
text) {
86 std::snprintf(gPlaygroundResult, kPlaygroundResultCap,
"%s",
text);
87 return gPlaygroundResult;
93void playgroundApply(
const char*
source) {
94 if (!gPlaygroundVm || !
source)
return;
96 const SQInteger
top = sq_gettop(
vm);
98 std::ofstream
out(
"/game/main.nut", std::ios::binary | std::ios::trunc);
100 std::fprintf(stderr,
"playground: cannot open /game/main.nut for writing\n");
105 }
catch (
const std::exception& e) {
106 std::fprintf(stderr,
"playground: write /game/main.nut failed: %s\n", e.what());
111 sq_pushroottable(
vm);
112 sq_pushstring(
vm, _SC(
"handle_change"), -1);
113 if (SQ_SUCCEEDED(sq_get(
vm, -2))) {
115 HSQOBJECT handleChange;
116 sq_getstackobj(
vm, -1, &handleChange);
126const char* playgroundEval(
const char*
source) {
127 if (!gPlaygroundVm)
return "engine not ready";
130 const SQInteger
top = sq_gettop(
vm);
136 const std::string wrapped = std::string(
"return (") +
source +
");";
137 const char* evalSource = wrapped.c_str();
138 SQInteger evalLen =
static_cast<SQInteger
>(wrapped.size());
140 vm, evalSource, evalLen, _SC(
"playground_eval"), SQTrue));
144 vm,
source,
static_cast<SQInteger
>(std::strlen(
source)), _SC(
"playground_eval"), SQTrue));
147 const SQChar* msg =
nullptr;
148 if (sq_gettype(
vm, -1) == OT_STRING) sq_getstring(
vm, -1, &msg);
149 std::snprintf(errbuf,
sizeof(errbuf),
"compile error: %s", msg ? msg :
"unknown");
151 return setPlaygroundResult(errbuf);
153 sq_pushroottable(
vm);
154 if (SQ_FAILED(sq_call(
vm, 1, SQTrue, SQTrue))) {
155 const SQChar* msg =
nullptr;
156 if (sq_gettype(
vm, -1) == OT_STRING) sq_getstring(
vm, -1, &msg);
157 std::snprintf(errbuf,
sizeof(errbuf),
"eval error: %s", msg ? msg :
"unknown");
159 return setPlaygroundResult(errbuf);
161 if (sq_gettype(
vm, -1) == OT_NULL) {
163 return setPlaygroundResult(
"null");
165 if (SQ_FAILED(sq_tostring(
vm, -1))) {
167 return setPlaygroundResult(
"(unprintable result)");
169 const SQChar*
result =
nullptr;
172 return setPlaygroundResult(
"(unprintable result)");
174 const char*
out = setPlaygroundResult(
result);
180const char* playgroundRead(
const char*
path) {
181 if (!gPlaygroundVm || !
path)
return "";
183 std::ifstream in(
path, std::ios::binary);
184 if (!in)
return setPlaygroundResult(
"");
185 std::ostringstream ss;
187 const std::string
text = ss.str();
188 const size_t n = std::min(
text.size(),
static_cast<size_t>(kPlaygroundResultCap - 1));
189 std::memcpy(gPlaygroundResult,
text.data(),
n);
190 gPlaygroundResult[
n] =
'\0';
191 return gPlaygroundResult;
193 return setPlaygroundResult(
"");
199int playgroundReadBytes(
const char*
path,
void* dst,
int dstCap) {
200 if (!gPlaygroundVm || !
path || !dst || dstCap <= 0)
return 0;
202 std::ifstream in(
path, std::ios::binary);
204 std::ostringstream ss;
206 const std::string
text = ss.str();
207 const int n = std::min<int>(
static_cast<int>(
text.size()), dstCap);
208 std::memcpy(dst,
text.data(),
n);
217void playgroundCapture(
const char*
path) {
218 if (!gPlaygroundVm || !
path)
return;
219 auto* gfx = eve::ModuleManager::getInstance<eve::graphics::Graphics>(
"Graphics");
220 if (gfx) gfx->beginFrameReadback(
path);
223int playgroundReadbackStatus() {
224 if (!gPlaygroundVm)
return 0;
225 auto* gfx = eve::ModuleManager::getInstance<eve::graphics::Graphics>(
"Graphics");
226 return gfx ? gfx->frameReadbackStatus() : 0;
231void playgroundSetPaused(
int paused) {
232 if (!gPlaygroundVm)
return;
234 const SQInteger
top = sq_gettop(
vm);
235 sq_pushroottable(
vm);
236 sq_pushstring(
vm, _SC(
"eve_playground_paused"), -1);
237 sq_pushbool(
vm, paused != 0);
238 sq_newslot(
vm, -3, SQFalse);
245void playgroundResetScene() {
246 if (!gPlaygroundVm)
return;
248 const SQInteger
top = sq_gettop(
vm);
250 auto *
table = ecs::current();
251 auto destroyAll = [&](
auto *mgr) {
252 if (!mgr || !mgr->registy)
return;
253 auto *reg =
dynamic_cast<ecs::IRegistryComponentBuffer *
>(mgr->registy);
255 std::vector<ecs::Entity *>
entities;
256 const uint32_t
n = reg->entity_count();
258 for (uint32_t i = 0; i <
n; ++i) {
259 if (ecs::Entity *e = reg->entity_at(i))
entities.push_back(e);
261 for (ecs::Entity *e :
entities)
ecs::DestroyEntity(e);
267 sq_pushroottable(
vm);
268 sq_pushstring(
vm, _SC(
"__pg"), -1);
269 sq_deleteslot(
vm, -2, SQFalse);
279EMSCRIPTEN_KEEPALIVE
void eve_playground_apply(
const char*
source) { playgroundApply(
source); }
280EMSCRIPTEN_KEEPALIVE
const char* eve_playground_eval(
const char*
source) {
281 return playgroundEval(
source);
283EMSCRIPTEN_KEEPALIVE
const char* eve_playground_read(
const char*
path) {
284 return playgroundRead(
path);
286EMSCRIPTEN_KEEPALIVE
int eve_playground_read_bytes(
const char*
path,
void* dst,
int dstCap) {
287 return playgroundReadBytes(
path, dst, dstCap);
289EMSCRIPTEN_KEEPALIVE
void eve_playground_capture(
const char*
path) { playgroundCapture(
path); }
290EMSCRIPTEN_KEEPALIVE
int eve_playground_readback_status() {
return playgroundReadbackStatus(); }
291EMSCRIPTEN_KEEPALIVE
void eve_playground_set_paused(
int paused) { playgroundSetPaused(paused); }
292EMSCRIPTEN_KEEPALIVE
void eve_playground_reset() { playgroundResetScene(); }
297#if defined(EVENGINE_ANDROID)
298#include <android/log.h>
299#define EVE_ANDROID_LOGE(...) __android_log_print(ANDROID_LOG_ERROR, "EVEngine", __VA_ARGS__)
300#elif defined(EVENGINE_IOS) || defined(__EMSCRIPTEN__)
302#define EVE_ANDROID_LOGE(...) do { fprintf(stderr, "EVEngine: "); fprintf(stderr, __VA_ARGS__); fprintf(stderr, "\n"); } while (0)
304#define EVE_ANDROID_LOGE(...) ((void)0)
318 void setup(CLI::App& app, std::shared_ptr<CLI::Formatter> formatter)
override {
319 auto run = app.add_subcommand(
"run",
"Run game under current path");
320 run->allow_extras()->formatter(formatter);
321 run->add_flag(
"--no-window",
no_window,
"Run script only, no window mode");
322 run->add_flag(
"--debug",
debug,
"debug mode (slicer + pause/breakpoints/snapshot/MCP)");
324 "Start Debug Adapter Protocol server on port (implies --debug)");
326 "Start Model Context Protocol server on port for AI agents (implies --debug)");
328 "Remote hot-reload dev server URL (eve dev), e.g. http://192.168.1.5:8765");
329 run->add_option(
"-l,--log",
log_path,
"log messages into a file");
330 run->add_option(
"-r,--root",
root_path,
"give a entry script instead of using the system default one");
334 auto run = app.get_subcommand(
"run");
341 cerr <<
"Cannot open root script: " <<
root_path << endl;
344 std::string load_root((istreambuf_iterator<char>(ifs)), (istreambuf_iterator<char>()));
362 std::string devServer) {
363 std::fprintf(stderr,
"[startup] Run() begins at process clock %.1f ms\n",
364 (
double) std::clock() * 1000.0 / (
double) CLOCKS_PER_SEC);
365#if !EVENGINE_CMDLINE_DEVTOOLS
366 if (debug || dapPort > 0 || mcpPort > 0) {
367 std::cerr <<
"eve run: debugging requires the devtools module" << std::endl;
377 std::string gameDir =
path;
378 std::string archivePath;
379 eve::recordLogEvent(
"info",
"eve run starting: " + (gameDir.empty() ? std::string(
".") : gameDir));
384 gameDir = std::filesystem::current_path(ec).string();
386 gameDir = std::filesystem::absolute(
path, ec).string();
387 if (ec) gameDir =
path;
389 std::filesystem::path
gp(gameDir);
390 if (std::filesystem::is_regular_file(
gp, ec) &&
gp.extension() ==
".eve") {
392 archivePath =
gp.string();
393 gameDir =
gp.parent_path().string();
395 std::filesystem::path bundled =
gp /
"game.eve";
396 if (std::filesystem::is_regular_file(bundled, ec))
397 archivePath = bundled.string();
403 if (!gameDir.empty() && gameDir !=
".") {
405 std::filesystem::current_path(gameDir, ec);
407 cerr <<
"Cannot chdir to game path '" << gameDir <<
"': " << ec.message() << endl;
408 EVE_ANDROID_LOGE(
"Cannot chdir to game path '%s': %s", gameDir.c_str(), ec.message().c_str());
415 auto *fs = eve::filesystem::Filesystem::create();
417 if (!archivePath.empty()) {
419 std::ifstream ifs(archivePath, std::ios::binary);
421 cerr <<
"Cannot open game archive: " << archivePath << endl;
424 std::vector<char>
bytes((std::istreambuf_iterator<char>(ifs)),
425 std::istreambuf_iterator<char>());
426 if (
bytes.empty() || !fs->setSourceFromMemory(
bytes.data(),
bytes.size())) {
427 cerr <<
"Failed to mount game archive from memory: " << archivePath << endl;
432 auto cwd = std::filesystem::current_path(ec);
435 fs->setSource(cwd.string());
441 Runtime runtime(8192, ssq::Libs::ALL);
444 runtime.initialize();
446#if EVENGINE_CMDLINE_DEVTOOLS && !defined(EVENGINE_ANDROID) && !defined(EVENGINE_IOS) && !defined(__EMSCRIPTEN__)
449 dt.attach(runtime,
true);
450 dt.exposeScriptApi(runtime.vm());
452 const int bound =
dt.startDap(
static_cast<uint16_t
>(dapPort));
454 cerr <<
"DAP listening on 127.0.0.1:" << bound << endl;
458 if (!
dt.dap().waitUntilConfigured(15000))
459 cerr <<
"DAP: timed out waiting for client; starting anyway" << endl;
461 cerr <<
"Failed to start DAP server on port " << dapPort << endl;
466 dt.mcp().setGameRoot(std::filesystem::current_path().
string());
469 const int bound =
dt.startMcp(
static_cast<uint16_t
>(mcpPort));
471 cerr <<
"MCP listening on 127.0.0.1:" << bound
472 <<
" (newline JSON-RPC; use tools/eve-mcp for Cursor stdio)" << endl;
474 cerr <<
"Failed to start MCP server on port " << mcpPort << endl;
485 ssq::Table
eve = runtime.table(
"eve");
490 eve.addFunc(
"log", [](
const std::string&
level,
const std::string& msg) {
493 eve.addFunc(
"reloadScriptModule", [&runtime](
const std::string&
path) {
494 std::string canonical;
497 throw std::runtime_error(
error);
498 return !runtime.scriptModules().reloadAffected(canonical).empty();
502 eve.addFunc(
"startEditorHost", [&runtime, gameDir]() {
503 auto*
host = eve::cap::query<eve::IEditorHost>();
504 if (!
host)
return std::string(
"error: editor host unavailable");
505 host->start(runtime.vm(), gameDir,
true);
506 host->exposeScriptApi(runtime.vm());
507 return std::string(
"ok");
513 eve.set(
"devServerArg", devServer);
514 const char* bench = std::getenv(
"EVE_BOOT_BENCH");
515 eve.set(
"packageCheck", std::getenv(
"EVE_PACKAGE_CHECK") !=
nullptr);
516 eve.set(
"bootBench", bench && bench[0] !=
'\0' && bench[0] !=
'0');
517#if defined(__EMSCRIPTEN__)
520 eve.set(
"hostDrivesFrames",
true);
522 eve.set(
"hostDrivesFrames",
false);
529 ssq::Table
eve = runtime.table(
"eve");
530 eve.set(
"moduleList", runtime.root().find(
"eve_modules"));
531 eve.set(
"moduleContract", runtime.root().find(
"eve_module_contract"));
537 std::fprintf(stderr,
"[startup] load.nut begins at process clock %.1f ms\n",
538 (
double) std::clock() * 1000.0 / (
double) CLOCKS_PER_SEC);
539 runtime.runSource(std::move(
root),
"load.nut");
540 if (std::getenv(
"EVE_PACKAGE_CHECK")) {
541 if (runtime.root().find(
"_frame_count").toInt() < 30)
542 throw std::runtime_error(
"Package acceptance did not complete 30 frames");
543 std::cout <<
"[package-check] passed: 30 frames\n";
545#if !defined(EVENGINE_ANDROID) && !defined(EVENGINE_IOS) && !defined(__EMSCRIPTEN__)
546 bool editorHostDrive =
false;
548 editorHostDrive = runtime.root().find(
"config").toTable().find(
"editorHost").toBool();
551 if (editorHostDrive) {
552 auto*
host = eve::cap::query<eve::IEditorHost>();
554 std::cerr <<
"config.editorHost=true but the editor host is unavailable\n";
557 if (!
host->isWindowOpen()) {
558 std::cerr <<
"editor host did not open a window "
559 "(eve_init should call eve.host.applyEditor)\n";
562 while (!
host->exitRequested() &&
host->isWindowOpen())
host->frame();
566#if defined(__EMSCRIPTEN__)
571 gFrameVm = &runtime.vm();
572 gFrameFunc =
new ssq::Function(runtime.vm().find(
"eve_frame").toFunction());
573 gPlaygroundVm = runtime.handle();
576 EM_ASM({
if (window.eveEngineReady) window.eveEngineReady(); });
577 emscripten_set_main_loop(&webgpuFrameTick, 0, 1);
579#if EVENGINE_CMDLINE_DEVTOOLS && !defined(EVENGINE_ANDROID) && !defined(EVENGINE_IOS) && !defined(__EMSCRIPTEN__)
583 }
catch (
const std::exception& e) {
584 std::string what = e.what() ? e.what() :
"unknown exception";
586#if EVENGINE_CMDLINE_DEVTOOLS && !defined(EVENGINE_ANDROID) && !defined(EVENGINE_IOS) && !defined(EVENGINE_WEBGPU)
593 std::string report =
dt.lastReport();
594 if (report.empty()) report =
dt.notifyError(what);
595 cerr << report << endl;
598 cerr <<
"Run failed: " << what << endl;
601 cerr <<
"Run failed: " << what << endl;
607#if EVENGINE_CMDLINE_DEVTOOLS && !defined(EVENGINE_ANDROID) && !defined(EVENGINE_IOS) && !defined(EVENGINE_WEBGPU)
609 const std::string report =
611 cerr << report << endl;
614 cerr <<
"Run failed: unknown exception" << endl;
617 cerr <<
"Run failed: unknown exception" << endl;
struct SQVM * HSQUIRRELVM
Persistent, thread-safe record of engine crash and problem events.
std::vector< ecs::EntityHandle > entities
#define EVE_ANDROID_LOGE(...)
The single Squirrel projection for common Result, Status and Value.
EVENGINE_API_FOUNDATION public API.
命令行模块(eve.cmd):run / build / package / test / zip / dev-server 等子命令入口。
static std::string get_remaining(CLI::App *sub, std::string default_path=".")
子命令剩余位置参数。
unsigned getArgc()
Returns the argc.
int Run(std::string path, std::string root, bool debug=false, int dapPort=0, int mcpPort=0, std::string devServer="")
运行游戏(debug 时附加 DAP/MCP 端口)。
EVENGINE_API_BACKENDS public API.
Declarative 3D light. Collected by RenderSystem3D (max 8 per frame). type: "point" | "dir" | "spot" (...
EVENGINE_API_BACKENDS public API.
static SQRESULT compileBuffer(HSQUIRRELVM vm, const SQChar *source, SQInteger size, const SQChar *sourceName, SQBool raiseError)
Unified raw-VM entry used by REPL, debugger, MCP, and editor adapters.
static bool canonicalize(const ScriptModuleRequest &request, std::string &output, std::string &error)
Normalizes a logical module URI and rejects root traversal.
EVENGINE_API_FOUNDATION void startVulkanInstanceWarmup()
Kick off asynchronous VkInstance creation if a backend registered.
void installScriptFileApi(ssq::VM &vm)
用 PhysFS 版本覆盖 Squirrel 的 file / dofile / loadfile 全局, 使脚本与资源从已挂载的游戏源(真实目录或内存挂载的 .eve 归档)解析; PhysFS 中不...
std::unordered_map< std::string, SkillDefinition > & table()
SQRESULT callFunction(HSQUIRRELVM vm, const HSQOBJECT &fn, const Receiver &receiver, Args &&... args)
Call a script function, deriving sq_call's parameter count from the pushes.
constexpr RootTable rootTable
WidgetDesc window(std::string title, std::vector< WidgetDesc > children, std::string id)
Top-level window widget with a title bar.
Build metadata (engine git commit, build time, third-party version).
const char * async_content
const char * load_content
const char * module_list_content
const char * scene_director_content
void recordLogEvent(const std::string &level, const std::string &message)
Appends a timestamped event line to the crash/error log.
const char * demo_content
One eve <subcommand> handler: CLI setup + argument parsing.
void setup(CLI::App &app, std::shared_ptr< CLI::Formatter > formatter) override
Registers options on the CLI11 sub-app.
int parse(CLI::App &app, Cmdline &cmd) override
Parses arguments and runs the command; returns the exit code.