5#if !defined(__EMSCRIPTEN__)
6#include <Poco/PipeStream.h>
7#include <Poco/Process.h>
8#include <Poco/UnicodeConverter.h>
23#include "common/config.h"
26#if defined(EVENGINE_WINDOWS) || defined(_WIN32)
27#include <restartmanager.h>
33using namespace std::filesystem;
41#if !defined(__EMSCRIPTEN__)
44#if defined(EVENGINE_WINDOWS) || defined(_WIN32)
45struct PackageLockOwners {
46 DWORD
status = ERROR_GEN_FAILURE;
47 vector<DWORD> processes;
49PackageLockOwners diagnosePackageLocks(
const path& candidate,
bool verbose =
true) {
52 struct RestartManager {
53 HMODULE library = LoadLibraryExW(L
"Rstrtmgr.dll",
nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32);
55 if (library) FreeLibrary(library);
59 cerr <<
"Package lock diagnostics unavailable: " << GetLastError() <<
'\n';
62 auto start =
reinterpret_cast<decltype(&RmStartSession)
>(GetProcAddress(api.library,
"RmStartSession"));
63 auto end =
reinterpret_cast<decltype(&RmEndSession)
>(GetProcAddress(api.library,
"RmEndSession"));
65 reinterpret_cast<decltype(&RmRegisterResources)
>(GetProcAddress(api.library,
"RmRegisterResources"));
66 auto list =
reinterpret_cast<decltype(&RmGetList)
>(GetProcAddress(api.library,
"RmGetList"));
68 cerr <<
"Package lock diagnostics API unavailable\n";
72 WCHAR
key[CCH_RM_SESSION_KEY + 1]{};
74 if (
status != ERROR_SUCCESS) {
75 cerr <<
"Package lock diagnostics start failed: " <<
status <<
'\n';
80 decltype(&RmEndSession) close;
83 if (
result != ERROR_SUCCESS) cerr <<
"Package lock diagnostics end failed: " <<
result <<
'\n';
86 vector<wstring> names;
88 for (recursive_directory_iterator it(candidate, scanError), last; !scanError && it != last;
89 it.increment(scanError)) {
90 if (it->is_regular_file(scanError)) names.push_back(absolute(it->path()).wstring());
92 if (scanError || names.empty()) {
93 cerr <<
"Package lock diagnostics enumeration failed or empty: " << scanError.message() <<
'\n';
96 vector<LPCWSTR> files;
97 for (
const auto&
name : names) files.push_back(
name.c_str());
99 UINT needed = 0,
count = 0;
102 vector<RM_PROCESS_INFO> processes;
103 if (
status == ERROR_MORE_DATA) {
104 processes.resize(needed);
108 if (verbose) cerr <<
"Package lock diagnostics: status=" <<
status <<
" process_count=" <<
count <<
'\n';
109 if (
status != ERROR_SUCCESS)
return {};
110 PackageLockOwners owners{ERROR_SUCCESS, {}};
111 for (UINT i = 0; i <
count; ++i) {
112 owners.processes.push_back(processes[i].Process.dwProcessId);
114 Poco::UnicodeConverter::toUTF8(wstring(processes[i].strAppName),
name);
116 cerr <<
"Package locker pid=" << processes[i].Process.dwProcessId <<
" application=" <<
name <<
'\n';
122PackageLockRelease waitForExternalPackageLocks(
const path& candidate, DWORD runtimePid, PackageLockOwners owners) {
123 const auto deadline = chrono::steady_clock::now() + chrono::seconds(5);
124 const auto publisherPid = GetCurrentProcessId();
125 if (owners.status != ERROR_SUCCESS)
return PackageLockRelease::Unavailable;
128 if (owners.processes.empty())
return PackageLockRelease::Released;
130 if (find(owners.processes.begin(), owners.processes.end(), publisherPid) != owners.processes.end() ||
131 find(owners.processes.begin(), owners.processes.end(), runtimePid) != owners.processes.end())
132 return PackageLockRelease::NotExternal;
133 if (chrono::steady_clock::now() >=
deadline)
return PackageLockRelease::TimedOut;
134 this_thread::sleep_for(chrono::milliseconds(100));
135 owners = diagnosePackageLocks(candidate,
false);
136 if (owners.status != ERROR_SUCCESS)
return PackageLockRelease::Unavailable;
137 if (owners.processes.empty())
return PackageLockRelease::Released;
146std::string targetRuntimeName(
const std::string& sdkRoot) {
147 std::ifstream in(std::filesystem::path(sdkRoot) /
"share" /
"eve" /
"TARGET_PLATFORM");
149 std::getline(in, plat);
150 while (!plat.empty() && (plat.back() ==
'\r' || plat.back() ==
'\n' || plat.back() ==
' '))
152 return plat ==
"win32" ?
"eve.exe" :
"eve";
155bool copyFileIf(
const path& src,
const path& dst) {
157 if (!
exists(src, ec))
return false;
158 create_directories(dst.parent_path(), ec);
159 copy_file(src, dst, copy_options::overwrite_existing, ec);
164bool copyFirst(
const std::string& dll,
const std::vector<path>&
candidates,
const path& dstDir) {
167 if (copyFileIf(
p, dstDir / dll))
return true;
172struct ScriptPackageManifest {
173 std::map<std::string, std::vector<std::string>>
graph;
176 std::string serialize()
const {
177 std::ostringstream
out;
178 out <<
"version=1\n";
179 for (
const auto& [module, dependencies] :
graph) {
181 for (
const std::string& dependency : dependencies)
out <<
'\t' << dependency;
188bool canonicalGameModule(std::string_view importer, std::string_view specifier, std::string&
result,
189 std::string&
error) {
190 script::ScriptModuleRequest
request{std::string(importer), std::string(specifier)};
192 if (
result.rfind(
"game:/", 0) != 0) {
193 error =
"package cannot statically resolve non-game script module: " +
result;
201class PackageScriptProvider final :
public script::IScriptModuleProvider {
205 std::string&
error)
override {
211 std::string&
error)
override {
212 if (
uri.rfind(
"game:/", 0) != 0) {
213 error =
"non-game package module";
216 const path file = root_ / std::string(
uri.substr(6));
219 error =
"Cannot read package module: " +
file.string();
223 source.utf8Source.assign(std::istreambuf_iterator<char>(
input), {});
225 sdk::detail::Sha256
hash;
235ScriptPackageManifest scanScriptPackage(
const path& gameDir) {
236 ScriptPackageManifest manifest;
238 for (recursive_directory_iterator it(gameDir, directory_options::none, ec),
end; it !=
end; it.increment(ec)) {
240 manifest.error =
"cannot enumerate scripts: " + ec.message();
243 if (!it->is_regular_file() || it->path().extension() !=
".nut")
continue;
244 std::ifstream
input(it->path(), std::ios::binary);
246 manifest.error =
"cannot read script during package scan: " + it->path().string();
249 const std::string
source(std::istreambuf_iterator<char>(
input), {});
250 const std::string
relative = std::filesystem::relative(it->path(), gameDir, ec).generic_string();
252 manifest.error =
"cannot canonicalize packaged script: " + it->path().string();
255 const std::string canonical =
"game:/" +
relative;
256 auto&
edges = manifest.graph[canonical];
257 for (
const std::string& specifier :
script::ScriptCompiler::analyze(
source, canonical).imports) {
258 std::string dependency;
259 if (!canonicalGameModule(canonical, specifier, dependency, manifest.error))
return manifest;
260 edges.push_back(std::move(dependency));
267 manifest.error =
"cannot enumerate scripts: " + ec.message();
271 for (
const auto& [module, dependencies] : manifest.
graph) {
272 for (
const std::string& dependency : dependencies) {
273 if (manifest.graph.find(dependency) == manifest.graph.end()) {
274 manifest.error =
"script module imported by " +
module + " is missing from package: " + dependency;
280 enum class Visit { Visiting,
Ready };
281 std::map<std::string, Visit> visits;
282 std::vector<std::string> stack;
283 const auto visit = [&](
const auto& self,
const std::string& module) ->
bool {
284 if (
const auto found = visits.find(module);
found != visits.end()) {
285 if (
found->second == Visit::Ready)
return true;
286 manifest.error =
"cyclic script import in package";
287 for (
const std::string& entry : stack) manifest.
error +=
" -> " + entry;
288 manifest.error +=
" -> " +
module;
291 visits[module] = Visit::Visiting;
292 stack.push_back(module);
293 for (
const std::string& dependency : manifest.
graph[module]) {
294 if (!self(self, dependency))
return false;
297 visits[module] = Visit::Ready;
300 for (
const auto& [module, _] : manifest.
graph) {
301 if (!visit(visit, module))
return manifest;
304 if (
compiler.scriptModules().registerProvider(std::make_shared<PackageScriptProvider>(gameDir), 100) == 0)
305 throw runtime_error(
"Cannot register package snapshot provider");
306 for (
const auto& [module, _] : manifest.
graph) {
307 ifstream
input(gameDir / module.substr(6), ios::binary);
308 if (!
input)
throw runtime_error(
"Cannot read package script: " + module);
309 const string source(std::istreambuf_iterator<char>(
input), {});
310 if (
input.bad())
throw runtime_error(
"Cannot read complete package script: " + module);
313 }
catch (
const std::exception&
error) {
314 manifest.error =
module + ": " + error.what();
322std::string resolveSdkRoot(
const std::string& sdkArg) {
323 if (!sdkArg.empty() && is_directory(sdkArg))
return sdkArg;
325 const char* env = getenv(
"EVENGINE_SDK");
326 if (env && is_directory(env))
return env;
330#if defined(EVENGINE_WINDOWS) || defined(_WIN32)
331 wchar_t buf[MAX_PATH + 1] = {0};
332 if (GetModuleFileNameW(
nullptr, buf, MAX_PATH) != 0) exe =
path(buf);
334 char buf[4096] = {0};
335 const ssize_t
n = readlink(
"/proc/self/exe", buf,
sizeof(buf) - 1);
336 if (
n > 0) exe =
path(std::string(buf,
static_cast<size_t>(
n)));
339 path root = exe.parent_path().parent_path();
340 if (
exists(
root /
"share" /
"eve" /
"TARGET_PLATFORM"))
return root.string();
350 void setup(CLI::App& app, std::shared_ptr<CLI::Formatter>)
override {
351 auto subcmd = app.add_subcommand(
"package",
"Package a game into a runnable game folder.");
352 subcmd->allow_extras();
353 subcmd->add_option(
"-o,--output",
outputPath,
"output folder path");
354 subcmd->add_option(
"--sdk",
sdkPath,
"target SDK root (default: auto-detect / $EVENGINE_SDK)");
358 auto subcmd = app.get_subcommand(
"package");
359 if (subcmd->parsed()) {
370#if defined(__EMSCRIPTEN__)
372 cerr <<
"eve package requires a native host that can run the target SDK runtime; "
373 "desktop packaging is unavailable in the browser.\n";
379 if (!is_directory(gamePath, ec)) {
380 cerr << rang::fg::red <<
"Not a directory: " << rang::fg::reset << gamePath << endl;
384 std::string sdkRoot = resolveSdkRoot(sdk);
385 if (sdkRoot.empty()) {
386 cerr << rang::fg::red
387 <<
"Cannot locate the target SDK. Pass --sdk <dir>, set $EVENGINE_SDK, "
388 "or run from <sdk>/bin/<runtime>."
389 << rang::fg::reset << endl;
393 gamePath = canonical(gamePath).string();
394 if (!is_regular_file(
path(gamePath) /
"main.nut")) {
395 cerr <<
"Package requires main.nut\n";
399 std::string gameName = gamePath;
400 while (!gameName.empty() && (gameName.back() ==
'/' || gameName.back() ==
'\\'))
402 if (gameName.find_first_of(
"/\\") != string::npos)
403 gameName = std::filesystem::path(gameName).filename().string();
404 if (gameName.empty()) gameName =
"game";
407 const auto relativeOutput = destination.lexically_relative(gamePath);
408 const auto relativeGame =
path(gamePath).lexically_relative(destination);
409 if (destination ==
path(gamePath) || (!relativeOutput.empty() && *relativeOutput.begin() !=
"..") ||
410 (!relativeGame.empty() && *relativeGame.begin() !=
"..")) {
411 cerr <<
"Package output and source must not contain one another\n";
414 create_directories(destination.parent_path());
415 const path lock = destination.string() +
".package-lock";
416 if (!create_directory(lock)) {
417 cerr <<
"Package destination is locked: " << lock <<
'\n';
427 path outDir = lock /
"candidate";
428 create_directory(outDir);
430 copy(gamePath,
snapshot, copy_options::recursive);
431 const ScriptPackageManifest scripts = scanScriptPackage(
snapshot);
432 if (!scripts.error.empty()) {
433 cerr << rang::fg::red <<
"Script dependency scan failed: " << scripts.error << rang::fg::reset << endl;
438 path sdkBin =
path(sdkRoot) /
"bin";
439 path sdkLib =
path(sdkRoot) /
"lib";
440 path sdkPlat =
path(sdkRoot) /
"platform";
442 const std::string runtimeName = targetRuntimeName(sdkRoot);
445 path runtimeSrc = sdkBin / runtimeName;
446 path runtimeDst = outDir / runtimeName;
447 if (!copyFileIf(runtimeSrc, runtimeDst)) {
448 cerr << rang::fg::red <<
"SDK missing " << runtimeSrc.string() << rang::fg::reset << endl;
456 if (runtimeName ==
"eve.exe") {
457 std::vector<path> crtCandidates;
458 if (
exists(sdkBin)) crtCandidates.push_back(sdkBin);
459 if (
exists(sdkLib)) crtCandidates.push_back(sdkLib);
460#if defined(EVENGINE_WINDOWS) || defined(_WIN32)
462 for (
const auto& msroot : {
"C:/Program Files/Microsoft Visual Studio"}) {
464 if (
exists(base /
"18")) base = base /
"18";
465 for (
const auto& entry : directory_iterator(base, ec)) {
466 if (!entry.is_directory())
continue;
467 path redist = entry.path() /
"Community" /
"VC" /
"Redist" /
"MSVC";
468 if (!
exists(redist))
continue;
469 for (
const auto& ver : directory_iterator(redist, ec)) {
470 for (
const auto& crtDir : {
"x64",
"debug_nonredist/x64"}) {
471 path crt = ver.path() / crtDir;
472 if (!
exists(crt))
continue;
473 for (
const auto& sub : directory_iterator(crt, ec)) {
474 if (!sub.is_directory())
continue;
475 const std::string
n = sub.path().filename().string();
476 if (
n.find(
"Microsoft.VC") == 0 &&
477 (
n.find(
".CRT") != string::npos ||
478 n.find(
"DebugCRT") != string::npos))
479 crtCandidates.push_back(sub.path());
486 crtCandidates.push_back(
path(
"C:/Windows/System32"));
491 for (
const auto& dll : {
"vulkan-1.dll",
"msvcp140.dll",
"msvcp140_1.dll",
492 "msvcp140_2.dll",
"vcruntime140.dll",
493 "vcruntime140_1.dll",
"concrt140.dll",
494 "msvcp140d.dll",
"vcruntime140d.dll",
495 "vcruntime140_1d.dll",
"ucrtbased.dll",
497 if (!copyFirst(dll, crtCandidates, outDir))
498 cerr << rang::fg::yellow
499 <<
"note: runtime DLL not found (may be system-installed): "
500 << dll << rang::fg::reset << endl;
504#ifdef EVENGINE_MACOSX
512 std::ifstream platIn(std::filesystem::path(sdkRoot) /
"share" /
"eve" /
"TARGET_PLATFORM");
514 std::getline(platIn, plat);
515 while (!plat.empty() && (plat.back() ==
'\r' || plat.back() ==
'\n' || plat.back() ==
' '))
519 if (plat ==
"macosx")
520 copy(sdkLib, outDir /
"lib",
521 copy_options::recursive | copy_options::overwrite_existing, ec);
522 if (ec)
throw filesystem_error(
"copy SDK libraries", sdkLib, ec);
528 for (
const auto& entry : directory_iterator(sdkPlat, ec)) {
529 copy(entry.path(), outDir / entry.path().filename(),
530 copy_options::recursive | copy_options::overwrite_existing, ec);
531 if (ec)
throw filesystem_error(
"copy platform template", entry.path(), ec);
536 path archive = outDir /
"game.eve";
538 cerr << rang::fg::red <<
"Failed to package game archive." << rang::fg::reset << endl;
542 const auto hashFile = [](
const path&
file) {
544 if (!
input)
throw runtime_error(
"Cannot hash " +
file.string());
549 if (!
input.eof())
throw runtime_error(
"Cannot read " +
file.string());
550 return hash.finish();
552 const string archiveHash = hashFile(archive);
553 const string runtimeHash = hashFile(runtimeDst);
556 Poco::Process::Env childEnvironment;
557#if defined(EVENGINE_WINDOWS) || defined(_WIN32)
560 struct EnvironmentBlock {
561 LPWCH
value = GetEnvironmentStringsW();
562 ~EnvironmentBlock() {
566 if (!environment.value)
throw runtime_error(
"Cannot read child process environment");
567 for (
const wchar_t* entry = environment.value; *entry; entry += std::wcslen(entry) + 1) {
569 Poco::UnicodeConverter::toUTF8(std::wstring(entry), utf8);
570 const auto separator = utf8.find(
'=', 1);
571 if (separator != string::npos) childEnvironment.emplace(utf8.substr(0, separator), utf8.substr(separator + 1));
574 childEnvironment[
"EVE_PACKAGE_CHECK"] =
"1";
576 auto process = Poco::Process::launch(absolute(runtimeDst).
string(), {
"run"}, absolute(outDir).string(),
nullptr,
577 &pipe, &pipe, childEnvironment);
579 struct ChildCleanup {
580 Poco::ProcessHandle child;
584 if (child.tryWait() == -1) {
585 Poco::Process::kill(child.id());
590 if (reader.joinable()) reader.join();
592 } child{process, {}};
593 child.reader = std::thread([&] {
594 Poco::PipeInputStream
input(pipe);
598 if (log.size() < 8 * 1024 * 1024) log.append(
buffer,
static_cast<size_t>(
input.gcount()));
602 const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(60);
603 while ((exit = process.tryWait()) == -1 && std::chrono::steady_clock::now() <
deadline)
604 std::this_thread::sleep_for(std::chrono::milliseconds(20));
606 Poco::Process::kill(process.id());
607 exit = process.wait();
609#if defined(EVENGINE_WINDOWS) || defined(_WIN32)
612 exit = process.wait();
615 if (exit != 0 || log.find(
"[package-check] passed: 30 frames") == std::string::npos) {
616 cerr <<
"Package runtime acceptance failed (exit " << exit <<
")\n" << log;
619 if (hashFile(archive) != archiveHash || hashFile(runtimeDst) != runtimeHash)
620 throw runtime_error(
"Candidate changed during runtime acceptance");
622 const string identityInput =
"eve.package-build/1\n" + archiveHash +
"\n" + runtimeHash;
623 buildIdentity.
update(identityInput.data(), identityInput.size());
624 ofstream
record(outDir /
"build-identity.manifest", ios::binary);
625 record <<
"schema=eve.package-build\nversion=1\n"
626 <<
"build_id=" << buildIdentity.
finish() <<
"\n"
627 <<
"archive_sha256=" << archiveHash <<
"\n"
628 <<
"runtime_sha256=" << runtimeHash <<
"\n"
629 <<
"built_at_unix_ms="
630 << chrono::duration_cast<chrono::milliseconds>(chrono::system_clock::now().time_since_epoch()).count()
632 <<
"compiled_scripts=" << scripts.graph.size() <<
"\n"
633 <<
"acceptance=passed\nframes=30\n";
635 if (!
record)
throw runtime_error(
"Cannot write build identity");
636 ofstream acceptance(outDir /
"acceptance.log", ios::binary);
639 if (!acceptance)
throw runtime_error(
"Cannot write acceptance log");
642 const bool hadPrevious =
exists(destination);
643 if (hadPrevious) rename(destination,
previous);
644 rename(outDir, destination, ec);
646 cerr <<
"Package publish failed: code=" << ec.value() <<
" category=" << ec.category().name()
647 <<
" candidate=" << outDir <<
" destination=" << destination <<
'\n';
648#if defined(EVENGINE_WINDOWS) || defined(_WIN32)
649 cerr <<
"Package publisher pid=" << GetCurrentProcessId() <<
" accepted runtime pid=" << process.id() <<
'\n';
651 auto owners = diagnosePackageLocks(outDir);
652 if (ec.category() == system_category() &&
653 (ec.value() == ERROR_ACCESS_DENIED || ec.value() == ERROR_SHARING_VIOLATION) &&
654 waitForExternalPackageLocks(outDir, process.id(), std::move(owners)) == PackageLockRelease::Released) {
657 if (hashFile(archive) != archiveHash || hashFile(runtimeDst) != runtimeHash)
658 throw runtime_error(
"Candidate changed while waiting for external package locks");
659 cerr <<
"No package lockers reported; retrying verified candidate\n";
660 rename(outDir, destination, ec);
662 }
catch (
const std::exception& diagnosticError) {
663 cerr <<
"Package lock diagnostics failed: " << diagnosticError.what() <<
'\n';
669 error_code restoreError;
670 rename(
previous, destination, restoreError);
673 cleanup.directory.clear();
674 cerr <<
"Previous package retained at " <<
previous <<
'\n';
677 throw filesystem_error(
"publish package", destination, ec);
679 cout <<
"Built verified game package -> " << destination.string() <<
'\n';
680 cout <<
" run: " << (destination / runtimeName).
string() <<
'\n';
682}
catch (
const std::exception&
error) {
683 cerr <<
"Package failed: " <<
error.what() <<
'\n';
std::filesystem::path directory
ScriptComponentRecord record
const GltfImportRequest & request
wgpu::PopErrorScopeStatus status
std::chrono::steady_clock::time_point deadline
std::shared_ptr< const OceanSprayFrame > previous
std::vector< std::weak_ptr< DeviceBytes > > resources
onnx_detail::CompilerQueue compiler
std::unique_ptr< gpgpu::GpuBuffer > buffer
std::map< std::string, std::vector< std::string > > graph
std::map< std::array< int, 4 >, std::vector< const Subject * > > candidates
std::optional< InteractionSession > session
命令行模块(eve.cmd):run / build / package / test / zip / dev-server 等子命令入口。
static std::string get_remaining(CLI::App *sub, std::string default_path=".")
子命令剩余位置参数。
int Package(std::string path, std::string output, std::string sdk)
把游戏打包为单个可执行文件 / APK。
std::string finish()
Finish.
void update(const char *data, std::size_t size)
Updates .
static bool canonicalize(const ScriptModuleRequest &request, std::string &output, std::string &error)
Normalizes a logical module URI and rejects root traversal.
bool createGameArchive(const std::filesystem::path &gameDir, const std::filesystem::path &outArchive, const std::vector< std::pair< std::string, std::string > > &generatedEntries={})
Creates game archive.
ScriptModuleStatus
Result of asking a provider to resolve or load a script module.
WidgetDesc list(std::string listId, const std::vector< std::string > &items, const std::function< WidgetDesc(const std::string &, int)> &itemFn)
Expand a string list into a Group of item widgets. itemFn(label, index) builds each row; keys default...
One eve <subcommand> handler: CLI setup + argument parsing.
int parse(CLI::App &app, Cmdline &cmd) override
Parses arguments and runs the command; returns the exit code.
void setup(CLI::App &app, std::shared_ptr< CLI::Formatter >) override
Registers options on the CLI11 sub-app.