metaforce/hecl/lib/Blender/Connection.cpp

1753 lines
56 KiB
C++
Raw Permalink Normal View History

#include <algorithm>
2017-12-29 07:56:31 +00:00
#include <cerrno>
#include <cfloat>
#include <chrono>
#include <cinttypes>
#include <csignal>
2017-12-29 07:56:31 +00:00
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <mutex>
2015-05-24 04:51:16 +00:00
#include <string>
#include <system_error>
2016-08-02 22:12:49 +00:00
#include <thread>
#include <tuple>
2015-05-24 04:51:16 +00:00
2017-12-29 07:56:31 +00:00
#include "hecl/Blender/Connection.hpp"
#include "hecl/Blender/Token.hpp"
#include "hecl/Database.hpp"
#include "hecl/hecl.hpp"
#include "hecl/SteamFinder.hpp"
2019-05-08 03:47:34 +00:00
#include "MeshOptimizer.hpp"
2015-05-24 04:51:16 +00:00
#include <athena/MemoryWriter.hpp>
#include <logvisor/logvisor.hpp>
2015-08-31 03:36:24 +00:00
#if _WIN32
#include <io.h>
#include <fcntl.h>
2019-10-01 07:23:35 +00:00
#else
#include <sys/wait.h>
2015-08-31 03:36:24 +00:00
#endif
2017-12-30 01:07:15 +00:00
#undef min
#undef max
2018-12-08 05:18:42 +00:00
namespace std {
template <>
struct hash<std::pair<uint32_t, uint32_t>> {
std::size_t operator()(const std::pair<uint32_t, uint32_t>& val) const noexcept {
2018-12-08 05:18:42 +00:00
/* this will potentially truncate the second value if 32-bit size_t,
* however, its application here is intended to operate in 16-bit indices */
return val.first | (val.second << 16);
}
2015-10-22 02:01:08 +00:00
};
2018-12-08 05:18:42 +00:00
} // namespace std
2015-10-22 02:01:08 +00:00
2017-11-13 06:13:53 +00:00
using namespace std::literals;
2018-12-08 05:18:42 +00:00
namespace hecl::blender {
2015-07-28 02:25:33 +00:00
static const uint32_t MinBlenderMajorSearch = 2;
static const uint32_t MaxBlenderMajorSearch = 2;
static const uint32_t MinBlenderMinorSearch = 83;
static const uint32_t MaxBlenderMinorSearch = 92;
2017-12-29 07:56:31 +00:00
logvisor::Module BlenderLog("hecl::blender::Connection");
Token SharedBlenderToken;
2015-07-22 19:14:50 +00:00
2015-05-24 04:51:16 +00:00
#ifdef __APPLE__
#define DEFAULT_BLENDER_BIN "/Applications/Blender.app/Contents/MacOS/blender"
#else
2019-10-01 07:23:35 +00:00
#define DEFAULT_BLENDER_BIN "blender"
2015-05-24 04:51:16 +00:00
#endif
2015-08-13 07:30:23 +00:00
extern "C" uint8_t HECL_BLENDERSHELL[];
extern "C" size_t HECL_BLENDERSHELL_SZ;
2015-05-24 04:51:16 +00:00
2015-08-31 03:36:24 +00:00
extern "C" uint8_t HECL_ADDON[];
extern "C" size_t HECL_ADDON_SZ;
2016-04-03 03:31:50 +00:00
2015-09-06 20:08:23 +00:00
extern "C" uint8_t HECL_STARTUP[];
extern "C" size_t HECL_STARTUP_SZ;
2015-08-31 03:36:24 +00:00
2018-12-08 05:18:42 +00:00
static void InstallBlendershell(const SystemChar* path) {
auto fp = hecl::FopenUnique(path, _SYS_STR("w"));
if (fp == nullptr) {
2020-04-11 22:48:11 +00:00
BlenderLog.report(logvisor::Fatal, FMT_STRING(_SYS_STR("unable to open {} for writing")), path);
}
std::fwrite(HECL_BLENDERSHELL, 1, HECL_BLENDERSHELL_SZ, fp.get());
2018-12-08 05:18:42 +00:00
}
static void InstallAddon(const SystemChar* path) {
auto fp = hecl::FopenUnique(path, _SYS_STR("wb"));
if (fp == nullptr) {
2020-04-11 22:48:11 +00:00
BlenderLog.report(logvisor::Fatal, FMT_STRING(_SYS_STR("Unable to install blender addon at '{}'")), path);
}
std::fwrite(HECL_ADDON, 1, HECL_ADDON_SZ, fp.get());
2018-12-08 05:18:42 +00:00
}
static int Read(int fd, void* buf, std::size_t size) {
2018-12-08 05:18:42 +00:00
int intrCount = 0;
do {
auto ret = read(fd, buf, size);
if (ret < 0) {
if (errno == EINTR)
++intrCount;
else
return -1;
} else
return ret;
} while (intrCount < 1000);
return -1;
}
static int Write(int fd, const void* buf, std::size_t size) {
2018-12-08 05:18:42 +00:00
int intrCount = 0;
do {
auto ret = write(fd, buf, size);
if (ret < 0) {
if (errno == EINTR)
++intrCount;
else
return -1;
} else
return ret;
} while (intrCount < 1000);
return -1;
}
static std::size_t BoundedStrLen(const char* buf, std::size_t maxLen) {
std::size_t ret;
for (ret = 0; ret < maxLen; ++ret)
if (buf[ret] == '\0')
break;
return ret;
}
2018-12-08 05:18:42 +00:00
uint32_t Connection::_readStr(char* buf, uint32_t bufSz) {
uint32_t readLen;
2019-08-21 22:43:51 +00:00
int ret = Read(m_readpipe[0], &readLen, sizeof(readLen));
2018-12-08 05:18:42 +00:00
if (ret < 4) {
2020-04-11 22:48:11 +00:00
BlenderLog.report(logvisor::Error, FMT_STRING("Pipe error {} {}"), ret, strerror(errno));
2018-12-08 05:18:42 +00:00
_blenderDied();
return 0;
}
2018-12-08 05:18:42 +00:00
if (readLen >= bufSz) {
2020-04-11 22:48:11 +00:00
BlenderLog.report(logvisor::Fatal, FMT_STRING("Pipe buffer overrun [{}/{}]"), readLen, bufSz);
2018-12-08 05:18:42 +00:00
*buf = '\0';
return 0;
}
2018-12-08 05:18:42 +00:00
ret = Read(m_readpipe[0], buf, readLen);
if (ret < 0) {
2020-04-11 22:48:11 +00:00
BlenderLog.report(logvisor::Fatal, FMT_STRING("{}"), strerror(errno));
2018-12-08 05:18:42 +00:00
return 0;
2019-08-21 22:43:51 +00:00
}
constexpr std::string_view exception_str{"EXCEPTION"};
const std::size_t readStrLen = BoundedStrLen(buf, readLen);
if (readStrLen >= exception_str.size()) {
if (exception_str.compare(0, exception_str.size(), std::string_view(buf, readStrLen)) == 0) {
2018-12-08 05:18:42 +00:00
_blenderDied();
return 0;
2017-01-19 09:01:54 +00:00
}
2018-12-08 05:18:42 +00:00
}
2018-12-08 05:18:42 +00:00
*(buf + readLen) = '\0';
return readLen;
2015-05-24 04:51:16 +00:00
}
2018-12-08 05:18:42 +00:00
uint32_t Connection::_writeStr(const char* buf, uint32_t len, int wpipe) {
2019-08-21 22:43:51 +00:00
const auto error = [this] {
_blenderDied();
return 0U;
};
const int nlerr = Write(wpipe, &len, 4);
if (nlerr < 4) {
return error();
}
const int ret = Write(wpipe, buf, len);
if (ret < 0) {
return error();
}
return static_cast<uint32_t>(ret);
2015-05-24 04:51:16 +00:00
}
std::size_t Connection::_readBuf(void* buf, std::size_t len) {
2019-08-21 22:43:51 +00:00
const auto error = [this] {
_blenderDied();
return 0U;
};
auto* cBuf = static_cast<uint8_t*>(buf);
std::size_t readLen = 0;
2019-08-21 22:43:51 +00:00
2018-12-08 05:18:42 +00:00
do {
2019-08-21 22:43:51 +00:00
const int ret = Read(m_readpipe[0], cBuf, len);
if (ret < 0) {
return error();
}
constexpr std::string_view exception_str{"EXCEPTION"};
const std::size_t readStrLen = BoundedStrLen(static_cast<char*>(buf), len);
if (readStrLen >= exception_str.size()) {
if (exception_str.compare(0, exception_str.size(), std::string_view(static_cast<char*>(buf), readStrLen)) == 0) {
2018-12-08 05:18:42 +00:00
_blenderDied();
2019-08-21 22:43:51 +00:00
}
}
2018-12-08 05:18:42 +00:00
readLen += ret;
cBuf += ret;
len -= ret;
2019-08-21 22:43:51 +00:00
} while (len != 0);
2018-12-08 05:18:42 +00:00
return readLen;
2015-05-24 04:51:16 +00:00
}
std::size_t Connection::_writeBuf(const void* buf, std::size_t len) {
2019-08-21 22:43:51 +00:00
const auto error = [this] {
_blenderDied();
return 0U;
};
const auto* cBuf = static_cast<const uint8_t*>(buf);
std::size_t writeLen = 0;
2019-08-21 22:43:51 +00:00
2018-12-08 05:18:42 +00:00
do {
2019-08-21 22:43:51 +00:00
const int ret = Write(m_writepipe[1], cBuf, len);
if (ret < 0) {
return error();
}
2018-12-08 05:18:42 +00:00
writeLen += ret;
cBuf += ret;
len -= ret;
2019-08-21 22:43:51 +00:00
} while (len != 0);
2018-12-08 05:18:42 +00:00
return writeLen;
2015-05-24 04:51:16 +00:00
}
2019-10-01 07:23:35 +00:00
ProjectPath Connection::_readPath() {
std::string path = _readStdString();
if (!path.empty()) {
SystemStringConv pathAbs(path);
SystemString meshPathRel =
getBlendPath().getProject().getProjectRootPath().getProjectRelativeFromAbsolute(pathAbs.sys_str());
return ProjectPath(getBlendPath().getProject().getProjectWorkingPath(), meshPathRel);
}
return {};
}
2018-12-08 05:18:42 +00:00
void Connection::_closePipe() {
close(m_readpipe[0]);
close(m_writepipe[1]);
#ifdef _WIN32
2018-12-08 05:18:42 +00:00
CloseHandle(m_pinfo.hProcess);
CloseHandle(m_pinfo.hThread);
m_consoleThreadRunning = false;
if (m_consoleThread.joinable())
m_consoleThread.join();
#endif
2015-05-24 04:51:16 +00:00
}
2018-12-08 05:18:42 +00:00
void Connection::_blenderDied() {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
auto errFp = hecl::FopenUnique(m_errPath.c_str(), _SYS_STR("r"));
if (errFp != nullptr) {
std::fseek(errFp.get(), 0, SEEK_END);
const int64_t len = hecl::FTell(errFp.get());
if (len != 0) {
std::fseek(errFp.get(), 0, SEEK_SET);
const auto buf = std::make_unique<char[]>(len + 1);
std::fread(buf.get(), 1, len, errFp.get());
2020-04-11 22:48:11 +00:00
BlenderLog.report(logvisor::Fatal, FMT_STRING("\n{:.{}s}"), buf.get(), len);
2016-08-02 22:12:49 +00:00
}
2018-12-08 05:18:42 +00:00
}
2020-04-11 22:48:11 +00:00
BlenderLog.report(logvisor::Fatal, FMT_STRING("Blender Exception"));
2016-08-02 22:12:49 +00:00
}
static std::atomic_bool BlenderFirstInit(false);
#if _WIN32
2018-12-08 05:18:42 +00:00
static bool RegFileExists(const hecl::SystemChar* path) {
if (!path)
return false;
hecl::Sstat theStat;
return !hecl::Stat(path, &theStat) && S_ISREG(theStat.st_mode);
}
#endif
2018-12-08 05:18:42 +00:00
Connection::Connection(int verbosityLevel) {
2017-12-06 03:22:31 +00:00
#if !WINDOWS_STORE
2018-12-08 05:18:42 +00:00
if (hecl::VerbosityLevel >= 1)
2020-04-11 22:48:11 +00:00
BlenderLog.report(logvisor::Info, FMT_STRING("Establishing BlenderConnection..."));
2016-04-03 03:31:50 +00:00
2018-12-08 05:18:42 +00:00
/* Put hecl_blendershell.py in temp dir */
const SystemChar* TMPDIR = GetTmpDir();
2019-06-13 01:29:52 +00:00
#ifndef _WIN32
2018-12-08 05:18:42 +00:00
signal(SIGPIPE, SIG_IGN);
#endif
2018-12-08 05:18:42 +00:00
hecl::SystemString blenderShellPath(TMPDIR);
blenderShellPath += _SYS_STR("/hecl_blendershell.py");
2018-12-08 05:18:42 +00:00
hecl::SystemString blenderAddonPath(TMPDIR);
blenderAddonPath += _SYS_STR("/hecl_blenderaddon.zip");
2018-12-08 05:18:42 +00:00
bool FalseCmp = false;
if (BlenderFirstInit.compare_exchange_strong(FalseCmp, true)) {
InstallBlendershell(blenderShellPath.c_str());
InstallAddon(blenderAddonPath.c_str());
}
2015-08-31 03:36:24 +00:00
2018-12-08 05:18:42 +00:00
int installAttempt = 0;
while (true) {
/* Construct communication pipes */
2015-07-22 19:14:50 +00:00
#if _WIN32
_pipe(m_readpipe.data(), 2048, _O_BINARY);
_pipe(m_writepipe.data(), 2048, _O_BINARY);
2018-12-08 05:18:42 +00:00
HANDLE writehandle = HANDLE(_get_osfhandle(m_writepipe[0]));
SetHandleInformation(writehandle, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT);
HANDLE readhandle = HANDLE(_get_osfhandle(m_readpipe[1]));
SetHandleInformation(readhandle, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT);
SECURITY_ATTRIBUTES sattrs = {sizeof(SECURITY_ATTRIBUTES), nullptr, TRUE};
2018-12-08 05:18:42 +00:00
HANDLE consoleOutReadTmp, consoleOutWrite, consoleErrWrite, consoleOutRead;
2019-05-10 04:07:48 +00:00
if (!CreatePipe(&consoleOutReadTmp, &consoleOutWrite, &sattrs, 1024))
2020-04-11 22:48:11 +00:00
BlenderLog.report(logvisor::Fatal, FMT_STRING("Error with CreatePipe"));
2018-12-08 05:18:42 +00:00
if (!DuplicateHandle(GetCurrentProcess(), consoleOutWrite, GetCurrentProcess(), &consoleErrWrite, 0, TRUE,
DUPLICATE_SAME_ACCESS))
2020-04-11 22:48:11 +00:00
BlenderLog.report(logvisor::Fatal, FMT_STRING("Error with DuplicateHandle"));
2018-12-08 05:18:42 +00:00
if (!DuplicateHandle(GetCurrentProcess(), consoleOutReadTmp, GetCurrentProcess(),
&consoleOutRead, // Address of new handle.
0, FALSE, // Make it uninheritable.
DUPLICATE_SAME_ACCESS))
2020-04-11 22:48:11 +00:00
BlenderLog.report(logvisor::Fatal, FMT_STRING("Error with DupliateHandle"));
2018-12-08 05:18:42 +00:00
if (!CloseHandle(consoleOutReadTmp))
2020-04-11 22:48:11 +00:00
BlenderLog.report(logvisor::Fatal, FMT_STRING("Error with CloseHandle"));
2015-07-22 19:14:50 +00:00
#else
2019-08-23 23:58:15 +00:00
pipe(m_readpipe.data());
pipe(m_writepipe.data());
2015-07-22 19:14:50 +00:00
#endif
2015-05-24 04:51:16 +00:00
2018-12-08 05:18:42 +00:00
/* User-specified blender path */
2015-07-22 19:14:50 +00:00
#if _WIN32
wchar_t BLENDER_BIN_BUF[2048];
2019-07-28 01:19:48 +00:00
std::wstring blenderBinBuf;
2018-12-08 05:18:42 +00:00
const wchar_t* blenderBin = _wgetenv(L"BLENDER_BIN");
2015-07-22 19:14:50 +00:00
#else
2018-12-08 05:18:42 +00:00
const char* blenderBin = getenv("BLENDER_BIN");
2015-07-22 19:14:50 +00:00
#endif
2015-05-24 04:51:16 +00:00
2018-12-08 05:18:42 +00:00
/* Steam blender */
hecl::SystemString steamBlender;
2018-12-08 05:18:42 +00:00
/* Child process of blender */
2015-07-22 19:14:50 +00:00
#if _WIN32
2018-12-08 05:18:42 +00:00
if (!blenderBin || !RegFileExists(blenderBin)) {
/* Environment not set; try steam */
steamBlender = hecl::FindCommonSteamApp(_SYS_STR("Blender"));
if (steamBlender.size()) {
steamBlender += _SYS_STR("\\blender.exe");
blenderBin = steamBlender.c_str();
}
if (!RegFileExists(blenderBin)) {
/* No steam; try default */
wchar_t progFiles[256];
if (GetEnvironmentVariableW(L"ProgramFiles", progFiles, 256)) {
2021-03-10 19:59:10 +00:00
for (size_t major = MaxBlenderMajorSearch; major >= MinBlenderMajorSearch; --major) {
bool found = false;
2021-03-10 19:59:10 +00:00
for (size_t minor = MaxBlenderMinorSearch; minor >= MinBlenderMinorSearch; --minor) {
_snwprintf(BLENDER_BIN_BUF, 2048, L"%s\\Blender Foundation\\Blender %i.%i\\blender.exe", progFiles, major,
minor);
if (RegFileExists(BLENDER_BIN_BUF)) {
blenderBin = BLENDER_BIN_BUF;
found = true;
break;
}
}
if (found) {
break;
}
}
}
2018-12-08 05:18:42 +00:00
}
}
2015-07-22 19:14:50 +00:00
2020-04-11 22:48:11 +00:00
std::wstring cmdLine = fmt::format(FMT_STRING(L" --background -P \"{}\" -- {} {} {} \"{}\""), blenderShellPath,
uintptr_t(writehandle), uintptr_t(readhandle), verbosityLevel, blenderAddonPath);
2018-12-08 05:18:42 +00:00
STARTUPINFO sinfo = {sizeof(STARTUPINFO)};
HANDLE nulHandle = CreateFileW(L"nul", GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, &sattrs, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL, nullptr);
2018-12-08 05:18:42 +00:00
sinfo.dwFlags = STARTF_USESTDHANDLES;
sinfo.hStdInput = nulHandle;
if (verbosityLevel == 0) {
sinfo.hStdError = nulHandle;
sinfo.hStdOutput = nulHandle;
} else {
sinfo.hStdError = consoleErrWrite;
sinfo.hStdOutput = consoleOutWrite;
}
if (!CreateProcessW(blenderBin, cmdLine.data(), nullptr, nullptr, TRUE, NORMAL_PRIORITY_CLASS, nullptr, nullptr,
&sinfo, &m_pinfo)) {
2018-12-08 05:18:42 +00:00
LPWSTR messageBuffer = nullptr;
FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
nullptr, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPWSTR)&messageBuffer, 0,
nullptr);
BlenderLog.report(logvisor::Fatal, FMT_STRING(L"unable to launch blender from {}: {}"), blenderBin,
messageBuffer);
2018-12-08 05:18:42 +00:00
}
close(m_writepipe[0]);
close(m_readpipe[1]);
CloseHandle(nulHandle);
CloseHandle(consoleErrWrite);
CloseHandle(consoleOutWrite);
m_consoleThreadRunning = true;
m_consoleThread = std::thread([=]() {
2019-05-10 04:07:48 +00:00
CHAR lpBuffer[1024];
2018-12-08 05:18:42 +00:00
DWORD nBytesRead;
DWORD nCharsWritten;
while (m_consoleThreadRunning) {
if (!ReadFile(consoleOutRead, lpBuffer, sizeof(lpBuffer), &nBytesRead, nullptr) || !nBytesRead) {
2018-12-08 05:18:42 +00:00
DWORD err = GetLastError();
if (err == ERROR_BROKEN_PIPE)
break; // pipe done - normal exit path.
else
BlenderLog.report(logvisor::Error, FMT_STRING("Error with ReadFile: {:08X}"),
err); // Something bad happened.
2015-08-31 03:36:24 +00:00
}
2015-07-22 19:14:50 +00:00
2018-12-08 05:18:42 +00:00
// Display the character read on the screen.
auto lk = logvisor::LockLog();
if (!WriteConsoleA(GetStdHandle(STD_OUTPUT_HANDLE), lpBuffer, nBytesRead, &nCharsWritten, nullptr)) {
2020-04-11 22:48:11 +00:00
// BlenderLog.report(logvisor::Error, FMT_STRING("Error with WriteConsole: %08X"), GetLastError());
2015-08-31 03:36:24 +00:00
}
2018-12-08 05:18:42 +00:00
}
2015-07-22 19:14:50 +00:00
2018-12-08 05:18:42 +00:00
CloseHandle(consoleOutRead);
});
2015-07-22 19:14:50 +00:00
#else
2018-12-08 05:18:42 +00:00
pid_t pid = fork();
if (!pid) {
/* Close all file descriptors besides those this blender instance uses */
int upper_fd = std::max(m_writepipe[0], m_readpipe[1]);
for (int i = 3; i < upper_fd; ++i) {
if (i != m_writepipe[0] && i != m_readpipe[1])
close(i);
}
closefrom(upper_fd + 1);
2018-12-08 05:18:42 +00:00
if (verbosityLevel == 0) {
int devNull = open("/dev/null", O_WRONLY);
dup2(devNull, STDOUT_FILENO);
dup2(devNull, STDERR_FILENO);
close(devNull);
}
2019-07-20 04:22:58 +00:00
std::string errbuf;
2020-04-11 22:48:11 +00:00
std::string readfds = fmt::format(FMT_STRING("{}"), m_writepipe[0]);
std::string writefds = fmt::format(FMT_STRING("{}"), m_readpipe[1]);
std::string vLevel = fmt::format(FMT_STRING("{}"), verbosityLevel);
2018-12-08 05:18:42 +00:00
/* Try user-specified blender first */
if (blenderBin) {
execlp(blenderBin, blenderBin, "--background", "-P", blenderShellPath.c_str(), "--", readfds.c_str(),
writefds.c_str(), vLevel.c_str(), blenderAddonPath.c_str(), nullptr);
2018-12-08 05:18:42 +00:00
if (errno != ENOENT) {
2020-04-11 22:48:11 +00:00
errbuf = fmt::format(FMT_STRING("NOLAUNCH {}"), strerror(errno));
2019-07-20 04:22:58 +00:00
_writeStr(errbuf.c_str(), errbuf.size(), m_readpipe[1]);
2018-12-08 05:18:42 +00:00
exit(1);
}
}
/* Try steam */
steamBlender = hecl::FindCommonSteamApp(_SYS_STR("Blender"));
if (steamBlender.size()) {
2017-07-23 23:44:17 +00:00
#ifdef __APPLE__
2018-12-08 05:18:42 +00:00
steamBlender += "/blender.app/Contents/MacOS/blender";
2017-07-23 23:44:17 +00:00
#else
2018-12-08 05:18:42 +00:00
steamBlender += "/blender";
2017-07-23 23:44:17 +00:00
#endif
2018-12-08 05:18:42 +00:00
blenderBin = steamBlender.c_str();
execlp(blenderBin, blenderBin, "--background", "-P", blenderShellPath.c_str(), "--", readfds.c_str(),
writefds.c_str(), vLevel.c_str(), blenderAddonPath.c_str(), nullptr);
2018-12-08 05:18:42 +00:00
if (errno != ENOENT) {
2020-04-11 22:48:11 +00:00
errbuf = fmt::format(FMT_STRING("NOLAUNCH {}"), strerror(errno));
2019-07-20 04:22:58 +00:00
_writeStr(errbuf.c_str(), errbuf.size(), m_readpipe[1]);
2018-12-08 05:18:42 +00:00
exit(1);
2015-08-31 03:36:24 +00:00
}
2018-12-08 05:18:42 +00:00
}
/* Otherwise default blender */
2019-07-20 04:22:58 +00:00
execlp(DEFAULT_BLENDER_BIN, DEFAULT_BLENDER_BIN, "--background", "-P", blenderShellPath.c_str(), "--",
readfds.c_str(), writefds.c_str(), vLevel.c_str(), blenderAddonPath.c_str(), nullptr);
2018-12-08 05:18:42 +00:00
if (errno != ENOENT) {
2020-04-11 22:48:11 +00:00
errbuf = fmt::format(FMT_STRING("NOLAUNCH {}"), strerror(errno));
2019-07-20 04:22:58 +00:00
_writeStr(errbuf.c_str(), errbuf.size(), m_readpipe[1]);
2018-12-08 05:18:42 +00:00
exit(1);
}
/* Unable to find blender */
_writeStr("NOBLENDER", 9, m_readpipe[1]);
exit(1);
}
close(m_writepipe[0]);
close(m_readpipe[1]);
m_blenderProc = pid;
2015-07-22 19:14:50 +00:00
#endif
2015-05-24 04:51:16 +00:00
2018-12-08 05:18:42 +00:00
/* Stash error path and unlink existing file */
2016-12-26 05:54:23 +00:00
#if _WIN32
2018-12-08 05:18:42 +00:00
m_errPath = hecl::SystemString(TMPDIR) +
2020-04-11 22:48:11 +00:00
fmt::format(FMT_STRING(_SYS_STR("/hecl_{:016X}.derp")), (unsigned long long)m_pinfo.dwProcessId);
2016-12-26 05:54:23 +00:00
#else
m_errPath = hecl::SystemString(TMPDIR) +
2020-04-11 22:48:11 +00:00
fmt::format(FMT_STRING(_SYS_STR("/hecl_{:016X}.derp")), (unsigned long long)m_blenderProc);
2016-12-26 05:54:23 +00:00
#endif
2018-12-08 05:18:42 +00:00
hecl::Unlink(m_errPath.c_str());
2016-08-02 22:12:49 +00:00
2018-12-08 05:18:42 +00:00
/* Handle first response */
2019-10-01 07:23:35 +00:00
std::string lineStr = _readStdString();
2016-04-26 00:47:11 +00:00
2019-10-01 07:23:35 +00:00
if (!lineStr.compare(0, 8, "NOLAUNCH")) {
2018-12-08 05:18:42 +00:00
_closePipe();
2020-04-11 22:48:11 +00:00
BlenderLog.report(logvisor::Fatal, FMT_STRING("Unable to launch blender: {}"), lineStr.c_str() + 9);
2019-10-01 07:23:35 +00:00
} else if (!lineStr.compare(0, 9, "NOBLENDER")) {
2018-12-08 05:18:42 +00:00
_closePipe();
2019-07-28 01:19:48 +00:00
#if _WIN32
2020-04-11 22:48:11 +00:00
BlenderLog.report(logvisor::Fatal, FMT_STRING(_SYS_STR("Unable to find blender at '{}'")), blenderBin);
2019-07-28 01:19:48 +00:00
#else
2018-12-08 05:18:42 +00:00
if (blenderBin)
2020-04-11 22:48:11 +00:00
BlenderLog.report(logvisor::Fatal, FMT_STRING(_SYS_STR("Unable to find blender at '{}' or '{}'")), blenderBin,
2018-12-08 05:18:42 +00:00
DEFAULT_BLENDER_BIN);
else
2020-04-11 22:48:11 +00:00
BlenderLog.report(logvisor::Fatal, FMT_STRING(_SYS_STR("Unable to find blender at '{}'")), DEFAULT_BLENDER_BIN);
2019-07-28 01:19:48 +00:00
#endif
} else if (lineStr == "INVALIDBLENDERVER") {
2019-05-10 04:07:48 +00:00
_closePipe();
BlenderLog.report(logvisor::Fatal, FMT_STRING(_SYS_STR("Installed blender version must be >= {}.{}")),
MinBlenderMajorSearch, MinBlenderMinorSearch);
2019-10-01 07:23:35 +00:00
} else if (lineStr == "NOADDON") {
2018-12-08 05:18:42 +00:00
_closePipe();
if (blenderAddonPath != _SYS_STR("SKIPINSTALL"))
InstallAddon(blenderAddonPath.c_str());
2018-12-08 05:18:42 +00:00
++installAttempt;
if (installAttempt >= 2)
2020-04-11 22:48:11 +00:00
BlenderLog.report(logvisor::Fatal, FMT_STRING(_SYS_STR("unable to install blender addon using '{}'")),
2018-12-08 05:18:42 +00:00
blenderAddonPath.c_str());
2019-10-01 07:23:35 +00:00
#ifndef _WIN32
waitpid(pid, nullptr, 0);
#endif
2018-12-08 05:18:42 +00:00
continue;
2019-10-01 07:23:35 +00:00
} else if (lineStr == "ADDONINSTALLED") {
2018-12-08 05:18:42 +00:00
_closePipe();
blenderAddonPath = _SYS_STR("SKIPINSTALL");
2019-10-01 07:23:35 +00:00
#ifndef _WIN32
waitpid(pid, nullptr, 0);
#endif
2018-12-08 05:18:42 +00:00
continue;
2019-10-01 07:23:35 +00:00
} else if (lineStr != "READY") {
2018-12-08 05:18:42 +00:00
_closePipe();
2020-04-11 22:48:11 +00:00
BlenderLog.report(logvisor::Fatal, FMT_STRING("read '{}' from blender; expected 'READY'"), lineStr);
2015-08-31 03:36:24 +00:00
}
2018-12-08 05:18:42 +00:00
_writeStr("ACK");
break;
}
2017-12-06 03:22:31 +00:00
#else
2020-04-11 22:48:11 +00:00
BlenderLog.report(logvisor::Fatal, FMT_STRING("BlenderConnection not available on UWP"));
2017-12-06 03:22:31 +00:00
#endif
2015-05-24 04:51:16 +00:00
}
2018-12-08 05:18:42 +00:00
Connection::~Connection() { _closePipe(); }
2015-05-24 22:19:28 +00:00
2018-12-08 05:18:42 +00:00
void Vector2f::read(Connection& conn) { conn._readBuf(&val, 8); }
void Vector3f::read(Connection& conn) { conn._readBuf(&val, 12); }
void Vector4f::read(Connection& conn) { conn._readBuf(&val, 16); }
void Matrix4f::read(Connection& conn) { conn._readBuf(&val, 64); }
void Index::read(Connection& conn) { conn._readBuf(&val, 4); }
2019-05-08 03:47:34 +00:00
void Float::read(Connection& conn) { conn._readBuf(&val, 4); }
void Boolean::read(Connection& conn) { conn._readBuf(&val, 1); }
2017-12-29 07:56:31 +00:00
2019-10-01 07:23:35 +00:00
bool PyOutStream::StreamBuf::sendLine(std::string_view line) {
m_parent.m_parent->_writeStr(line);
if (!m_parent.m_parent->_isOk()) {
2018-12-08 05:18:42 +00:00
if (m_deleteOnError)
m_parent.m_parent->deleteBlend();
m_parent.m_parent->_blenderDied();
2019-10-01 07:23:35 +00:00
return false;
2018-12-08 05:18:42 +00:00
}
2019-10-01 07:23:35 +00:00
return true;
2018-12-08 05:18:42 +00:00
}
2020-04-11 04:58:06 +00:00
PyOutStream::StreamBuf::int_type PyOutStream::StreamBuf::overflow(int_type ch) {
if (!m_parent.m_parent || !m_parent.m_parent->m_lock)
2020-04-11 22:48:11 +00:00
BlenderLog.report(logvisor::Fatal, FMT_STRING("lock not held for PyOutStream writing"));
2020-04-11 04:58:06 +00:00
if (ch != traits_type::eof() && ch != '\n' && ch != '\0') {
m_lineBuf += char_type(ch);
return ch;
}
sendLine(m_lineBuf);
m_lineBuf.clear();
return ch;
}
2019-10-01 07:23:35 +00:00
std::streamsize PyOutStream::StreamBuf::xsputn(const char_type* __first, std::streamsize __n) {
if (!m_parent.m_parent || !m_parent.m_parent->m_lock)
2020-04-11 22:48:11 +00:00
BlenderLog.report(logvisor::Fatal, FMT_STRING("lock not held for PyOutStream writing"));
2019-10-01 07:23:35 +00:00
const char_type* __last = __first + __n;
const char_type* __s = __first;
for (const char_type* __e = __first; __e != __last; ++__e) {
if (*__e == '\n' || traits_type::to_int_type(*__e) == traits_type::eof()) {
2019-10-01 07:23:35 +00:00
std::string_view line(__s, __e - __s);
bool result;
if (!m_lineBuf.empty()) {
/* Complete line with incomplete line from previous call */
m_lineBuf += line;
result = sendLine(m_lineBuf);
m_lineBuf.clear();
} else {
/* Complete line (optimal case) */
result = sendLine(line);
}
if (!result || traits_type::to_int_type(*__e) == traits_type::eof())
2019-10-01 07:23:35 +00:00
return __e - __first; /* Error or eof, end now */
__s += line.size() + 1;
}
}
if (__s != __last) /* String ended with incomplete line (ideally this shouldn't happen for zero buffer overhead) */
m_lineBuf += std::string_view(__s, __last - __s);
return __n;
}
constexpr std::array<std::string_view, 12> BlendTypeStrs{"NONE"sv, "MESH"sv, "CMESH"sv, "ARMATURE"sv,
"ACTOR"sv, "AREA"sv, "WORLD"sv, "MAPAREA"sv,
"MAPUNIVERSE"sv, "FRAME"sv, "PATH"sv};
2018-12-08 05:18:42 +00:00
bool Connection::createBlend(const ProjectPath& path, BlendType type) {
if (m_lock) {
BlenderLog.report(logvisor::Fatal,
FMT_STRING("BlenderConnection::createBlend() musn't be called with stream active"));
2015-07-28 02:25:33 +00:00
return false;
2018-12-08 05:18:42 +00:00
}
2020-04-11 22:48:11 +00:00
_writeStr(fmt::format(FMT_STRING("CREATE \"{}\" {}"), path.getAbsolutePathUTF8(), BlendTypeStrs[int(type)]));
2019-10-01 07:23:35 +00:00
if (_isFinished()) {
2018-12-08 05:18:42 +00:00
/* Delete immediately in case save doesn't occur */
hecl::Unlink(path.getAbsolutePath().data());
m_loadedBlend = path;
m_loadedType = type;
return true;
}
return false;
2015-07-28 02:25:33 +00:00
}
2018-12-08 05:18:42 +00:00
bool Connection::openBlend(const ProjectPath& path, bool force) {
if (m_lock) {
BlenderLog.report(logvisor::Fatal,
FMT_STRING("BlenderConnection::openBlend() musn't be called with stream active"));
2018-12-08 05:18:42 +00:00
return false;
}
if (!force && path == m_loadedBlend)
return true;
2020-04-11 22:48:11 +00:00
_writeStr(fmt::format(FMT_STRING("OPEN \"{}\""), path.getAbsolutePathUTF8()));
2019-10-01 07:23:35 +00:00
if (_isFinished()) {
2018-12-08 05:18:42 +00:00
m_loadedBlend = path;
_writeStr("GETTYPE");
2019-10-01 07:23:35 +00:00
std::string typeStr = _readStdString();
2018-12-08 05:18:42 +00:00
m_loadedType = BlendType::None;
unsigned idx = 0;
2019-10-01 07:23:35 +00:00
for (const auto& type : BlendTypeStrs) {
if (type == typeStr) {
2018-12-08 05:18:42 +00:00
m_loadedType = BlendType(idx);
break;
}
++idx;
2015-05-24 22:19:28 +00:00
}
2018-12-08 05:18:42 +00:00
m_loadedRigged = false;
if (m_loadedType == BlendType::Mesh) {
_writeStr("GETMESHRIGGED");
2019-10-01 07:23:35 +00:00
if (_isTrue())
2018-12-08 05:18:42 +00:00
m_loadedRigged = true;
}
return true;
}
return false;
2015-05-24 22:19:28 +00:00
}
2018-12-08 05:18:42 +00:00
bool Connection::saveBlend() {
if (m_lock) {
BlenderLog.report(logvisor::Fatal,
FMT_STRING("BlenderConnection::saveBlend() musn't be called with stream active"));
return false;
2018-12-08 05:18:42 +00:00
}
_writeStr("SAVE");
2019-10-01 07:23:35 +00:00
return _isFinished();
}
2018-12-08 05:18:42 +00:00
void Connection::deleteBlend() {
if (m_loadedBlend) {
hecl::Unlink(m_loadedBlend.getAbsolutePath().data());
2020-04-11 22:48:11 +00:00
BlenderLog.report(logvisor::Info, FMT_STRING(_SYS_STR("Deleted '{}'")), m_loadedBlend.getAbsolutePath());
2018-12-08 05:18:42 +00:00
m_loadedBlend = ProjectPath();
}
2015-08-05 22:59:59 +00:00
}
2017-12-29 07:56:31 +00:00
PyOutStream::PyOutStream(Connection* parent, bool deleteOnError)
2018-12-08 05:18:42 +00:00
: std::ostream(&m_sbuf), m_parent(parent), m_sbuf(*this, deleteOnError) {
m_parent->m_pyStreamActive = true;
m_parent->_writeStr("PYBEGIN");
2019-10-01 07:23:35 +00:00
m_parent->_checkReady("unable to open PyOutStream with blender"sv);
2018-12-08 05:18:42 +00:00
}
void PyOutStream::close() {
if (m_parent && m_parent->m_lock) {
m_parent->_writeStr("PYEND");
2019-10-01 07:23:35 +00:00
m_parent->_checkDone("unable to close PyOutStream with blender"sv);
2018-12-08 05:18:42 +00:00
m_parent->m_pyStreamActive = false;
m_parent->m_lock = false;
}
2017-12-29 07:56:31 +00:00
}
2019-10-01 07:23:35 +00:00
void PyOutStream::linkBlend(std::string_view target, std::string_view objName, bool link) {
format(
FMT_STRING("if '{}' not in bpy.data.scenes:\n"
" with bpy.data.libraries.load('''{}''', link={}, relative=True) as (data_from, data_to):\n"
" data_to.scenes = data_from.scenes\n"
" obj_scene = None\n"
" for scene in data_to.scenes:\n"
" if scene.name == '{}':\n"
" obj_scene = scene\n"
" break\n"
" if not obj_scene:\n"
" raise RuntimeError('''unable to find {} in {}. try deleting it and restart the extract.''')\n"
" obj = None\n"
" for object in obj_scene.objects:\n"
" if object.name == obj_scene.name:\n"
" obj = object\n"
"else:\n"
" obj = bpy.data.objects['{}']\n"
"\n"),
objName, target, link ? "True" : "False", objName, objName, target, objName);
2018-12-08 05:18:42 +00:00
}
2019-10-01 07:23:35 +00:00
void PyOutStream::linkArmature(std::string_view target, std::string_view armName) {
format(FMT_STRING(
"target_arm_name = '{}'\n"
2019-10-01 07:23:35 +00:00
"if target_arm_name not in bpy.data.armatures:\n"
" with bpy.data.libraries.load('''{}''', link=True, relative=True) as (data_from, data_to):\n"
" if target_arm_name not in data_from.armatures:\n"
" raise RuntimeError('''unable to find {} in {}. try deleting it and restart the extract.''')\n"
" data_to.armatures.append(target_arm_name)\n"
" obj = bpy.data.objects.new(target_arm_name, bpy.data.armatures[target_arm_name])\n"
"else:\n"
" obj = bpy.data.objects[target_arm_name]\n"
"\n"),
armName, target, armName, target);
}
void PyOutStream::linkMesh(std::string_view target, std::string_view meshName) {
format(FMT_STRING(
"target_mesh_name = '{}'\n"
2019-10-01 07:23:35 +00:00
"if target_mesh_name not in bpy.data.objects:\n"
" with bpy.data.libraries.load('''{}''', link=True, relative=True) as (data_from, data_to):\n"
" if target_mesh_name not in data_from.objects:\n"
" raise RuntimeError('''unable to find {} in {}. try deleting it and restart the extract.''')\n"
" data_to.objects.append(target_mesh_name)\n"
"obj = bpy.data.objects[target_mesh_name]\n"
"\n"),
meshName, target, meshName, target);
}
void PyOutStream::linkBackground(std::string_view target, std::string_view sceneName) {
if (sceneName.empty()) {
2020-04-11 22:48:11 +00:00
format(FMT_STRING("with bpy.data.libraries.load('''{}''', link=True, relative=True) as (data_from, data_to):\n"
" data_to.scenes = data_from.scenes\n"
"obj_scene = None\n"
"for scene in data_to.scenes:\n"
" obj_scene = scene\n"
" break\n"
"if not obj_scene:\n"
" raise RuntimeError('''unable to find {}. try deleting it and restart the extract.''')\n"
"\n"
"bpy.context.scene.background_set = obj_scene\n"),
target, target);
2018-12-08 05:18:42 +00:00
} else {
format(FMT_STRING(
"if '{}' not in bpy.data.scenes:\n"
" with bpy.data.libraries.load('''{}''', link=True, relative=True) as (data_from, data_to):\n"
" data_to.scenes = data_from.scenes\n"
" obj_scene = None\n"
" for scene in data_to.scenes:\n"
" if scene.name == '{}':\n"
" obj_scene = scene\n"
" break\n"
" if not obj_scene:\n"
" raise RuntimeError('''unable to find {} in {}. try deleting it and restart the extract.''')\n"
"\n"
"bpy.context.scene.background_set = bpy.data.scenes['{}']\n"),
sceneName, target, sceneName, sceneName, target, sceneName);
2018-12-08 05:18:42 +00:00
}
}
void PyOutStream::AABBToBMesh(const atVec3f& min, const atVec3f& max) {
athena::simd_floats minf(min.simd);
athena::simd_floats maxf(max.simd);
2020-04-11 22:48:11 +00:00
format(FMT_STRING("bm = bmesh.new()\n"
"bm.verts.new(({},{},{}))\n"
"bm.verts.new(({},{},{}))\n"
"bm.verts.new(({},{},{}))\n"
"bm.verts.new(({},{},{}))\n"
"bm.verts.new(({},{},{}))\n"
"bm.verts.new(({},{},{}))\n"
"bm.verts.new(({},{},{}))\n"
"bm.verts.new(({},{},{}))\n"
"bm.verts.ensure_lookup_table()\n"
"bm.edges.new((bm.verts[0], bm.verts[1]))\n"
"bm.edges.new((bm.verts[0], bm.verts[2]))\n"
"bm.edges.new((bm.verts[0], bm.verts[4]))\n"
"bm.edges.new((bm.verts[3], bm.verts[1]))\n"
"bm.edges.new((bm.verts[3], bm.verts[2]))\n"
"bm.edges.new((bm.verts[3], bm.verts[7]))\n"
"bm.edges.new((bm.verts[5], bm.verts[1]))\n"
"bm.edges.new((bm.verts[5], bm.verts[4]))\n"
"bm.edges.new((bm.verts[5], bm.verts[7]))\n"
"bm.edges.new((bm.verts[6], bm.verts[2]))\n"
"bm.edges.new((bm.verts[6], bm.verts[4]))\n"
"bm.edges.new((bm.verts[6], bm.verts[7]))\n"),
minf[0], minf[1], minf[2], maxf[0], minf[1], minf[2], minf[0], maxf[1], minf[2], maxf[0], maxf[1], minf[2],
minf[0], minf[1], maxf[2], maxf[0], minf[1], maxf[2], minf[0], maxf[1], maxf[2], maxf[0], maxf[1], maxf[2]);
2018-12-08 05:18:42 +00:00
}
void PyOutStream::centerView() {
*this << "for obj in bpy.context.scene.objects:\n"
2019-05-08 03:47:34 +00:00
" if obj.type == 'CAMERA' or obj.type == 'LIGHT':\n"
" obj.hide_set(True)\n"
2018-12-08 05:18:42 +00:00
"\n"
2019-05-08 03:47:34 +00:00
"old_smooth_view = bpy.context.preferences.view.smooth_view\n"
"bpy.context.preferences.view.smooth_view = 0\n"
2018-12-08 05:18:42 +00:00
"for window in bpy.context.window_manager.windows:\n"
" screen = window.screen\n"
" for area in screen.areas:\n"
" if area.type == 'VIEW_3D':\n"
" for region in area.regions:\n"
" if region.type == 'WINDOW':\n"
" override = {'scene': bpy.context.scene, 'window': window, 'screen': screen, 'area': "
"area, 'region': region}\n"
" bpy.ops.view3d.view_all(override)\n"
" break\n"
2019-05-08 03:47:34 +00:00
"bpy.context.preferences.view.smooth_view = old_smooth_view\n"
2018-12-08 05:18:42 +00:00
"\n"
"for obj in bpy.context.scene.objects:\n"
2019-05-08 03:47:34 +00:00
" if obj.type == 'CAMERA' or obj.type == 'LIGHT':\n"
" obj.hide_set(True)\n";
2018-12-08 05:18:42 +00:00
}
ANIMOutStream::ANIMOutStream(Connection* parent) : m_parent(parent) {
m_parent->_writeStr("PYANIM");
2019-10-01 07:23:35 +00:00
m_parent->_checkAnimReady("unable to open ANIMOutStream"sv);
2017-12-29 07:56:31 +00:00
}
2018-12-08 05:18:42 +00:00
ANIMOutStream::~ANIMOutStream() {
char tp = -1;
m_parent->_writeBuf(&tp, 1);
2019-10-01 07:23:35 +00:00
m_parent->_checkAnimDone("unable to close ANIMOutStream"sv);
2018-12-08 05:18:42 +00:00
}
void ANIMOutStream::changeCurve(CurveType type, unsigned crvIdx, unsigned keyCount) {
if (m_curCount != m_totalCount)
2020-04-11 22:48:11 +00:00
BlenderLog.report(logvisor::Fatal, FMT_STRING("incomplete ANIMOutStream for change"));
2018-12-08 05:18:42 +00:00
m_curCount = 0;
m_totalCount = keyCount;
char tp = char(type);
m_parent->_writeBuf(&tp, 1);
struct {
uint32_t ci;
uint32_t kc;
} info = {uint32_t(crvIdx), uint32_t(keyCount)};
m_parent->_writeBuf(reinterpret_cast<const char*>(&info), 8);
m_inCurve = true;
}
void ANIMOutStream::write(unsigned frame, float val) {
if (!m_inCurve)
2020-04-11 22:48:11 +00:00
BlenderLog.report(logvisor::Fatal, FMT_STRING("changeCurve not called before write"));
2018-12-08 05:18:42 +00:00
if (m_curCount < m_totalCount) {
struct {
uint32_t frm;
float val;
} key = {uint32_t(frame), val};
m_parent->_writeBuf(reinterpret_cast<const char*>(&key), 8);
++m_curCount;
} else
2020-04-11 22:48:11 +00:00
BlenderLog.report(logvisor::Fatal, FMT_STRING("ANIMOutStream keyCount overflow"));
2018-12-08 05:18:42 +00:00
}
2019-05-08 03:47:34 +00:00
Mesh::SkinBind::SkinBind(Connection& conn) {
2019-10-01 07:23:35 +00:00
conn._readValue(vg_idx);
conn._readValue(weight);
2019-05-08 03:47:34 +00:00
}
2018-12-08 05:18:42 +00:00
void Mesh::normalizeSkinBinds() {
2019-05-08 03:47:34 +00:00
for (auto& skin : skins) {
2018-12-08 05:18:42 +00:00
float accum = 0.f;
for (const SkinBind& bind : skin)
2019-05-08 23:38:00 +00:00
if (bind.valid())
2019-05-08 03:47:34 +00:00
accum += bind.weight;
2018-12-08 05:18:42 +00:00
if (accum > FLT_EPSILON) {
for (SkinBind& bind : skin)
2019-05-08 23:38:00 +00:00
if (bind.valid())
2019-05-08 03:47:34 +00:00
bind.weight /= accum;
2016-09-10 05:38:18 +00:00
}
2018-12-08 05:18:42 +00:00
}
2016-09-10 05:38:18 +00:00
}
2019-05-08 03:47:34 +00:00
Mesh::Mesh(Connection& conn, HMDLTopology topologyIn, int skinSlotCount, bool useLuvs)
2018-12-08 05:18:42 +00:00
: topology(topologyIn), sceneXf(conn), aabbMin(conn), aabbMax(conn) {
conn._readVectorFunc(materialSets, [&]() { conn._readVector(materialSets.emplace_back()); });
2018-12-08 05:18:42 +00:00
2019-05-08 03:47:34 +00:00
MeshOptimizer opt(conn, materialSets[0], useLuvs);
opt.optimize(*this, skinSlotCount);
2018-12-08 05:18:42 +00:00
2019-10-01 07:23:35 +00:00
conn._readVector(boneNames);
2019-05-08 03:47:34 +00:00
if (boneNames.size())
for (Surface& s : surfaces)
s.skinBankIdx = skinBanks.addSurface(*this, s, skinSlotCount);
2018-12-08 05:18:42 +00:00
/* Custom properties */
2019-10-01 07:23:35 +00:00
uint32_t propCount;
conn._readValue(propCount);
2018-12-08 05:18:42 +00:00
std::string keyBuf;
std::string valBuf;
2019-10-01 07:23:35 +00:00
for (uint32_t i = 0; i < propCount; ++i) {
keyBuf = conn._readStdString();
valBuf = conn._readStdString();
2018-12-08 05:18:42 +00:00
customProps[keyBuf] = valBuf;
}
/* Connect skinned verts to bank slots */
if (boneNames.size()) {
for (Surface& surf : surfaces) {
SkinBanks::Bank& bank = skinBanks.banks[surf.skinBankIdx];
for (Surface::Vert& vert : surf.verts) {
if (vert.iPos == 0xffffffff)
continue;
for (uint32_t i = 0; i < bank.m_skinIdxs.size(); ++i) {
if (bank.m_skinIdxs[i] == vert.iSkin) {
vert.iBankSkin = i;
break;
}
2015-10-04 04:35:18 +00:00
}
2018-12-08 05:18:42 +00:00
}
2015-10-04 04:35:18 +00:00
}
2018-12-08 05:18:42 +00:00
}
}
Mesh Mesh::getContiguousSkinningVersion() const {
Mesh newMesh = *this;
newMesh.pos.clear();
newMesh.norm.clear();
newMesh.contiguousSkinVertCounts.clear();
newMesh.contiguousSkinVertCounts.reserve(skins.size());
for (std::size_t i = 0; i < skins.size(); ++i) {
2018-12-08 05:18:42 +00:00
std::unordered_map<std::pair<uint32_t, uint32_t>, uint32_t> contigMap;
std::size_t vertCount = 0;
2018-12-08 05:18:42 +00:00
for (Surface& surf : newMesh.surfaces) {
for (Surface::Vert& vert : surf.verts) {
if (vert.iPos == 0xffffffff)
continue;
if (vert.iSkin == i) {
auto key = std::make_pair(vert.iPos, vert.iNorm);
auto search = contigMap.find(key);
if (search != contigMap.end()) {
vert.iPos = search->second;
vert.iNorm = search->second;
} else {
uint32_t newIdx = newMesh.pos.size();
contigMap[key] = newIdx;
newMesh.pos.push_back(pos.at(vert.iPos));
newMesh.norm.push_back(norm.at(vert.iNorm));
vert.iPos = newIdx;
vert.iNorm = newIdx;
++vertCount;
}
2015-10-22 02:01:08 +00:00
}
2018-12-08 05:18:42 +00:00
}
2015-10-22 02:01:08 +00:00
}
2018-12-08 05:18:42 +00:00
newMesh.contiguousSkinVertCounts.push_back(vertCount);
}
return newMesh;
2015-10-22 02:01:08 +00:00
}
2019-05-08 03:47:34 +00:00
template <typename T>
static T SwapFourCC(T fcc) {
return T(hecl::SBig(std::underlying_type_t<T>(fcc)));
}
Material::PASS::PASS(Connection& conn) {
2019-10-01 07:23:35 +00:00
conn._readValue(type);
2019-05-08 03:47:34 +00:00
type = SwapFourCC(type);
2019-10-01 07:23:35 +00:00
tex = conn._readPath();
2019-05-08 03:47:34 +00:00
2019-10-01 07:23:35 +00:00
conn._readValue(source);
conn._readValue(uvAnimType);
2019-05-08 03:47:34 +00:00
uint32_t argCount;
2019-10-01 07:23:35 +00:00
conn._readValue(argCount);
2019-05-08 03:47:34 +00:00
for (uint32_t i = 0; i < argCount; ++i)
2019-10-01 07:23:35 +00:00
conn._readValue(uvAnimParms[i]);
conn._readValue(alpha);
2019-05-08 03:47:34 +00:00
}
Material::CLR::CLR(Connection& conn) {
2019-10-01 07:23:35 +00:00
conn._readValue(type);
2019-05-08 03:47:34 +00:00
type = SwapFourCC(type);
color.read(conn);
}
2018-12-08 05:18:42 +00:00
Material::Material(Connection& conn) {
2019-10-01 07:23:35 +00:00
name = conn._readStdString();
2015-10-14 23:06:47 +00:00
2019-10-01 07:23:35 +00:00
conn._readValue(passIndex);
conn._readValue(shaderType);
2019-05-08 03:47:34 +00:00
shaderType = SwapFourCC(shaderType);
2019-10-01 07:23:35 +00:00
conn._readVectorFunc(chunks, [&]() {
2019-05-08 03:47:34 +00:00
ChunkType type;
2019-10-01 07:23:35 +00:00
conn._readValue(type);
2019-05-08 03:47:34 +00:00
type = SwapFourCC(type);
chunks.push_back(Chunk::Build(type, conn));
2019-10-01 07:23:35 +00:00
});
2015-10-17 02:06:27 +00:00
2018-12-08 05:18:42 +00:00
uint32_t iPropCount;
2019-10-01 07:23:35 +00:00
conn._readValue(iPropCount);
2018-12-08 05:18:42 +00:00
iprops.reserve(iPropCount);
for (uint32_t i = 0; i < iPropCount; ++i) {
2019-10-01 07:23:35 +00:00
std::string readStr = conn._readStdString();
conn._readValue(iprops[readStr]);
2018-12-08 05:18:42 +00:00
}
2019-10-01 07:23:35 +00:00
conn._readValue(blendMode);
2017-12-29 07:56:31 +00:00
}
2018-12-08 05:18:42 +00:00
bool Mesh::Surface::Vert::operator==(const Vert& other) const {
return std::tie(iPos, iNorm, iColor, iUv, iSkin) ==
std::tie(other.iPos, other.iNorm, other.iColor, other.iUv, other.iSkin);
2015-10-04 04:35:18 +00:00
}
2018-12-08 05:18:42 +00:00
static bool VertInBank(const std::vector<uint32_t>& bank, uint32_t sIdx) {
return std::any_of(bank.cbegin(), bank.cend(), [sIdx](auto index) { return index == sIdx; });
2017-12-29 07:56:31 +00:00
}
2018-12-08 05:18:42 +00:00
void Mesh::SkinBanks::Bank::addSkins(const Mesh& parent, const std::vector<uint32_t>& skinIdxs) {
for (uint32_t sidx : skinIdxs) {
m_skinIdxs.push_back(sidx);
for (const SkinBind& bind : parent.skins[sidx]) {
2019-05-08 23:38:00 +00:00
if (!bind.valid())
2019-05-08 03:47:34 +00:00
break;
2018-12-08 05:18:42 +00:00
bool found = false;
for (uint32_t bidx : m_boneIdxs) {
2019-05-08 03:47:34 +00:00
if (bidx == bind.vg_idx) {
2018-12-08 05:18:42 +00:00
found = true;
break;
2015-10-04 04:35:18 +00:00
}
2018-12-08 05:18:42 +00:00
}
if (!found)
2019-05-08 03:47:34 +00:00
m_boneIdxs.push_back(bind.vg_idx);
2018-12-08 05:18:42 +00:00
}
}
}
std::vector<Mesh::SkinBanks::Bank>::iterator Mesh::SkinBanks::addSkinBank(int skinSlotCount) {
banks.emplace_back();
if (skinSlotCount > 0)
banks.back().m_skinIdxs.reserve(skinSlotCount);
return banks.end() - 1;
}
uint32_t Mesh::SkinBanks::addSurface(const Mesh& mesh, const Surface& surf, int skinSlotCount) {
if (banks.empty())
addSkinBank(skinSlotCount);
std::vector<uint32_t> toAdd;
if (skinSlotCount > 0)
toAdd.reserve(skinSlotCount);
std::vector<Bank>::iterator bankIt = banks.begin();
for (;;) {
bool done = true;
for (; bankIt != banks.end(); ++bankIt) {
Bank& bank = *bankIt;
done = true;
for (const Surface::Vert& v : surf.verts) {
if (v.iPos == 0xffffffff)
continue;
if (!VertInBank(bank.m_skinIdxs, v.iSkin) && !VertInBank(toAdd, v.iSkin)) {
toAdd.push_back(v.iSkin);
if (skinSlotCount > 0 && bank.m_skinIdxs.size() + toAdd.size() > std::size_t(skinSlotCount)) {
2018-12-08 05:18:42 +00:00
toAdd.clear();
done = false;
break;
}
2015-10-04 04:35:18 +00:00
}
2018-12-08 05:18:42 +00:00
}
if (toAdd.size()) {
bank.addSkins(mesh, toAdd);
toAdd.clear();
}
if (done)
return uint32_t(bankIt - banks.begin());
2015-10-04 04:35:18 +00:00
}
2018-12-08 05:18:42 +00:00
if (!done) {
bankIt = addSkinBank(skinSlotCount);
continue;
}
2018-12-08 05:18:42 +00:00
break;
}
return uint32_t(-1);
}
ColMesh::ColMesh(Connection& conn) {
2019-10-01 07:23:35 +00:00
conn._readVector(materials);
conn._readVector(verts);
conn._readVector(edges);
conn._readVector(trianges);
2018-12-08 05:18:42 +00:00
}
ColMesh::Material::Material(Connection& conn) {
2019-10-01 07:23:35 +00:00
name = conn._readStdString();
2018-12-08 05:18:42 +00:00
conn._readBuf(&unknown, 42);
}
ColMesh::Edge::Edge(Connection& conn) { conn._readBuf(this, 9); }
ColMesh::Triangle::Triangle(Connection& conn) { conn._readBuf(this, 17); }
World::Area::Dock::Dock(Connection& conn) {
verts[0].read(conn);
verts[1].read(conn);
verts[2].read(conn);
verts[3].read(conn);
targetArea.read(conn);
targetDock.read(conn);
}
World::Area::Area(Connection& conn) {
2019-10-01 07:23:35 +00:00
std::string name = conn._readStdString();
2018-12-08 05:18:42 +00:00
path.assign(conn.getBlendPath().getParentPath(), name);
aabb[0].read(conn);
aabb[1].read(conn);
transform.read(conn);
2019-10-01 07:23:35 +00:00
conn._readVector(docks);
2018-12-08 05:18:42 +00:00
}
World::World(Connection& conn) { conn._readVector(areas); }
2018-12-08 05:18:42 +00:00
Light::Light(Connection& conn) : sceneXf(conn), color(conn) {
conn._readBuf(&layer, 29);
2019-10-01 07:23:35 +00:00
name = conn._readStdString();
2018-12-08 05:18:42 +00:00
}
MapArea::Surface::Surface(Connection& conn) {
centerOfMass.read(conn);
normal.read(conn);
conn._readBuf(&start, 8);
2019-10-01 07:23:35 +00:00
conn._readVectorFunc(borders, [&]() { conn._readBuf(&borders.emplace_back(), 8); });
2018-12-08 05:18:42 +00:00
}
MapArea::POI::POI(Connection& conn) {
conn._readBuf(&type, 12);
xf.read(conn);
}
MapArea::MapArea(Connection& conn) {
2019-10-01 07:23:35 +00:00
conn._readValue(visType);
conn._readVector(verts);
2018-12-08 05:18:42 +00:00
uint8_t isIdx;
2019-10-01 07:23:35 +00:00
conn._readValue(isIdx);
2018-12-08 05:18:42 +00:00
while (isIdx) {
2019-10-01 07:23:35 +00:00
conn._readValue(indices.emplace_back());
conn._readValue(isIdx);
2018-12-08 05:18:42 +00:00
}
2019-10-01 07:23:35 +00:00
conn._readVector(surfaces);
conn._readVector(pois);
2018-12-08 05:18:42 +00:00
}
MapUniverse::World::World(Connection& conn) {
2019-10-01 07:23:35 +00:00
name = conn._readStdString();
2018-12-08 05:18:42 +00:00
xf.read(conn);
2019-10-01 07:23:35 +00:00
conn._readVector(hexagons);
2018-12-08 05:18:42 +00:00
color.read(conn);
2019-10-01 07:23:35 +00:00
std::string path = conn._readStdString();
if (!path.empty()) {
2018-12-08 05:18:42 +00:00
hecl::SystemStringConv sysPath(path);
worldPath.assign(conn.getBlendPath().getProject().getProjectWorkingPath(), sysPath.sys_str());
}
}
MapUniverse::MapUniverse(Connection& conn) {
2019-10-01 07:23:35 +00:00
hexagonPath = conn._readPath();
conn._readVector(worlds);
2018-12-08 05:18:42 +00:00
}
Actor::Actor(Connection& conn) {
2019-10-01 07:23:35 +00:00
conn._readVector(armatures);
conn._readVector(subtypes);
conn._readVector(attachments);
conn._readVector(actions);
2018-12-08 05:18:42 +00:00
}
PathMesh::PathMesh(Connection& conn) { conn._readVector(data); }
2018-12-08 05:18:42 +00:00
const Bone* Armature::lookupBone(const char* name) const {
for (const Bone& b : bones)
2019-10-01 07:23:35 +00:00
if (b.name == name)
2018-12-08 05:18:42 +00:00
return &b;
return nullptr;
}
const Bone* Armature::getParent(const Bone* bone) const {
if (bone->parent < 0)
return nullptr;
return &bones[bone->parent];
}
const Bone* Armature::getChild(const Bone* bone, std::size_t child) const {
2018-12-08 05:18:42 +00:00
if (child >= bone->children.size())
return nullptr;
int32_t cIdx = bone->children[child];
if (cIdx < 0)
return nullptr;
return &bones[cIdx];
}
2018-12-08 05:18:42 +00:00
const Bone* Armature::getRoot() const {
for (const Bone& b : bones)
if (b.parent < 0)
return &b;
return nullptr;
2016-10-01 23:18:52 +00:00
}
Armature::Armature(Connection& conn) { conn._readVector(bones); }
2016-10-01 23:18:52 +00:00
2018-12-08 05:18:42 +00:00
Bone::Bone(Connection& conn) {
2019-10-01 07:23:35 +00:00
name = conn._readStdString();
2018-12-08 05:18:42 +00:00
origin.read(conn);
2019-10-01 07:23:35 +00:00
conn._readValue(parent);
conn._readVector(children);
}
2016-08-11 19:51:41 +00:00
2019-10-01 07:23:35 +00:00
Actor::ActorArmature::ActorArmature(Connection& conn) {
name = conn._readStdString();
path = conn._readPath();
armature.emplace(conn);
}
2019-10-01 07:23:35 +00:00
Actor::Subtype::OverlayMesh::OverlayMesh(Connection& conn) {
name = conn._readStdString();
cskrId = conn._readStdString();
mesh = conn._readPath();
}
2018-12-08 05:18:42 +00:00
Actor::Subtype::Subtype(Connection& conn) {
2019-10-01 07:23:35 +00:00
name = conn._readStdString();
cskrId = conn._readStdString();
mesh = conn._readPath();
conn._readValue(armature);
conn._readVector(overlayMeshes);
2018-12-08 05:18:42 +00:00
}
2018-12-08 05:18:42 +00:00
Actor::Attachment::Attachment(Connection& conn) {
2019-10-01 07:23:35 +00:00
name = conn._readStdString();
cskrId = conn._readStdString();
mesh = conn._readPath();
conn._readValue(armature);
2018-12-08 05:18:42 +00:00
}
Action::Action(Connection& conn) {
2019-10-01 07:23:35 +00:00
name = conn._readStdString();
animId = conn._readStdString();
conn._readValue(interval);
conn._readValue(additive);
conn._readValue(looping);
conn._readVector(frames);
conn._readVector(channels);
conn._readVectorFunc(subtypeAABBs, [&]() {
auto& p = subtypeAABBs.emplace_back();
p.first.read(conn);
p.second.read(conn);
});
2018-12-08 05:18:42 +00:00
}
Action::Channel::Channel(Connection& conn) {
2019-10-01 07:23:35 +00:00
boneName = conn._readStdString();
conn._readValue(attrMask);
conn._readVector(keys, attrMask);
2018-12-08 05:18:42 +00:00
}
Action::Channel::Key::Key(Connection& conn, uint32_t attrMask) {
if (attrMask & 1)
rotation.read(conn);
if (attrMask & 2)
position.read(conn);
if (attrMask & 4)
scale.read(conn);
}
DataStream::DataStream(Connection* parent) : m_parent(parent) {
m_parent->m_dataStreamActive = true;
m_parent->_writeStr("DATABEGIN");
2019-10-01 07:23:35 +00:00
m_parent->_checkReady("unable to open DataStream with blender"sv);
}
2018-12-08 05:18:42 +00:00
void DataStream::close() {
if (m_parent && m_parent->m_lock) {
m_parent->_writeStr("DATAEND");
2019-10-01 07:23:35 +00:00
m_parent->_checkDone("unable to close DataStream with blender"sv);
2018-12-08 05:18:42 +00:00
m_parent->m_dataStreamActive = false;
m_parent->m_lock = false;
}
}
std::vector<std::string> DataStream::getMeshList() {
m_parent->_writeStr("MESHLIST");
std::vector<std::string> retval;
2019-10-01 07:23:35 +00:00
m_parent->_readVector(retval);
2018-12-08 05:18:42 +00:00
return retval;
}
std::vector<std::string> DataStream::getLightList() {
m_parent->_writeStr("LIGHTLIST");
std::vector<std::string> retval;
2019-10-01 07:23:35 +00:00
m_parent->_readVector(retval);
2018-12-08 05:18:42 +00:00
return retval;
}
2018-12-08 05:18:42 +00:00
std::pair<atVec3f, atVec3f> DataStream::getMeshAABB() {
if (m_parent->m_loadedType != BlendType::Mesh && m_parent->m_loadedType != BlendType::Actor)
2020-04-11 22:48:11 +00:00
BlenderLog.report(logvisor::Fatal, FMT_STRING(_SYS_STR("{} is not a MESH or ACTOR blend")),
2019-07-20 04:22:58 +00:00
m_parent->m_loadedBlend.getAbsolutePath());
2018-02-24 06:15:12 +00:00
2018-12-08 05:18:42 +00:00
m_parent->_writeStr("MESHAABB");
2019-10-01 07:23:35 +00:00
m_parent->_checkOk("unable get AABB"sv);
2017-12-29 07:56:31 +00:00
2018-12-08 05:18:42 +00:00
Vector3f minPt(*m_parent);
Vector3f maxPt(*m_parent);
return std::make_pair(minPt.val, maxPt.val);
2017-12-29 07:56:31 +00:00
}
2018-12-08 05:18:42 +00:00
const char* DataStream::MeshOutputModeString(HMDLTopology topology) {
static constexpr std::array<const char*, 2> STRS{"TRIANGLES", "TRISTRIPS"};
2018-12-08 05:18:42 +00:00
return STRS[int(topology)];
2017-12-29 07:56:31 +00:00
}
2019-05-08 03:47:34 +00:00
Mesh DataStream::compileMesh(HMDLTopology topology, int skinSlotCount) {
2018-12-08 05:18:42 +00:00
if (m_parent->getBlendType() != BlendType::Mesh)
2020-04-11 22:48:11 +00:00
BlenderLog.report(logvisor::Fatal, FMT_STRING(_SYS_STR("{} is not a MESH blend")),
2019-07-20 04:22:58 +00:00
m_parent->getBlendPath().getAbsolutePath());
2017-12-29 07:56:31 +00:00
2019-05-08 03:47:34 +00:00
m_parent->_writeStr("MESHCOMPILE");
2019-10-01 07:23:35 +00:00
m_parent->_checkOk("unable to cook mesh"sv);
2015-10-23 00:44:37 +00:00
2019-05-08 03:47:34 +00:00
return Mesh(*m_parent, topology, skinSlotCount);
2015-10-23 00:44:37 +00:00
}
2019-05-08 03:47:34 +00:00
Mesh DataStream::compileMesh(std::string_view name, HMDLTopology topology, int skinSlotCount, bool useLuv) {
2018-12-08 05:18:42 +00:00
if (m_parent->getBlendType() != BlendType::Area)
2020-04-11 22:48:11 +00:00
BlenderLog.report(logvisor::Fatal, FMT_STRING(_SYS_STR("{} is not an AREA blend")),
2019-07-20 04:22:58 +00:00
m_parent->getBlendPath().getAbsolutePath());
2015-10-23 00:44:37 +00:00
2020-04-11 22:48:11 +00:00
m_parent->_writeStr(fmt::format(FMT_STRING("MESHCOMPILENAME {} {}"), name, int(useLuv)));
2019-10-01 07:23:35 +00:00
m_parent->_checkOk("unable to cook mesh"sv);
2015-10-23 00:44:37 +00:00
2019-05-08 03:47:34 +00:00
return Mesh(*m_parent, topology, skinSlotCount, useLuv);
2015-10-23 00:44:37 +00:00
}
2018-12-08 05:18:42 +00:00
ColMesh DataStream::compileColMesh(std::string_view name) {
if (m_parent->getBlendType() != BlendType::Area)
2020-04-11 22:48:11 +00:00
BlenderLog.report(logvisor::Fatal, FMT_STRING(_SYS_STR("{} is not an AREA blend")),
2019-07-20 04:22:58 +00:00
m_parent->getBlendPath().getAbsolutePath());
2015-10-23 00:44:37 +00:00
2020-04-11 22:48:11 +00:00
m_parent->_writeStr(fmt::format(FMT_STRING("MESHCOMPILENAMECOLLISION {}"), name));
2019-10-01 07:23:35 +00:00
m_parent->_checkOk("unable to cook collision mesh"sv);
2015-10-23 00:44:37 +00:00
2018-12-08 05:18:42 +00:00
return ColMesh(*m_parent);
2015-10-23 00:44:37 +00:00
}
2018-12-08 05:18:42 +00:00
std::vector<ColMesh> DataStream::compileColMeshes() {
if (m_parent->getBlendType() != BlendType::ColMesh)
2020-04-11 22:48:11 +00:00
BlenderLog.report(logvisor::Fatal, FMT_STRING(_SYS_STR("{} is not a CMESH blend")),
2019-07-20 04:22:58 +00:00
m_parent->getBlendPath().getAbsolutePath());
2019-07-20 04:22:58 +00:00
m_parent->_writeStr("MESHCOMPILECOLLISIONALL");
2019-10-01 07:23:35 +00:00
m_parent->_checkOk("unable to cook collision meshes"sv);
2015-10-23 00:44:37 +00:00
2018-12-08 05:18:42 +00:00
std::vector<ColMesh> ret;
2019-10-01 07:23:35 +00:00
m_parent->_readVector(ret);
2018-12-08 05:18:42 +00:00
return ret;
2015-10-23 00:44:37 +00:00
}
2018-12-08 05:18:42 +00:00
std::vector<Light> DataStream::compileLights() {
if (m_parent->getBlendType() != BlendType::Area)
2020-04-11 22:48:11 +00:00
BlenderLog.report(logvisor::Fatal, FMT_STRING(_SYS_STR("{} is not an AREA blend")),
2019-07-20 04:22:58 +00:00
m_parent->getBlendPath().getAbsolutePath());
2017-12-29 07:56:31 +00:00
2018-12-08 05:18:42 +00:00
m_parent->_writeStr("LIGHTCOMPILEALL");
2019-10-01 07:23:35 +00:00
m_parent->_checkOk("unable to gather all lights"sv);
2018-12-08 05:18:42 +00:00
std::vector<Light> ret;
2019-10-01 07:23:35 +00:00
m_parent->_readVector(ret);
2018-12-08 05:18:42 +00:00
return ret;
2017-12-29 07:56:31 +00:00
}
2018-12-08 05:18:42 +00:00
PathMesh DataStream::compilePathMesh() {
if (m_parent->getBlendType() != BlendType::PathMesh)
2020-04-11 22:48:11 +00:00
BlenderLog.report(logvisor::Fatal, FMT_STRING(_SYS_STR("{} is not a PATH blend")),
2019-07-20 04:22:58 +00:00
m_parent->getBlendPath().getAbsolutePath());
2017-12-29 07:56:31 +00:00
2018-12-08 05:18:42 +00:00
m_parent->_writeStr("MESHCOMPILEPATH");
2019-10-01 07:23:35 +00:00
m_parent->_checkOk("unable to compile path mesh"sv);
2018-12-08 05:18:42 +00:00
return PathMesh(*m_parent);
}
2018-12-08 05:18:42 +00:00
std::vector<uint8_t> DataStream::compileGuiFrame(int version) {
if (m_parent->getBlendType() != BlendType::Frame)
2020-04-11 22:48:11 +00:00
BlenderLog.report(logvisor::Fatal, FMT_STRING(_SYS_STR("{} is not a FRAME blend")),
2019-07-20 04:22:58 +00:00
m_parent->getBlendPath().getAbsolutePath());
2020-04-11 22:48:11 +00:00
m_parent->_writeStr(fmt::format(FMT_STRING("FRAMECOMPILE {}"), version));
2019-10-01 07:23:35 +00:00
m_parent->_checkOk("unable to compile frame"sv);
2018-12-08 05:18:42 +00:00
while (true) {
2019-10-01 07:23:35 +00:00
std::string readStr = m_parent->_readStdString();
if (readStr == "FRAMEDONE")
2018-12-08 05:18:42 +00:00
break;
SystemStringConv absolute(readStr);
auto& proj = m_parent->getBlendPath().getProject();
SystemString relative;
if (PathRelative(absolute.c_str()))
relative = absolute.sys_str();
else
relative = proj.getProjectRootPath().getProjectRelativeFromAbsolute(absolute.sys_str());
hecl::ProjectPath path(proj.getProjectWorkingPath(), relative);
2020-04-11 22:48:11 +00:00
m_parent->_writeStr(fmt::format(FMT_STRING("{:08X}"), path.parsedHash32()));
2018-12-08 05:18:42 +00:00
}
2019-10-01 07:23:35 +00:00
std::vector<uint8_t> ret;
m_parent->_readVector(ret);
2018-12-08 05:18:42 +00:00
return ret;
}
2018-12-08 05:18:42 +00:00
std::vector<ProjectPath> DataStream::getTextures() {
m_parent->_writeStr("GETTEXTURES");
2019-10-01 07:23:35 +00:00
m_parent->_checkOk("unable to get textures"sv);
2017-10-17 05:51:13 +00:00
2018-12-08 05:18:42 +00:00
std::vector<ProjectPath> texs;
m_parent->_readVectorFunc(texs, [&]() { texs.push_back(m_parent->_readPath()); });
2017-10-17 05:51:13 +00:00
2018-12-08 05:18:42 +00:00
return texs;
2017-10-17 05:51:13 +00:00
}
2018-12-08 05:18:42 +00:00
Actor DataStream::compileActor() {
if (m_parent->getBlendType() != BlendType::Actor)
2020-04-11 22:48:11 +00:00
BlenderLog.report(logvisor::Fatal, FMT_STRING(_SYS_STR("{} is not an ACTOR blend")),
2019-07-20 04:22:58 +00:00
m_parent->getBlendPath().getAbsolutePath());
2018-12-08 05:18:42 +00:00
m_parent->_writeStr("ACTORCOMPILE");
2019-10-01 07:23:35 +00:00
m_parent->_checkOk("unable to compile actor"sv);
2016-08-11 19:51:41 +00:00
2018-12-08 05:18:42 +00:00
return Actor(*m_parent);
}
2016-08-11 19:51:41 +00:00
2018-12-08 05:18:42 +00:00
Actor DataStream::compileActorCharacterOnly() {
if (m_parent->getBlendType() != BlendType::Actor)
2020-04-11 22:48:11 +00:00
BlenderLog.report(logvisor::Fatal, FMT_STRING(_SYS_STR("{} is not an ACTOR blend")),
2019-07-20 04:22:58 +00:00
m_parent->getBlendPath().getAbsolutePath());
2016-08-11 19:51:41 +00:00
2018-12-08 05:18:42 +00:00
m_parent->_writeStr("ACTORCOMPILECHARACTERONLY");
2019-10-01 07:23:35 +00:00
m_parent->_checkOk("unable to compile actor"sv);
2016-08-11 19:51:41 +00:00
2018-12-08 05:18:42 +00:00
return Actor(*m_parent);
2016-08-11 19:51:41 +00:00
}
2019-10-01 07:23:35 +00:00
Armature DataStream::compileArmature() {
if (m_parent->getBlendType() != BlendType::Armature)
2020-04-11 22:48:11 +00:00
BlenderLog.report(logvisor::Fatal, FMT_STRING(_SYS_STR("{} is not an ARMATURE blend")),
2019-10-01 07:23:35 +00:00
m_parent->getBlendPath().getAbsolutePath());
m_parent->_writeStr("ARMATURECOMPILE");
m_parent->_checkOk("unable to compile armature"sv);
return Armature(*m_parent);
}
2018-12-08 05:18:42 +00:00
Action DataStream::compileActionChannelsOnly(std::string_view name) {
if (m_parent->getBlendType() != BlendType::Actor)
2020-04-11 22:48:11 +00:00
BlenderLog.report(logvisor::Fatal, FMT_STRING(_SYS_STR("{} is not an ACTOR blend")),
2019-07-20 04:22:58 +00:00
m_parent->getBlendPath().getAbsolutePath());
2018-02-24 06:15:12 +00:00
2020-04-11 22:48:11 +00:00
m_parent->_writeStr(fmt::format(FMT_STRING("ACTIONCOMPILECHANNELSONLY {}"), name));
2019-10-01 07:23:35 +00:00
m_parent->_checkOk("unable to compile action"sv);
2018-02-24 06:15:12 +00:00
2018-12-08 05:18:42 +00:00
return Action(*m_parent);
2018-02-24 06:15:12 +00:00
}
2018-12-08 05:18:42 +00:00
World DataStream::compileWorld() {
if (m_parent->getBlendType() != BlendType::World)
2020-04-11 22:48:11 +00:00
BlenderLog.report(logvisor::Fatal, FMT_STRING(_SYS_STR("{} is not an WORLD blend")),
2019-07-20 04:22:58 +00:00
m_parent->getBlendPath().getAbsolutePath());
2018-12-08 05:18:42 +00:00
m_parent->_writeStr("WORLDCOMPILE");
2019-10-01 07:23:35 +00:00
m_parent->_checkOk("unable to compile world"sv);
2018-03-28 08:06:34 +00:00
2018-12-08 05:18:42 +00:00
return World(*m_parent);
}
2019-10-01 07:23:35 +00:00
std::vector<std::pair<std::string, std::string>> DataStream::getSubtypeNames() {
2018-12-08 05:18:42 +00:00
if (m_parent->getBlendType() != BlendType::Actor)
2020-04-11 22:48:11 +00:00
BlenderLog.report(logvisor::Fatal, FMT_STRING(_SYS_STR("{} is not an ACTOR blend")),
2019-07-20 04:22:58 +00:00
m_parent->getBlendPath().getAbsolutePath());
2018-12-08 05:18:42 +00:00
m_parent->_writeStr("GETSUBTYPENAMES");
2019-10-01 07:23:35 +00:00
m_parent->_checkOk("unable to get subtypes of actor"sv);
2019-10-01 07:23:35 +00:00
std::vector<std::pair<std::string, std::string>> ret;
m_parent->_readVectorFunc(ret, [&]() {
auto& [name, cskrId] = ret.emplace_back();
name = m_parent->_readStdString();
cskrId = m_parent->_readStdString();
});
2018-12-08 05:18:42 +00:00
return ret;
}
2019-10-01 07:23:35 +00:00
std::vector<std::pair<std::string, std::string>> DataStream::getActionNames() {
2018-12-08 05:18:42 +00:00
if (m_parent->getBlendType() != BlendType::Actor)
2020-04-11 22:48:11 +00:00
BlenderLog.report(logvisor::Fatal, FMT_STRING(_SYS_STR("{} is not an ACTOR blend")),
2019-07-20 04:22:58 +00:00
m_parent->getBlendPath().getAbsolutePath());
2018-12-08 05:18:42 +00:00
m_parent->_writeStr("GETACTIONNAMES");
2019-10-01 07:23:35 +00:00
m_parent->_checkOk("unable to get actions of actor"sv);
2019-10-01 07:23:35 +00:00
std::vector<std::pair<std::string, std::string>> ret;
m_parent->_readVectorFunc(ret, [&]() {
auto& [name, animId] = ret.emplace_back();
name = m_parent->_readStdString();
animId = m_parent->_readStdString();
});
2016-09-30 22:41:01 +00:00
2018-12-08 05:18:42 +00:00
return ret;
2016-09-30 22:41:01 +00:00
}
2019-10-01 07:23:35 +00:00
std::vector<std::pair<std::string, std::string>> DataStream::getSubtypeOverlayNames(std::string_view name) {
2018-12-08 05:18:42 +00:00
if (m_parent->getBlendType() != BlendType::Actor)
2020-04-11 22:48:11 +00:00
BlenderLog.report(logvisor::Fatal, FMT_STRING(_SYS_STR("{} is not an ACTOR blend")),
2019-07-20 04:22:58 +00:00
m_parent->getBlendPath().getAbsolutePath());
2020-04-11 22:48:11 +00:00
m_parent->_writeStr(fmt::format(FMT_STRING("GETSUBTYPEOVERLAYNAMES {}"), name));
2019-10-01 07:23:35 +00:00
m_parent->_checkOk("unable to get subtype overlays of actor"sv);
2019-10-01 07:23:35 +00:00
std::vector<std::pair<std::string, std::string>> ret;
m_parent->_readVectorFunc(ret, [&]() {
auto& [subtypeName, cskrId] = ret.emplace_back();
subtypeName = m_parent->_readStdString();
cskrId = m_parent->_readStdString();
});
2017-10-25 07:46:32 +00:00
2018-12-08 05:18:42 +00:00
return ret;
2017-10-25 07:46:32 +00:00
}
2019-10-01 07:23:35 +00:00
std::vector<std::pair<std::string, std::string>> DataStream::getAttachmentNames() {
2018-12-08 05:18:42 +00:00
if (m_parent->getBlendType() != BlendType::Actor)
2020-04-11 22:48:11 +00:00
BlenderLog.report(logvisor::Fatal, FMT_STRING(_SYS_STR("{} is not an ACTOR blend")),
2019-07-20 04:22:58 +00:00
m_parent->getBlendPath().getAbsolutePath());
2017-10-25 07:46:32 +00:00
2018-12-08 05:18:42 +00:00
m_parent->_writeStr("GETATTACHMENTNAMES");
2019-10-01 07:23:35 +00:00
m_parent->_checkOk("unable to get attachments of actor"sv);
2017-10-25 07:46:32 +00:00
2019-10-01 07:23:35 +00:00
std::vector<std::pair<std::string, std::string>> ret;
m_parent->_readVectorFunc(ret, [&]() {
auto& [name, cskrId] = ret.emplace_back();
name = m_parent->_readStdString();
cskrId = m_parent->_readStdString();
});
2018-12-08 05:18:42 +00:00
return ret;
}
2018-12-08 05:18:42 +00:00
std::unordered_map<std::string, Matrix3f> DataStream::getBoneMatrices(std::string_view name) {
if (name.empty())
return {};
2018-12-08 05:18:42 +00:00
if (m_parent->getBlendType() != BlendType::Actor)
2020-04-11 22:48:11 +00:00
BlenderLog.report(logvisor::Fatal, FMT_STRING(_SYS_STR("{} is not an ACTOR blend")),
2019-07-20 04:22:58 +00:00
m_parent->getBlendPath().getAbsolutePath());
2020-04-11 22:48:11 +00:00
m_parent->_writeStr(fmt::format(FMT_STRING("GETBONEMATRICES {}"), name));
2019-10-01 07:23:35 +00:00
m_parent->_checkOk("unable to get matrices of armature"sv);
2018-12-08 05:18:42 +00:00
std::unordered_map<std::string, Matrix3f> ret;
uint32_t boneCount;
2019-10-01 07:23:35 +00:00
m_parent->_readValue(boneCount);
2018-12-08 05:18:42 +00:00
ret.reserve(boneCount);
for (uint32_t i = 0; i < boneCount; ++i) {
2019-10-01 07:23:35 +00:00
std::string mat_name = m_parent->_readStdString();
2018-12-08 05:18:42 +00:00
Matrix3f matOut;
for (int mat_i = 0; mat_i < 3; ++mat_i) {
for (int mat_j = 0; mat_j < 3; ++mat_j) {
2018-12-08 05:18:42 +00:00
float val;
2019-10-01 07:23:35 +00:00
m_parent->_readValue(val);
matOut[mat_i].simd[mat_j] = val;
2018-12-08 05:18:42 +00:00
}
2019-10-01 07:23:35 +00:00
matOut[mat_i].simd[3] = 0.f;
}
ret.emplace(std::move(mat_name), std::move(matOut));
2018-12-08 05:18:42 +00:00
}
2018-12-08 05:18:42 +00:00
return ret;
}
2018-12-08 05:18:42 +00:00
bool DataStream::renderPvs(std::string_view path, const atVec3f& location) {
if (path.empty())
return false;
2017-02-24 08:27:07 +00:00
2018-12-08 05:18:42 +00:00
if (m_parent->getBlendType() != BlendType::Area)
2020-04-11 22:48:11 +00:00
BlenderLog.report(logvisor::Fatal, FMT_STRING(_SYS_STR("{} is not an AREA blend")),
2019-07-20 04:22:58 +00:00
m_parent->getBlendPath().getAbsolutePath());
2017-02-24 08:27:07 +00:00
2018-12-08 05:18:42 +00:00
athena::simd_floats f(location.simd);
2020-04-11 22:48:11 +00:00
m_parent->_writeStr(fmt::format(FMT_STRING("RENDERPVS {} {} {} {}"), path, f[0], f[1], f[2]));
2019-10-01 07:23:35 +00:00
m_parent->_checkOk("unable to render PVS"sv);
2017-02-24 08:27:07 +00:00
2018-12-08 05:18:42 +00:00
return true;
2017-02-24 08:27:07 +00:00
}
2018-12-08 05:18:42 +00:00
bool DataStream::renderPvsLight(std::string_view path, std::string_view lightName) {
if (path.empty())
return false;
2017-02-24 08:27:07 +00:00
2018-12-08 05:18:42 +00:00
if (m_parent->getBlendType() != BlendType::Area)
2020-04-11 22:48:11 +00:00
BlenderLog.report(logvisor::Fatal, FMT_STRING(_SYS_STR("{} is not an AREA blend")),
2019-07-20 04:22:58 +00:00
m_parent->getBlendPath().getAbsolutePath());
2017-02-24 08:27:07 +00:00
2020-04-11 22:48:11 +00:00
m_parent->_writeStr(fmt::format(FMT_STRING("RENDERPVSLIGHT {} {}"), path, lightName));
2019-10-01 07:23:35 +00:00
m_parent->_checkOk("unable to render PVS light"sv);
2017-02-24 08:27:07 +00:00
2018-12-08 05:18:42 +00:00
return true;
2017-02-24 08:27:07 +00:00
}
2018-12-08 05:18:42 +00:00
MapArea DataStream::compileMapArea() {
if (m_parent->getBlendType() != BlendType::MapArea)
2020-04-11 22:48:11 +00:00
BlenderLog.report(logvisor::Fatal, FMT_STRING(_SYS_STR("{} is not a MAPAREA blend")),
2019-07-20 04:22:58 +00:00
m_parent->getBlendPath().getAbsolutePath());
2018-12-08 05:18:42 +00:00
m_parent->_writeStr("MAPAREACOMPILE");
2019-10-01 07:23:35 +00:00
m_parent->_checkOk("unable to compile map area"sv);
2018-12-08 05:18:42 +00:00
return {*m_parent};
}
2018-12-08 05:18:42 +00:00
MapUniverse DataStream::compileMapUniverse() {
if (m_parent->getBlendType() != BlendType::MapUniverse)
2020-04-11 22:48:11 +00:00
BlenderLog.report(logvisor::Fatal, FMT_STRING(_SYS_STR("{} is not a MAPUNIVERSE blend")),
2019-07-20 04:22:58 +00:00
m_parent->getBlendPath().getAbsolutePath());
2018-12-08 05:18:42 +00:00
m_parent->_writeStr("MAPUNIVERSECOMPILE");
2019-10-01 07:23:35 +00:00
m_parent->_checkOk("unable to compile map universe"sv);
2018-12-08 05:18:42 +00:00
return {*m_parent};
}
2018-12-08 05:18:42 +00:00
void Connection::quitBlender() {
2020-04-10 03:19:33 +00:00
if (m_blenderQuit)
return;
m_blenderQuit = true;
2018-12-08 05:18:42 +00:00
char lineBuf[256];
if (m_lock) {
if (m_pyStreamActive) {
_writeStr("PYEND");
_readStr(lineBuf, sizeof(lineBuf));
m_pyStreamActive = false;
} else if (m_dataStreamActive) {
_writeStr("DATAEND");
_readStr(lineBuf, sizeof(lineBuf));
m_dataStreamActive = false;
}
2018-12-08 05:18:42 +00:00
m_lock = false;
}
_writeStr("QUIT");
_readStr(lineBuf, sizeof(lineBuf));
2019-10-01 07:23:35 +00:00
#ifndef _WIN32
waitpid(m_blenderProc, nullptr, 0);
#endif
2015-05-24 04:51:16 +00:00
}
2015-07-28 02:25:33 +00:00
2018-12-08 05:18:42 +00:00
Connection& Connection::SharedConnection() { return SharedBlenderToken.getBlenderConnection(); }
2016-03-28 22:39:18 +00:00
2018-12-08 05:18:42 +00:00
void Connection::Shutdown() { SharedBlenderToken.shutdown(); }
2016-03-28 22:39:18 +00:00
2018-12-08 05:18:42 +00:00
Connection& Token::getBlenderConnection() {
if (!m_conn)
m_conn = std::make_unique<Connection>(hecl::VerbosityLevel);
return *m_conn;
2017-12-29 07:56:31 +00:00
}
2018-12-08 05:18:42 +00:00
void Token::shutdown() {
if (m_conn) {
m_conn->quitBlender();
m_conn.reset();
if (hecl::VerbosityLevel >= 1)
2020-04-11 22:48:11 +00:00
BlenderLog.report(logvisor::Info, FMT_STRING("Blender Shutdown Successful"));
2018-12-08 05:18:42 +00:00
}
2017-12-29 07:56:31 +00:00
}
Token::~Token() { shutdown(); }
HMDLBuffers::HMDLBuffers(HMDLMeta&& meta, std::size_t vboSz, const std::vector<atUint32>& iboData,
2018-12-08 05:18:42 +00:00
std::vector<Surface>&& surfaces, const Mesh::SkinBanks& skinBanks)
: m_meta(std::move(meta))
, m_vboSz(vboSz)
, m_vboData(new uint8_t[vboSz])
, m_iboSz(iboData.size() * 4)
, m_iboData(new uint8_t[iboData.size() * 4])
, m_surfaces(std::move(surfaces))
, m_skinBanks(skinBanks) {
if (m_iboSz) {
athena::io::MemoryWriter w(m_iboData.get(), m_iboSz);
w.enumerateLittle(iboData);
}
}
} // namespace hecl::blender