layout: restructure into src/ tests/ android/ scripts/ tools/

- extension/src/{port,platform,codepage} -> src/; native_render -> src/host
  (+ dxt, shaders/); libgr2 -> src/gr2; extension/third_party -> third_party
- extension/tests -> tests/port, libgr2/tests -> tests/gr2
- android-native -> android (build.sh, push-client.sh moved in)
- script -> scripts; tools/40250 -> tools/server; oracle -> tools/granny-oracle;
  perf tools -> tools/perf
- all build trees under build/ (native, release, android, port-gate)
- xrender:: CMake aliases -> mt::; port-map ledger impl paths rewritten

No code changes. ctest 15/15, port_gate macos+android PASS, port_map check 0 errors.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
shenlei
2026-09-29 19:08:19 +09:00
co-authored by Claude Opus 5.5
parent 70710477cf
commit a46093104c
2817 changed files with 13728 additions and 13744 deletions
+23
View File
@@ -0,0 +1,23 @@
# port_platform — platform-layer implementations of the mirrored 40250 headers
# (src/platform/<Lib>/<File>.cpp for src/port/<Lib>/<File>.h). Starts as the empty
# skeleton generated by platform_stub.py; see docs/PORT-PLAN.md batch 2A. Added from port/CMakeLists.txt
# so it shares the per-library definitions.
file(GLOB_RECURSE MT_PLATFORM_SOURCES CONFIGURE_DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/*.cpp)
# Same rule as port_logic: without the embedded interpreter there is no ScriptLib to back
# (PORT-PLAN 批次 2P step 4 — Windows).
if(NOT TARGET mtpython)
list(FILTER MT_PLATFORM_SOURCES EXCLUDE REGEX "/ScriptLib/")
endif()
add_library(port_platform STATIC ${MT_PLATFORM_SOURCES})
target_link_libraries(port_platform PUBLIC port_logic PRIVATE mt3p::freetype mt::libgr2)
foreach(src IN LISTS MT_PLATFORM_SOURCES)
mt_port_apply_defines(${src})
endforeach()
# ScriptLib/PythonBoot.cpp is UserInterface's RunMainScript; it sits under ScriptLib only because that is
# the directory dropped when there is no embedded interpreter. Its `#ifdef _DISTRIBUTE` (__DEBUG__ = 0)
# has to see the UserInterface library's definitions, not ScriptLib's.
if(TARGET mtpython)
set_property(SOURCE ${CMAKE_CURRENT_SOURCE_DIR}/ScriptLib/PythonBoot.cpp
PROPERTY COMPILE_DEFINITIONS ${MT_PORT_DEFINES_UserInterface})
endif()
+146
View File
@@ -0,0 +1,146 @@
// Platform implementation of EterBase/CRC32.h (40250 EterBase/CRC32.cpp). GetCRC32/GetCaseCRC32 are the 40250
// loops; CRCTable is the reflected IEEE 802.3 table (polynomial 0xEDB88320), which is what 40250 spells out
// literally (checked entry for entry). The file variants read through a CFileBase-style FILE* handle.
#include "EterBase/StdAfx.h"
#include "EterBase/CRC32.h"
#include <cstdio>
#include <vector>
namespace
{
struct CrcTable
{
DWORD v[256];
CrcTable()
{
for (DWORD n = 0; n < 256; ++n)
{
DWORD c = n;
for (int k = 0; k < 8; ++k)
c = (c & 1) ? (0xEDB88320u ^ (c >> 1)) : (c >> 1);
v[n] = c;
}
}
};
const CrcTable s_crcTable;
}
#define CRCTable (s_crcTable.v)
#define DO1(buf, i) crc = CRCTable[(crc ^ buf[i]) & 0xff] ^ (crc >> 8)
#define DO2(buf, i) DO1(buf, i); DO1(buf, i + 1);
#define DO4(buf, i) DO2(buf, i); DO2(buf, i + 2);
#define DO8(buf, i) DO4(buf, i); DO4(buf, i + 4);
#define DO16(buf, i) DO8(buf, i); DO8(buf, i + 8);
DWORD GetCRC32(const char * buf, size_t len)
{
DWORD crc = 0xffffffff;
if (len >= 16)
{
do
{
DO16(buf, 0);
buf += 16;
len -= 16;
} while (len >= 16);
}
if (len != 0)
{
do
{
DO1(buf, 0);
++buf;
--len;
} while (len > 0);
}
crc ^= 0xffffffff;
return crc;
}
#ifndef UPPER
#define UPPER(c) (((c)>='a' && (c) <= 'z') ? ((c)+('A'-'a')) : (c))
#endif
#define DO1CI(buf, i) crc = CRCTable[(crc ^ UPPER(buf[i])) & 0xff] ^ (crc >> 8)
#define DO2CI(buf, i) DO1CI(buf, i); DO1CI(buf, i + 1);
#define DO4CI(buf, i) DO2CI(buf, i); DO2CI(buf, i + 2);
#define DO8CI(buf, i) DO4CI(buf, i); DO4CI(buf, i + 4);
#define DO16CI(buf, i) DO8CI(buf, i); DO8CI(buf, i + 8);
DWORD GetCaseCRC32(const char * buf, size_t len)
{
DWORD crc = 0xffffffff;
if (16 <= len)
{
do
{
DO16CI(buf, 0);
buf += 16;
len -= 16;
} while (len >= 16);
}
if (0 != len)
{
do
{
DO1CI(buf, 0);
++buf;
--len;
} while (len > 0);
}
crc ^= 0xffffffff;
return crc;
}
DWORD GetHFILECRC32(HANDLE hFile)
{
// 40250 maps the whole file from offset 0 and CRCs it; the stream position is left where it was.
FILE* fp = static_cast<FILE*>(hFile);
const long pos = std::ftell(fp);
std::fseek(fp, 0, SEEK_END);
const long size = std::ftell(fp);
std::fseek(fp, 0, SEEK_SET);
std::vector<char> data(size > 0 ? size : 0);
const size_t got = data.empty() ? 0 : std::fread(data.data(), 1, data.size(), fp);
std::fseek(fp, pos, SEEK_SET);
if (got != data.size() || data.empty())
return 0;
return GetCRC32(data.data(), data.size());
}
DWORD GetFileCRC32(const char* c_szFileName)
{
FILE* fp = std::fopen(c_szFileName, "rb");
if (!fp)
return 0;
DWORD dwRetCRC32=GetHFILECRC32(fp);
std::fclose(fp);
return dwRetCRC32;
}
DWORD GetFileSize(const char* c_szFileName)
{
FILE* fp = std::fopen(c_szFileName, "rb");
if (!fp)
return 0;
std::fseek(fp, 0, SEEK_END);
const long size = std::ftell(fp);
std::fclose(fp);
return size < 0 ? 0 : static_cast<DWORD>(size);
}
+196
View File
@@ -0,0 +1,196 @@
// Platform skeleton for EterBase/Debug.h (40250 EterBase/Debug.cpp), generated by platform_stub.py.
// Every MT_PLATFORM_STUB() body is unimplemented: replace it with the platform implementation. Implemented
// bodies follow the 40250 non-_DEBUG build (batch 2D: Trace*, TraceError to stderr).
#include "EterBase/StdAfx.h"
#include "EterBase/Debug.h"
#include "../PlatformStub.h"
#include "EterBase/Timer.h"
#include "LogBox.h"
#include "TraceErrorObserver.h"
#include <cstdarg>
#include <cstdio>
#include <ctime>
#include <string>
const DWORD DEBUG_STRING_MAX_LEN = 1024;
namespace
{
TraceErrorObserver g_trace_error_observer = nullptr;
}
void SetTraceErrorObserver(TraceErrorObserver observer)
{
g_trace_error_observer = observer;
}
auto SetLogLevel(UINT) -> void
{
MT_PLATFORM_STUB();
}
auto Log(UINT, const char *) -> void
{
MT_PLATFORM_STUB();
}
auto Logn(UINT, const char *) -> void
{
MT_PLATFORM_STUB();
}
auto Logf(UINT, const char *, ...) -> void
{
MT_PLATFORM_STUB();
}
auto Lognf(UINT, const char *, ...) -> void
{
MT_PLATFORM_STUB();
}
void Trace(const char *)
{
// Non-_DEBUG 40250: written only to the log file (OpenLogFile, not implemented yet).
}
void Tracen(const char *)
{
// Non-_DEBUG 40250: written only to the log file (OpenLogFile, not implemented yet).
}
void Tracenf(const char *, ...)
{
// Non-_DEBUG 40250: written only to the log file (OpenLogFile, not implemented yet).
}
void Tracef(const char *, ...)
{
// Non-_DEBUG 40250: written only to the log file (OpenLogFile, not implemented yet).
}
void TraceError(const char* c_szFormat, ...)
{
#ifndef _DISTRIBUTE
char szBuf[DEBUG_STRING_MAX_LEN+2];
strncpy(szBuf, "SYSERR: ", DEBUG_STRING_MAX_LEN);
int len = strlen(szBuf);
va_list args;
va_start(args, c_szFormat);
len = _vsnprintf(szBuf + len, sizeof(szBuf) - (len + 1), c_szFormat, args) + len;
va_end(args);
// PORT: _vsnprintf returns -1 on truncation; 40250 then writes the terminator before the buffer.
if (len < 8)
len = DEBUG_STRING_MAX_LEN;
szBuf[len] = '\n';
szBuf[len + 1] = '\0';
time_t ct = time(0);
struct tm ctm = *localtime(&ct);
fprintf(stderr, "%02d%02d %02d:%02d:%05d :: %s",
ctm.tm_mon + 1,
ctm.tm_mday,
ctm.tm_hour,
ctm.tm_min,
ELTimer_GetMSec() % 60000,
szBuf + 8);
fflush(stderr);
if (g_trace_error_observer)
g_trace_error_observer(szBuf + 8);
#endif
}
auto TraceErrorWithoutEnter(const char *, ...) -> void
{
MT_PLATFORM_STUB();
}
namespace
{
std::string& log_box_message()
{
static std::string message;
return message;
}
}
const std::string& LastLogBoxMessage()
{
return log_box_message();
}
void ClearLogBoxMessage()
{
log_box_message().clear();
}
void LogBox(const char * c_szMsg, const char * c_szCaption, HWND)
{
// 40250 pops a MessageBox on g_PopupHwnd and Tracen()s the text. There is no window here and no
// log file yet, so stderr is the whole of it; the text is also kept for the caller (LogBox.h),
// because it is the only place a script traceback survives.
std::string& message = log_box_message();
message = c_szCaption ? c_szCaption : "LOG";
message += ": ";
message += c_szMsg ? c_szMsg : "";
fprintf(stderr, "%s\n", message.c_str());
fflush(stderr);
Tracen(c_szMsg);
}
void LogBoxf(const char * c_szFormat, ...)
{
va_list args;
va_start(args, c_szFormat);
char szBuf[2048];
_vsnprintf(szBuf, sizeof(szBuf), c_szFormat, args);
va_end(args); // PORT: 40250 leaks the va_list; on this ABI va_end is not optional
// PORT: _vsnprintf does not terminate on truncation.
szBuf[sizeof(szBuf) - 1] = '\0';
LogBox(szBuf);
}
auto LogFile(const char *) -> void
{
MT_PLATFORM_STUB();
}
auto LogFilef(const char *, ...) -> void
{
MT_PLATFORM_STUB();
}
auto OpenConsoleWindow() -> void
{
MT_PLATFORM_STUB();
}
auto CloseConsoleWindow() -> void
{
MT_PLATFORM_STUB();
}
auto SetupLog() -> void
{
MT_PLATFORM_STUB();
}
auto OpenLogFile(bool) -> void
{
MT_PLATFORM_STUB();
}
auto CloseLogFile() -> void
{
MT_PLATFORM_STUB();
}
+189
View File
@@ -0,0 +1,189 @@
// Platform implementation of EterBase/FileBase.h (40250 EterBase/FileBase.cpp). 40250 wraps a Win32 file
// HANDLE; here m_hFile holds a stdio FILE* on every target, with the same open modes (read: existing file,
// shared for reading; write: read/write, created when missing, not truncated) and the same size bookkeeping.
// Names are case-insensitive as on NTFS: 40250's pack/Index says "Etc" for ETC.eix, which a case-sensitive
// file system (Android, Linux) only finds through the fallback below.
#include "EterBase/StdAfx.h"
#include "EterBase/FileBase.h"
#include <cstdio>
#include <string>
#if !defined(_WIN32)
#include <dirent.h>
#include <strings.h>
#endif
// fopen, then (POSIX) resolve each path component case-insensitively when the exact spelling is missing.
static FILE* open_nocase(const char* filename, const char* mode)
{
FILE* fp = std::fopen(filename, mode);
#if !defined(_WIN32)
if (fp || !filename[0])
return fp;
std::string path(filename);
for (char& c : path)
if (c == '\\')
c = '/';
std::string resolved = path[0] == '/' ? "/" : "";
size_t pos = path[0] == '/' ? 1 : 0;
while (pos <= path.size())
{
size_t end = path.find('/', pos);
if (end == std::string::npos)
end = path.size();
const std::string part = path.substr(pos, end - pos);
pos = end + 1;
if (part.empty() || part == "." || part == "..")
{
if (!part.empty())
resolved += part + "/";
continue;
}
DIR* dir = opendir(resolved.empty() ? "." : resolved.c_str());
if (!dir)
return NULL;
std::string match;
while (dirent* e = readdir(dir))
{
if (strcasecmp(e->d_name, part.c_str()) == 0)
{
match = e->d_name;
if (match == part)
break;
}
}
closedir(dir);
if (match.empty())
return NULL;
resolved += match;
if (end != path.size())
resolved += "/";
}
fp = std::fopen(resolved.c_str(), mode);
#endif
return fp;
}
static FILE* file_of(HANDLE h)
{
return static_cast<FILE*>(h);
}
static DWORD stream_size(FILE* fp)
{
const long pos = std::ftell(fp);
std::fseek(fp, 0, SEEK_END);
const long size = std::ftell(fp);
std::fseek(fp, pos, SEEK_SET);
return size < 0 ? 0 : static_cast<DWORD>(size);
}
CFileBase::CFileBase() : m_hFile(NULL), m_dwSize(0)
{
}
CFileBase::~CFileBase()
{
Destroy();
}
char * CFileBase::GetFileName()
{
return m_filename;
}
void CFileBase::Destroy()
{
Close();
m_dwSize = 0;
}
void CFileBase::Close()
{
if (m_hFile)
{
std::fclose(file_of(m_hFile));
m_hFile = NULL;
}
}
BOOL CFileBase::Create(const char* filename, EFileMode mode)
{
Destroy();
strncpy(m_filename, filename, MAX_PATH);
FILE* fp = NULL;
if (mode == FILEMODE_WRITE)
{
// OPEN_ALWAYS + GENERIC_READ|GENERIC_WRITE: open without truncating, create when missing.
fp = open_nocase(filename, "r+b");
if (!fp)
fp = std::fopen(filename, "w+b");
}
else
fp = open_nocase(filename, "rb");
if (fp)
{
m_hFile = fp;
m_dwSize = stream_size(fp);
m_mode = mode;
return true;
}
m_hFile = NULL;
return false;
}
DWORD CFileBase::Size()
{
return (m_dwSize);
}
void CFileBase::SeekCur(DWORD size)
{
// SetFilePointer takes the low DWORD as a signed distance when the high part is NULL.
std::fseek(file_of(m_hFile), static_cast<LONG>(size), SEEK_CUR);
}
void CFileBase::Seek(DWORD offset)
{
if (offset > m_dwSize)
offset = m_dwSize;
std::fseek(file_of(m_hFile), static_cast<long>(offset), SEEK_SET);
}
DWORD CFileBase::GetPosition()
{
return static_cast<DWORD>(std::ftell(file_of(m_hFile)));
}
BOOL CFileBase::Write(const void* src, int bytes)
{
FILE* fp = file_of(m_hFile);
if (std::fwrite(src, 1, bytes, fp) != static_cast<size_t>(bytes))
return false;
std::fflush(fp);
m_dwSize = stream_size(fp);
return true;
}
BOOL CFileBase::Read(void* dest, int bytes)
{
// ReadFile succeeds on a short read (end of file); only an I/O error fails.
FILE* fp = file_of(m_hFile);
std::fread(dest, 1, bytes, fp);
return !std::ferror(fp);
}
BOOL CFileBase::IsNull()
{
return !m_hFile ? true : false;
}
+107
View File
@@ -0,0 +1,107 @@
// Platform implementation of EterBase/FileDir.h (40250 EterBase/FileDir.cpp): the 40250 code as is, over the
// FindFirstFile/FindNextFile/FindClose of common/Win32Crt.h.
#include "EterBase/StdAfx.h"
#include "EterBase/FileDir.h"
#include <string>
CDir::CDir()
{
Initialize();
}
CDir::~CDir()
{
Destroy();
}
void CDir::Destroy()
{
if (m_hFind)
FindClose(m_hFind);
Initialize();
}
bool CDir::Create(const char * c_szFilter, const char* c_szPath, BOOL bCheckedExtension)
{
Destroy();
std::string stPath = c_szPath;
if (stPath.length())
{
char end = stPath[stPath.length() - 1];
if (end != '\\')
stPath+='\\';
}
std::string stQuery;
stQuery += stPath;
stQuery += "*.*";
m_wfd.dwFileAttributes |= FILE_ATTRIBUTE_DIRECTORY;
m_hFind = FindFirstFile(stQuery.c_str(), &m_wfd);
if (m_hFind == INVALID_HANDLE_VALUE)
return true;
do
{
if (*m_wfd.cFileName == '.')
continue;
if (IsFolder())
{
if (!OnFolder(c_szFilter, stPath.c_str(), m_wfd.cFileName))
return false;
}
else
{
const char * c_szExtension = strchr(m_wfd.cFileName, '.');
if (!c_szExtension)
continue;
// NOTE : 임시 변수 - [levites]
// 최종적으로는 무조건 TRUE 형태로 만든다.
// 그전에 전 프로젝트의 CDir을 사용하는 곳에서 Extension을 "wav", "gr2" 이런식으로 넣게끔 한다. - [levites]
if (bCheckedExtension)
{
std::string strFilter = c_szFilter;
int iPos = strFilter.find_first_of(';', 0);
if (iPos > 0)
{
std::string strFirstFilter = std::string(c_szFilter).substr(0, iPos);
std::string strSecondFilter = std::string(c_szFilter).substr(iPos+1, strlen(c_szFilter));
if (0 != strFirstFilter.compare(c_szExtension+1) && 0 != strSecondFilter.compare(c_szExtension+1))
continue;
}
else
{
if (0 != stricmp(c_szExtension+1, c_szFilter))
continue;
}
}
if (!OnFile(stPath.c_str(), m_wfd.cFileName))
return false;
}
}
while (FindNextFile(m_hFind, &m_wfd));
return true;
}
bool CDir::IsFolder()
{
if (m_wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
return true;
return false;
}
void CDir::Initialize()
{
memset(&m_wfd, 0, sizeof(m_wfd));
m_hFind = NULL;
}
+290
View File
@@ -0,0 +1,290 @@
// Platform implementation of EterBase/FileLoader.h: the 40250 EterBase/FileLoader.cpp, which is portable C/stdio.
// Only change: the CP949 lead-byte test casts to signed char (char is unsigned on Android/Linux arm64).
#include "EterBase/StdAfx.h"
#include "EterBase/FileLoader.h"
#include <assert.h>
CMemoryTextFileLoader::CMemoryTextFileLoader()
{
}
CMemoryTextFileLoader::~CMemoryTextFileLoader()
{
}
bool CMemoryTextFileLoader::SplitLineByTab(DWORD dwLine, CTokenVector* pstTokenVector)
{
pstTokenVector->reserve(10);
pstTokenVector->clear();
const std::string & c_rstLine = GetLineString(dwLine);
const int c_iLineLength = c_rstLine.length();
if (0 == c_iLineLength)
return false;
int basePos = 0;
do
{
int beginPos = c_rstLine.find_first_of("\t", basePos);
pstTokenVector->push_back(c_rstLine.substr(basePos, beginPos-basePos));
basePos = beginPos+1;
} while (basePos < c_iLineLength && basePos > 0);
return true;
}
int CMemoryTextFileLoader::SplitLine2(DWORD dwLine, CTokenVector* pstTokenVector, const char * c_szDelimeter)
{
pstTokenVector->reserve(10);
pstTokenVector->clear();
std::string stToken;
const std::string & c_rstLine = GetLineString(dwLine);
DWORD basePos = 0;
do
{
int beginPos = c_rstLine.find_first_not_of(c_szDelimeter, basePos);
if (beginPos < 0)
return -1;
int endPos;
if (c_rstLine[beginPos] == '"')
{
++beginPos;
endPos = c_rstLine.find_first_of("\"", beginPos);
if (endPos < 0)
return -2;
basePos = endPos + 1;
}
else
{
endPos = c_rstLine.find_first_of(c_szDelimeter, beginPos);
basePos = endPos;
}
pstTokenVector->push_back(c_rstLine.substr(beginPos, endPos - beginPos));
// 추가 코드. 맨뒤에 탭이 있는 경우를 체크한다. - [levites]
if (int(c_rstLine.find_first_not_of(c_szDelimeter, basePos)) < 0)
break;
} while (basePos < c_rstLine.length());
return 0;
}
bool CMemoryTextFileLoader::SplitLine(DWORD dwLine, CTokenVector* pstTokenVector, const char * c_szDelimeter)
{
pstTokenVector->reserve(10);
pstTokenVector->clear();
std::string stToken;
const std::string & c_rstLine = GetLineString(dwLine);
DWORD basePos = 0;
do
{
int beginPos = c_rstLine.find_first_not_of(c_szDelimeter, basePos);
if (beginPos < 0)
return false;
int endPos;
if (c_rstLine[beginPos] == '"')
{
++beginPos;
endPos = c_rstLine.find_first_of("\"", beginPos);
if (endPos < 0)
return false;
basePos = endPos + 1;
}
else
{
endPos = c_rstLine.find_first_of(c_szDelimeter, beginPos);
basePos = endPos;
}
pstTokenVector->push_back(c_rstLine.substr(beginPos, endPos - beginPos));
// 추가 코드. 맨뒤에 탭이 있는 경우를 체크한다. - [levites]
if (int(c_rstLine.find_first_not_of(c_szDelimeter, basePos)) < 0)
break;
} while (basePos < c_rstLine.length());
return true;
}
DWORD CMemoryTextFileLoader::GetLineCount()
{
return m_stLineVector.size();
}
bool CMemoryTextFileLoader::CheckLineIndex(DWORD dwLine)
{
if (dwLine >= m_stLineVector.size())
return false;
return true;
}
const std::string & CMemoryTextFileLoader::GetLineString(DWORD dwLine)
{
assert(CheckLineIndex(dwLine));
return m_stLineVector[dwLine];
}
void CMemoryTextFileLoader::Bind(int bufSize, const void* c_pvBuf)
{
m_stLineVector.reserve(128);
m_stLineVector.clear();
const char * c_pcBuf = (const char *)c_pvBuf;
std::string stLine;
int pos = 0;
while (pos < bufSize)
{
const char c = c_pcBuf[pos++];
if ('\n' == c || '\r' == c)
{
if (pos < bufSize)
if ('\n' == c_pcBuf[pos] || '\r' == c_pcBuf[pos])
++pos;
m_stLineVector.push_back(stLine);
stLine = "";
}
else if (static_cast<signed char>(c) < 0) // PORT: Win32 char is signed
{
stLine.append(c_pcBuf + (pos-1), 2);
++pos;
}
else
{
stLine += c;
}
}
m_stLineVector.push_back(stLine);
}
//////////////////////////////////////////////////////////////////////////////////////////////////
int CMemoryFileLoader::GetSize()
{
return m_size;
}
int CMemoryFileLoader::GetPosition()
{
return m_pos;
}
bool CMemoryFileLoader::IsReadableSize(int size)
{
if (m_pos + size > m_size)
return false;
return true;
}
bool CMemoryFileLoader::Read(int size, void* pvDst)
{
if (!IsReadableSize(size))
return false;
memcpy(pvDst, GetCurrentPositionPointer(), size);
m_pos += size;
return true;
}
const char* CMemoryFileLoader::GetCurrentPositionPointer()
{
assert(m_pcBase != NULL);
return (m_pcBase + m_pos);
}
CMemoryFileLoader::CMemoryFileLoader(int size, const void* c_pvMemoryFile)
{
assert(c_pvMemoryFile != NULL);
m_pos = 0;
m_size = size;
m_pcBase = (const char *) c_pvMemoryFile;
}
CMemoryFileLoader::~CMemoryFileLoader()
{
}
//////////////////////////////////////////////////////////////////////////////////////////////////
int CDiskFileLoader::GetSize()
{
return m_size;
}
bool CDiskFileLoader::Read(int size, void* pvDst)
{
assert(m_fp != NULL);
int ret = fread(pvDst, size, 1, m_fp);
if (ret <= 0)
return false;
return true;
}
bool CDiskFileLoader::Open(const char* c_szFileName)
{
Close();
if (!c_szFileName[0])
return false;
m_fp = fopen(c_szFileName, "rb");
if (!m_fp)
return false;
fseek(m_fp, 0, SEEK_END);
m_size = ftell(m_fp);
fseek(m_fp, 0, SEEK_SET);
return true;
}
void CDiskFileLoader::Close()
{
if (m_fp)
fclose(m_fp);
Initialize();
}
void CDiskFileLoader::Initialize()
{
m_fp = NULL;
m_size = 0;
}
CDiskFileLoader::CDiskFileLoader()
{
Initialize();
}
CDiskFileLoader::~CDiskFileLoader()
{
Close();
}
+31
View File
@@ -0,0 +1,31 @@
#pragma once
// PORT: the player's frame-rate setting (system option dialog, app.Get/SetFrameRateMode), shared between
// the script thread and the host's render loop (src/host/main.cpp), which paces frames by it and
// saves it. 40250 has no counterpart: the PC client ran at the monitor's rate.
#include <atomic>
namespace MtFrameRate {
enum EMode {
MODE_SAVER = 0, // 30 fps
MODE_STANDARD = 1, // 60 fps, 30 after a while without input
MODE_HIGH = 2, // the display's highest rate (120 on current phones), 30 after a while without input
MODE_COUNT
};
inline std::atomic<int>& Mode()
{
static std::atomic<int> mode{MODE_STANDARD};
return mode;
}
inline int Get() { return Mode().load(std::memory_order_relaxed); }
inline void Set(int mode)
{
if (mode >= 0 && mode < MODE_COUNT)
Mode().store(mode, std::memory_order_relaxed);
}
} // namespace MtFrameRate
+14
View File
@@ -0,0 +1,14 @@
#pragma once
// The text 40250 would have put in a message box (EterBase/Debug.cpp LogBox/LogBoxf).
//
// LogBox is the client's fatal-error channel: Traceback() in ScriptLib/PythonLauncher.cpp reports every
// failed script line through it, and RunMainScript's callers show it and quit. There is no message box
// on this platform, so the implementation writes the text to stderr and keeps it here for whoever asked
// for the work — that is how a caller learns *why* a script failed, since Traceback() fetches the
// exception (and so clears it) before returning.
#include <string>
// The last LogBox/LogBoxf text, "" when none since the last ClearLogBoxMessage().
const std::string& LastLogBoxMessage();
void ClearLogBoxMessage();
+272
View File
@@ -0,0 +1,272 @@
// Platform implementation of EterBase/MappedFile.h (40250 EterBase/MappedFile.cpp). Everything but Map/Unmap
// is the 40250 code; the view is a POSIX mmap (CreateFileMapping/MapViewOfFile on Windows) of the CFileBase
// stream, aligned down to the allocation granularity exactly as 40250 does.
#include "EterBase/StdAfx.h"
#include "EterBase/MappedFile.h"
#include "EterBase/Debug.h"
#include <cstdio>
#if defined(_WIN32)
#include <io.h>
#else
#include <sys/mman.h>
#include <unistd.h>
#endif
static DWORD allocation_granularity()
{
#if defined(_WIN32)
SYSTEM_INFO SysInfo;
GetSystemInfo(&SysInfo);
return SysInfo.dwAllocationGranularity;
#else
return static_cast<DWORD>(sysconf(_SC_PAGESIZE));
#endif
}
CMappedFile::CMappedFile() :
m_hFM(NULL),
m_lpMapData(NULL),
m_dataOffset(0),
m_mapSize(0),
m_seekPosition(0),
m_pLZObj(NULL),
m_pbBufLinkData(NULL),
m_dwBufLinkSize(0),
m_pbAppendResultDataBlock(NULL),
m_dwAppendResultDataSize(0)
{
}
CMappedFile::~CMappedFile()
{
Destroy();
}
BOOL CMappedFile::Create(const char * filename)
{
Destroy();
return CFileBase::Create(filename, FILEMODE_READ);
}
BOOL CMappedFile::Create(const char * filename, const void** dest, int offset, int size)
{
if (!CMappedFile::Create(filename))
return FALSE;
int ret = Map(dest, offset, size);
return (ret) > 0;
}
LPCVOID CMappedFile::Get()
{
return m_lpData;
}
void CMappedFile::Link(DWORD dwBufSize, const void* c_pvBufData)
{
m_dwBufLinkSize=dwBufSize;
m_pbBufLinkData=(BYTE*)c_pvBufData;
}
void CMappedFile::BindLZObject(CLZObject * pLZObj)
{
assert(m_pLZObj == NULL);
m_pLZObj = pLZObj;
Link(m_pLZObj->GetSize(), m_pLZObj->GetBuffer());
}
void CMappedFile::BindLZObjectWithBufferedSize(CLZObject * pLZObj)
{
assert(m_pLZObj == NULL);
m_pLZObj = pLZObj;
Link(m_pLZObj->GetBufferSize(), m_pLZObj->GetBuffer());
}
BYTE* CMappedFile::AppendDataBlock( const void* pBlock, DWORD dwBlockSize )
{
if( m_pbAppendResultDataBlock )
{
delete []m_pbAppendResultDataBlock;
}
//realloc
m_dwAppendResultDataSize = m_dwBufLinkSize+dwBlockSize;
m_pbAppendResultDataBlock = new BYTE[m_dwAppendResultDataSize];
memcpy(m_pbAppendResultDataBlock, m_pbBufLinkData, m_dwBufLinkSize );
memcpy(m_pbAppendResultDataBlock + m_dwBufLinkSize, pBlock, dwBlockSize );
//redirect
Link(m_dwAppendResultDataSize, m_pbAppendResultDataBlock);
return m_pbAppendResultDataBlock;
}
void CMappedFile::Destroy()
{
if (m_pLZObj)
{
delete m_pLZObj;
m_pLZObj = NULL;
}
if (NULL != m_lpMapData)
{
Unmap(m_lpMapData);
m_lpMapData = NULL;
}
#if defined(_WIN32)
if (NULL != m_hFM)
{
CloseHandle(m_hFM);
m_hFM = NULL;
}
#endif
if( m_pbAppendResultDataBlock )
{
delete []m_pbAppendResultDataBlock;
m_pbAppendResultDataBlock = NULL;
}
m_dwAppendResultDataSize = 0;
m_pbBufLinkData = NULL;
m_dwBufLinkSize = 0;
m_seekPosition = 0;
m_dataOffset = 0;
m_mapSize = 0;
CFileBase::Destroy();
}
int CMappedFile::Seek(DWORD offset, int iSeekType)
{
switch (iSeekType)
{
case SEEK_TYPE_BEGIN:
if (offset > m_dwSize)
offset = m_dwSize;
m_seekPosition = offset;
break;
case SEEK_TYPE_CURRENT:
m_seekPosition = min(m_seekPosition + offset, Size());
break;
case SEEK_TYPE_END:
m_seekPosition = max(0, Size() - offset);
break;
}
return m_seekPosition;
}
int CMappedFile::Map(const void **dest, int offset, int size)
{
m_dataOffset = offset;
if (size == 0)
m_mapSize = m_dwSize;
else
m_mapSize = size;
if (m_dataOffset + m_mapSize > m_dwSize)
return 0;
DWORD dwSysGran = allocation_granularity();
DWORD dwFileMapStart = (m_dataOffset / dwSysGran) * dwSysGran;
DWORD dwMapViewSize = (m_dataOffset % dwSysGran) + m_mapSize;
INT iViewDelta = m_dataOffset - dwFileMapStart;
FILE* fp = static_cast<FILE*>(m_hFile);
#if defined(_WIN32)
m_hFM = CreateFileMapping((HANDLE) _get_osfhandle(_fileno(fp)), NULL, PAGE_READONLY, 0,
m_dataOffset + m_mapSize, NULL);
if (!m_hFM)
{
OutputDebugString("CMappedFile::Map !m_hFM\n");
return 0;
}
m_lpMapData = MapViewOfFile(m_hFM, FILE_MAP_READ, 0, dwFileMapStart, dwMapViewSize);
if (!m_lpMapData)
{
TraceError("CMappedFile::Map !m_lpMapData %lu", GetLastError());
return 0;
}
#else
// A zero-length view (empty file) is a valid 40250 map; mmap rejects length 0.
if (dwMapViewSize == 0)
dwMapViewSize = 1;
void* p = mmap(NULL, dwMapViewSize, PROT_READ, MAP_PRIVATE, fileno(fp), static_cast<off_t>(dwFileMapStart));
if (p == MAP_FAILED)
{
TraceError("CMappedFile::Map !m_lpMapData %s", GetFileName());
return 0;
}
m_lpMapData = p;
#endif
m_lpData = (char*) m_lpMapData + iViewDelta;
*dest = (char*) m_lpData;
m_seekPosition = 0;
Link(m_mapSize, m_lpData);
return (m_mapSize);
}
BYTE * CMappedFile::GetCurrentSeekPoint()
{
return m_pbBufLinkData+m_seekPosition;
}
DWORD CMappedFile::Size()
{
return m_dwBufLinkSize;
}
DWORD CMappedFile::GetPosition()
{
return m_dataOffset;
}
BOOL CMappedFile::Read(void * dest, int bytes)
{
if (m_seekPosition + bytes > Size())
return FALSE;
memcpy(dest, GetCurrentSeekPoint(), bytes);
m_seekPosition += bytes;
return TRUE;
}
DWORD CMappedFile::GetSeekPosition(void)
{
return m_seekPosition;
}
void CMappedFile::Unmap(LPCVOID data)
{
#if defined(_WIN32)
if (!UnmapViewOfFile(data))
TraceError("CMappedFile::Unmap - Error");
#else
// Same view length Map computed from the (unchanged) offset and size.
const DWORD dwSysGran = allocation_granularity();
DWORD dwMapViewSize = (m_dataOffset % dwSysGran) + m_mapSize;
if (dwMapViewSize == 0)
dwMapViewSize = 1;
if (munmap(const_cast<void*>(data), dwMapViewSize) != 0)
TraceError("CMappedFile::Unmap - Error");
#endif
m_lpData = NULL;
}
+124
View File
@@ -0,0 +1,124 @@
#pragma once
// PORT: performance telemetry (40250 has no counterpart). The script thread adds the wall time of the
// sections of CPythonApplication::Process() and of the Python callbacks here; the native host
// (src/host/perf_log.h) reads and clears the totals every sample window. The two threads never run
// at the same time (PythonBoot hands one baton between them), so plain fields are enough.
//
// Nothing is timed until MtPerf::Enabled() is set, so a build without --perf-log pays one branch per
// section.
#include <chrono>
namespace MtPerf
{
enum ESection
{
SECTION_PROCESS, // the whole CPythonApplication::Process()
SECTION_NETWORK, // CPythonNetworkStream + CAccountConnector Process
SECTION_CAMERA, // __UpdateCamera, CResourceManager::Update, OnCameraUpdate, OnMouseUpdate
SECTION_UI_UPDATE, // OnUIUpdate (WindowManager Update -> Python OnUpdate)
SECTION_UPDATE_GAME, // app.UpdateGame, inside UI_UPDATE
SECTION_RENDER_BEGIN, // CCullingManager::Update + the command-list restarts
SECTION_UI_RENDER, // OnUIRender (Python OnRender) + OnMouseRender
SECTION_RENDER_GAME, // app.RenderGame, inside UI_RENDER
SECTION_PYTHON, // outermost C++ -> Python callbacks (includes UPDATE_GAME/RENDER_GAME)
SECTION_SHADOW_RASTER, // RecordingDevice's CPU rasterization of the shadow texture, inside RENDER_GAME
SECTION_COUNT,
};
struct SCounters
{
double ms[SECTION_COUNT] = {};
unsigned calls[SECTION_COUNT] = {};
unsigned pyMissing = 0; // callbacks whose method does not exist
int actorCount = 0; // CPythonCharacterManager alive instances, last Process()
int scriptCpu = -1; // CPU the script thread last ran on (Linux/Android), else -1
};
inline bool& Enabled()
{
static bool s_bEnabled = false;
return s_bEnabled;
}
inline SCounters& Counters()
{
static SCounters s_kCounters;
return s_kCounters;
}
inline int& PythonDepth()
{
static int s_iDepth = 0;
return s_iDepth;
}
class CScope
{
public:
explicit CScope(ESection eSection) : m_eSection(eSection), m_bActive(Enabled())
{
if (m_bActive)
m_kStart = std::chrono::steady_clock::now();
}
~CScope()
{
if (!m_bActive)
return;
SCounters& rkCounters = Counters();
rkCounters.ms[m_eSection] += std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - m_kStart).count();
++rkCounters.calls[m_eSection];
}
private:
ESection m_eSection;
bool m_bActive;
std::chrono::steady_clock::time_point m_kStart;
};
// Times only the outermost Python callback, so nested callbacks are not counted twice.
class CPythonScope
{
public:
CPythonScope() : m_bActive(Enabled() && PythonDepth()++ == 0)
{
if (m_bActive)
m_kStart = std::chrono::steady_clock::now();
}
~CPythonScope()
{
if (!Enabled())
return;
if (PythonDepth() > 0)
--PythonDepth();
if (!m_bActive)
return;
SCounters& rkCounters = Counters();
rkCounters.ms[SECTION_PYTHON] += std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - m_kStart).count();
++rkCounters.calls[SECTION_PYTHON];
}
private:
bool m_bActive;
std::chrono::steady_clock::time_point m_kStart;
};
inline void CountPythonMissing()
{
if (Enabled())
++Counters().pyMissing;
}
// The totals since the last call, which clears them.
inline SCounters Take()
{
SCounters kTaken = Counters();
SCounters& rkCounters = Counters();
const int iActors = rkCounters.actorCount;
const int iCpu = rkCounters.scriptCpu;
rkCounters = SCounters();
rkCounters.actorCount = iActors;
rkCounters.scriptCpu = iCpu;
return kTaken;
}
}
+23
View File
@@ -0,0 +1,23 @@
// Platform implementation of EterBase/TempFile.h (40250 EterBase/TempFile.cpp): the 40250 code as is; the file
// name comes from the platform CreateTempFileName and DeleteFile is the common/Win32Crt.h shim.
#include "EterBase/StdAfx.h"
#include "EterBase/TempFile.h"
#include "EterBase/Utils.h"
#include "EterBase/Debug.h"
CTempFile::~CTempFile()
{
Destroy();
DeleteFile(m_szFileName);
}
CTempFile::CTempFile(const char * c_pszPrefix)
{
strncpy(m_szFileName, CreateTempFileName(c_pszPrefix), MAX_PATH);
if (!Create(m_szFileName, CFileBase::FILEMODE_WRITE))
{
TraceError("CTempFile::CTempFile cannot create temporary file. (filename: %s)", m_szFileName);
return;
}
}
@@ -0,0 +1,8 @@
#pragma once
// Test hook: sees every TraceError line (without the "SYSERR: " prefix) after it is written to stderr.
// The 40250 client only writes these to syserr.txt; tests use it to fail on, e.g., the stream's
// "Unknown packet header" (CPythonNetworkStream::CheckPacket), which otherwise only clears the buffer.
using TraceErrorObserver = void (*)(const char* line);
void SetTraceErrorObserver(TraceErrorObserver observer);
+616
View File
@@ -0,0 +1,616 @@
// Platform implementation of EterBase/Utils.h (40250 EterBase/Utils.cpp). The pure string/path helpers are the
// 40250 bodies verbatim (PORT-PLAN §3); Win32 calls are swapped for POSIX ones where marked PORT.
// stl_lowers lives in EterBase/Stl.cpp.
#include "EterBase/StdAfx.h"
#include "EterBase/Utils.h"
#include "EterBase/Stl.h"
#include <assert.h>
#include <stdarg.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <unistd.h>
#include <algorithm>
#include <filesystem>
// PORT: GetTempPath/GetTempFileName -> $TMPDIR + mkstemp (same "<prefix>XXXX" unique-file contract).
const char * CreateTempFileName(const char * c_pszPrefix)
{
static char szTempName[MAX_PATH + 1];
const char * tmp = getenv("TMPDIR");
snprintf(szTempName, sizeof(szTempName), "%s/%sXXXXXX", tmp && *tmp ? tmp : "/tmp", c_pszPrefix ? c_pszPrefix : "etb");
int fd = mkstemp(szTempName);
if (fd >= 0)
close(fd);
return (szTempName);
}
void GetFilePathNameExtension(const char * c_szFile, int len, std::string * pstPath, std::string * pstName, std::string * pstExt)
{
assert(pstPath != NULL);
assert(pstName != NULL);
assert(pstExt != NULL);
int ext = len;
int pos = len;
while (pos > 0)
{
--pos;
char c = c_szFile[pos];
if (ext == len && c == '.')
{
ext = pos;
break;
}
if (c == '/' || c == '\\')
break;
}
while (pos > 0)
{
--pos;
char c = c_szFile[pos];
if (c == '/' || c == '\\')
break;
}
if (pos)
{
++pos;
pstPath->append(c_szFile, pos);
}
if (ext > pos)
pstName->append(c_szFile + pos, ext - pos);
++ext;
if (len > ext)
pstExt->append(c_szFile + ext, len - ext);
}
void GetFileExtension(const char* c_szFile, int len, std::string* pstExt)
{
int ext = len;
int pos = len;
while (pos > 0)
{
--pos;
char c=c_szFile[pos];
if (ext==len && c=='.')
{
ext=pos;
break;
}
if (c=='/') break;
else if (c=='\\') break;
}
++ext;
if (len>ext)
pstExt->append(c_szFile+ext, len-ext);
}
void GetFileNameParts(const char* c_szFile, int len, char* pszPath, char* pszName, char* pszExt)
{
assert(pszPath!=NULL);
assert(pszName!=NULL);
assert(pszExt!=NULL);
int ext=len;
int pos=len;
while (pos>0)
{
--pos;
char c=c_szFile[pos];
if (ext==len && c=='.')
{
ext=pos;
break;
}
if (c=='/') break;
else if (c=='\\') break;
}
while (pos>0)
{
--pos;
char c=c_szFile[pos];
if (c=='/') break;
else if (c=='\\') break;
}
if (pos)
{
++pos;
for (int i = 0; i < pos; ++i)
{
pszPath[i] = c_szFile[i];
}
pszPath[pos] = '\0';
}
if (ext>pos)
{
int count = 0;
for (int i = pos; i < ext; ++i)
{
pszName[count++] = c_szFile[i];
}
pszName[count] = '\0';
}
++ext;
if (len > ext)
{
int count = 0;
for (int i = ext; i < len; ++i)
{
pszExt[count++] = c_szFile[i];
}
pszExt[count] = '\0';
}
}
// PORT: _ecvt(Index, 256, &dec, &sign) truncated at dec is the unsigned decimal digits of Index.
void GetOldIndexingName(char * szName, int Index)
{
char Temp[512];
snprintf(Temp, sizeof(Temp), "%u", Index < 0 ? 0u - (unsigned) Index : (unsigned) Index);
strcat(szName, Temp);
}
void GetIndexingName(char * szName, DWORD Index)
{
sprintf(szName + strlen(szName), "%u", Index);
}
void GetOnlyFileName(const char * sz_Name, std::string & strFileName)
{
strFileName = "";
int i;
for (i=strlen(sz_Name)-1; i>=0; --i)
{
if ('\\' == sz_Name[i] || '/' == sz_Name[i])
{
++i;
break;
}
}
if (i == -1)
i = 0;
for (size_t j = i; j < strlen(sz_Name); ++j)
{
strFileName += sz_Name[j];
}
strFileName += "\0";
}
void GetOnlyPathName(const char * sz_Name, std::string & OnlyPathName)
{
int i;
for (i = strlen(sz_Name) - 1; i >= 0; --i)
{
if ('\\' == sz_Name[i] || '/' == sz_Name[i])
{
++i;
break;
}
}
if (i == -1)
i = 0;
OnlyPathName.reserve(strlen(sz_Name));
OnlyPathName = "";
for (int j=0; j<i; ++j)
{
OnlyPathName += sz_Name[j];
}
OnlyPathName += "\0";
}
const char * GetOnlyPathName(const char * c_szName)
{
static std::string strPathName;
GetOnlyPathName(c_szName, strPathName);
return strPathName.c_str();
}
bool GetLocalFileName(const char * c_szGlobalPath, const char * c_szFullPathFileName, std::string * pstrLocalFileName)
{
std::string strLocalFileName;
std::string strGlobalPath;
std::string strFullPathFileName;
StringPath(c_szGlobalPath, strGlobalPath);
StringPath(c_szFullPathFileName, strFullPathFileName);
if (strGlobalPath.length() >= strFullPathFileName.length())
return false;
DWORD length = std::min(strGlobalPath.length(), strFullPathFileName.length()); // PORT: min -> std::min
for (DWORD dwPos = 0; dwPos < length; ++dwPos)
{
if (strGlobalPath[dwPos] != strFullPathFileName[dwPos])
return false;
}
*pstrLocalFileName = &c_szFullPathFileName[length];
return true;
}
void GetExceptionPathName(const char * sz_Name, std::string & OnlyFileName)
{
GetOnlyFileName(sz_Name, OnlyFileName);
}
void GetWorkingFolder(std::string & strFileName)
{
char buf[128+1];
if (!getcwd(buf, 128)) // PORT: _getcwd -> getcwd
buf[0] = '\0';
strcat(buf, "/");
strFileName = buf;
}
void StringLowers(char * String)
{
for (DWORD i = 0; i < strlen(String); ++i)
{
String[i] = korean_tolower(String[i]);
}
}
void StringPath(std::string & rString)
{
for (DWORD i = 0; i < rString.length(); ++i)
{
if (rString[i] == '\\')
rString[i] = '/';
else
rString[i] = korean_tolower(rString[i]);
}
}
void StringPath(char * pString)
{
for (DWORD i = 0; i < strlen(pString); ++i)
{
if (pString[i] == '\\')
pString[i] = '/';
else
pString[i] = korean_tolower(pString[i]);
}
}
void StringPath(const char * c_szSrc, char * szDest)
{
for (DWORD i = 0; i < strlen(c_szSrc); ++i)
{
if (c_szSrc[i] == '\\')
szDest[i] = '/';
else
szDest[i] = korean_tolower(c_szSrc[i]);
}
}
void StringPath(const char * c_szSrc, std::string & rString)
{
rString = "";
rString.resize(strlen(c_szSrc));
for (DWORD i = 0; i < strlen(c_szSrc); ++i)
{
if (c_szSrc[i] == '\\')
rString[i] = '/';
else
rString[i] = korean_tolower(c_szSrc[i]);
}
}
#define ishprint(x) ((((x) & 0xE0) > 0x90) || isprint(x))
void PrintAsciiData(const void* void_data, int bytes)
{
int i, j, k;
const unsigned char* p;
const unsigned char* data;
data = (const unsigned char*) void_data;
fprintf(stdout, "------------------------------------------------------------------\n");
j = bytes;
while (1)
{
k = j >= 16 ? 16 : j;
p = data;
for (i = 0; i < 16; ++i)
{
if (i >= k)
fprintf(stdout, " ");
else
fprintf(stdout, "%02x ", *p);
p++;
}
fprintf(stdout, "| ");
p = data;
for (i = 0; i < k; ++i)
{
if (i >= k)
fprintf(stdout, " ");
else
fprintf(stdout, "%c", ishprint(*p) ? *p : '.');
p++;
}
fprintf(stdout, "\n");
j -= 16;
data += 16;
if (j <= 0)
break;
}
fprintf(stdout, "------------------------------------------------------------------\n");
}
bool IsFile(const char* filename)
{
return access(filename, 0) == 0 ? true : false; // PORT: _access -> access
}
bool IsGlobalFileName(const char * c_szFileName)
{
return strchr(c_szFileName, ':') != NULL;
}
auto MIN(int a, int b) -> int
{
return a < b ? a : b;
}
auto MAX(int a, int b) -> int
{
return a > b ? a : b;
}
auto MINMAX(int min, int value, int max) -> int
{
if (max < min)
return MAX(min, value);
int tv;
tv = (min > value ? min : value);
return (max < tv) ? max : tv;
}
auto fMIN(float a, float b) -> float
{
return a < b ? a : b;
}
auto fMAX(float a, float b) -> float
{
return a > b ? a : b;
}
auto fMINMAX(float min, float value, float max) -> float
{
float tv;
tv = (min > value ? min : value);
return (max < tv) ? max : tv;
}
void MyCreateDirectory(const char* path)
{
if (!path || !*path)
return;
char * dir;
const char * p;
if (strlen(path) >= 3)
{
if (*(path + 1) == ':') // C:, D: drive prefix
path += 3;
}
p = path;
int len = strlen(path) + 1;
dir = new char[len];
while (*p)
{
if (*p == '/' || *p == '\\')
{
memset(dir, 0, len);
strncpy(dir, path, p - path);
mkdir(dir, 0755); // PORT: CreateDirectory(dir, NULL) -> mkdir
}
++p;
}
delete [] dir;
}
// PORT: CDirRemover (CDir walk + DeleteFile/RemoveDirectory) -> std::filesystem::remove_all.
void RemoveAllDirectory(const char * c_szDirectoryName)
{
std::error_code ec;
std::filesystem::remove_all(c_szDirectoryName, ec);
}
bool SplitLine(const char * c_szLine, const char * c_szDelimeter, std::vector<std::string> * pkVec_strToken)
{
pkVec_strToken->reserve(10);
pkVec_strToken->clear();
std::string strLine = c_szLine;
DWORD basePos = 0;
do
{
int beginPos = strLine.find_first_not_of(c_szDelimeter, basePos);
if (beginPos < 0)
return false;
int endPos;
if (strLine[beginPos] == '"')
{
++beginPos;
endPos = strLine.find_first_of("\"", beginPos);
if (endPos < 0)
return false;
basePos = endPos + 1;
}
else
{
endPos = strLine.find_first_of(c_szDelimeter, beginPos);
basePos = endPos;
}
pkVec_strToken->push_back(strLine.substr(beginPos, endPos - beginPos));
} while (basePos < strLine.length());
return true;
}
const char * _getf(const char* c_szFormat, ...)
{
static char szBuf[256];
va_list args;
va_start(args, c_szFormat);
vsnprintf(szBuf, sizeof(szBuf), c_szFormat, args); // PORT: _vsnprintf -> vsnprintf
va_end(args);
return szBuf;
}
PCHAR* CommandLineToArgv( PCHAR CmdLine, int* _argc )
{
PCHAR* argv;
PCHAR _argv;
ULONG len;
ULONG argc;
CHAR a;
ULONG i, j;
BOOL in_QM; // PORT: BOOLEAN/PUCHAR -> BOOL/unsigned char * (not in the platform windows.h)
BOOL in_TEXT;
BOOL in_SPACE;
len = strlen(CmdLine);
i = ((len+2)/2)*sizeof(PVOID) + sizeof(PVOID);
argv = (PCHAR*)malloc( // PORT: GlobalAlloc(GMEM_FIXED, ...) -> malloc
i + (len+2)*sizeof(CHAR));
_argv = (PCHAR)(((unsigned char *)argv)+i);
argc = 0;
argv[argc] = _argv;
in_QM = FALSE;
in_TEXT = FALSE;
in_SPACE = TRUE;
i = 0;
j = 0;
while( (a = CmdLine[i]) ) {
if(in_QM) {
if(a == '\"') {
in_QM = FALSE;
} else {
_argv[j] = a;
j++;
}
} else {
switch(a) {
case '\"':
in_QM = TRUE;
in_TEXT = TRUE;
if(in_SPACE) {
argv[argc] = _argv+j;
argc++;
}
in_SPACE = FALSE;
break;
case ' ':
case '\t':
case '\n':
case '\r':
if(in_TEXT) {
_argv[j] = '\0';
j++;
}
in_TEXT = FALSE;
in_SPACE = TRUE;
break;
default:
in_TEXT = TRUE;
if(in_SPACE) {
argv[argc] = _argv+j;
argc++;
}
_argv[j] = a;
j++;
in_SPACE = FALSE;
break;
}
}
i++;
}
_argv[j] = '\0';
argv[argc] = NULL;
(*_argc) = argc;
return argv;
}
void StringExceptCharacter(std::string * pstrString, const char * c_szCharacter)
{
int icurPos = 0;
int iNextPos = 0;
while((iNextPos = pstrString->find_first_of(c_szCharacter, icurPos)) >= 0)
{
std::string strFront = pstrString->substr(icurPos, iNextPos - icurPos);
std::string strBack = pstrString->substr(iNextPos+1, pstrString->length() - iNextPos - 1);
*pstrString = strFront + strBack;
}
}
// PORT: GetModuleFileName(NULL, ...) -> the platform has no executable-path query; report the working folder.
void GetExcutedFileName(std::string & r_str)
{
GetWorkingFolder(r_str);
}
File diff suppressed because it is too large Load Diff
+85
View File
@@ -0,0 +1,85 @@
// Platform skeleton for EterImageLib/DXTCImage.h (40250 EterImageLib/DXTCImage.cpp), generated by platform_stub.py.
// Every MT_PLATFORM_STUB() body is unimplemented: replace it with the platform implementation.
#include "EterImageLib/StdAfx.h"
#include "EterImageLib/DXTCImage.h"
#include "../PlatformStub.h"
CDXTCImage::CDXTCImage()
{
MT_PLATFORM_STUB();
}
CDXTCImage::~CDXTCImage()
{
MT_PLATFORM_STUB();
}
auto CDXTCImage::Initialize() -> void
{
MT_PLATFORM_STUB();
}
auto CDXTCImage::Clear() -> void
{
MT_PLATFORM_STUB();
}
auto CDXTCImage::LoadFromFile(const char *) -> bool
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<bool>();
}
auto CDXTCImage::LoadFromMemory(const BYTE *) -> bool
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<bool>();
}
auto CDXTCImage::LoadHeaderFromMemory(const BYTE *) -> bool
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<bool>();
}
auto CDXTCImage::Copy(int, BYTE *, long) -> bool
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<bool>();
}
auto CDXTCImage::Decompress(int, DWORD *) -> void
{
MT_PLATFORM_STUB();
}
auto CDXTCImage::DecompressDXT1(int, DWORD *) -> void
{
MT_PLATFORM_STUB();
}
auto CDXTCImage::DecompressDXT3(int, DWORD *) -> void
{
MT_PLATFORM_STUB();
}
auto CDXTCImage::DecompressDXT5(int, DWORD *) -> void
{
MT_PLATFORM_STUB();
}
auto CDXTCImage::DecompressARGB(int, DWORD *) -> void
{
MT_PLATFORM_STUB();
}
auto CDXTCImage::DecodePixelFormat(CHAR *, XDDPIXELFORMAT *) -> void
{
MT_PLATFORM_STUB();
}
auto CDXTCImage::Unextract(BYTE *, int, int, int) -> void
{
MT_PLATFORM_STUB();
}
+25
View File
@@ -0,0 +1,25 @@
#include <il/il.h>
#include "../PlatformStub.h"
void ilInit() { MT_PLATFORM_STUB(); }
void ilShutDown() { MT_PLATFORM_STUB(); }
void ilEnable(ILenum) { MT_PLATFORM_STUB(); }
void ilDisable(ILenum) { MT_PLATFORM_STUB(); }
void ilOriginFunc(ILenum) { MT_PLATFORM_STUB(); }
void ilGenImages(ILsizei count, ILuint* images)
{
MT_PLATFORM_STUB();
for (ILsizei i = 0; i < count; ++i)
images[i] = 0;
}
void ilBindImage(ILuint) { MT_PLATFORM_STUB(); }
void ilDeleteImages(ILsizei, const ILuint*) { MT_PLATFORM_STUB(); }
bool ilLoad(ILenum, const ILstring) { MT_PLATFORM_STUB(); return false; }
bool ilSave(ILenum, const ILstring) { MT_PLATFORM_STUB(); return false; }
int ilGetInteger(ILenum) { MT_PLATFORM_STUB(); return 0; }
bool ilConvertImage(ILenum, ILenum) { MT_PLATFORM_STUB(); return false; }
bool ilTexImage(ILuint, ILuint, ILuint, ILubyte, ILenum, ILenum, void*) { MT_PLATFORM_STUB(); return false; }
ILuint ilCopyPixels(ILuint, ILuint, ILuint, ILuint, ILuint, ILuint, ILenum, ILenum, void*) { MT_PLATFORM_STUB(); return 0; }
void ilSetPixels(ILint, ILint, ILint, ILuint, ILuint, ILuint, ILenum, ILenum, void*) { MT_PLATFORM_STUB(); }
+92
View File
@@ -0,0 +1,92 @@
// Platform skeleton for EterImageLib/Image.h (40250 EterImageLib/Image.cpp), generated by platform_stub.py.
// Every MT_PLATFORM_STUB() body is unimplemented: replace it with the platform implementation.
#include "EterImageLib/StdAfx.h"
#include "EterImageLib/Image.h"
#include "../PlatformStub.h"
CImage::CImage()
{
MT_PLATFORM_STUB();
}
CImage::CImage(CImage &)
{
MT_PLATFORM_STUB();
}
CImage::~CImage()
{
MT_PLATFORM_STUB();
}
auto CImage::Destroy() -> void
{
MT_PLATFORM_STUB();
}
auto CImage::Create(int, int) -> void
{
MT_PLATFORM_STUB();
}
auto CImage::Clear(DWORD) -> void
{
MT_PLATFORM_STUB();
}
auto CImage::GetWidth() const -> int
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<int>();
}
auto CImage::GetHeight() const -> int
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<int>();
}
auto CImage::GetBasePointer() -> DWORD *
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<DWORD *>();
}
auto CImage::GetLinePointer(int) -> DWORD *
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<DWORD *>();
}
auto CImage::PutImage(int, int, CImage *) -> void
{
MT_PLATFORM_STUB();
}
auto CImage::FlipTopToBottom() -> void
{
MT_PLATFORM_STUB();
}
auto CImage::SetFileName(const char *) -> void
{
MT_PLATFORM_STUB();
}
auto CImage::GetFileNameString() -> const std::string &
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<const std::string &>();
}
auto CImage::IsEmpty() const -> bool
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<bool>();
}
auto CImage::Initialize() -> void
{
MT_PLATFORM_STUB();
}
+72
View File
@@ -0,0 +1,72 @@
// Platform skeleton for EterImageLib/TGAImage.h (40250 EterImageLib/TGAImage.cpp), generated by platform_stub.py.
// Every MT_PLATFORM_STUB() body is unimplemented: replace it with the platform implementation.
#include "EterImageLib/StdAfx.h"
#include "EterImageLib/TGAImage.h"
#include "../PlatformStub.h"
CTGAImage::CTGAImage()
{
MT_PLATFORM_STUB();
}
CTGAImage::CTGAImage(CImage &)
{
MT_PLATFORM_STUB();
}
CTGAImage::~CTGAImage()
{
MT_PLATFORM_STUB();
}
auto CTGAImage::Create(int, int) -> void
{
MT_PLATFORM_STUB();
}
auto CTGAImage::LoadFromMemory(int, const BYTE *) -> bool
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<bool>();
}
auto CTGAImage::LoadFromDiskFile(const char *) -> bool
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<bool>();
}
auto CTGAImage::SaveToDiskFile(const char *) -> bool
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<bool>();
}
auto CTGAImage::SetCompressed(bool) -> void
{
MT_PLATFORM_STUB();
}
auto CTGAImage::SetAlphaChannel(bool) -> void
{
MT_PLATFORM_STUB();
}
auto CTGAImage::GetHeader() -> TGA_HEADER &
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<TGA_HEADER &>();
}
auto CTGAImage::GetRawPixelCount(const DWORD *) -> int
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<int>();
}
auto CTGAImage::GetRLEPixelCount(const DWORD *) -> int
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<int>();
}
+72
View File
@@ -0,0 +1,72 @@
#pragma once
// CPU-memory vertex/index buffers behind the D3D8 buffer handles. 40250 fills its buffers through
// Lock/Unlock (CGrannyModel::__LoadVertices, CGrannyModelInstance deform) and the renderer later reads
// them back, so the platform keeps the bytes in memory instead of creating device objects.
#include "EterLib/StdAfx.h"
#include <cstdint>
#include <atomic>
#include <vector>
inline std::atomic<std::uint64_t> mt_next_cpu_buffer_id{1};
struct MtCpuVertexBuffer : IDirect3DVertexBuffer8
{
const std::uint64_t id = mt_next_cpu_buffer_id.fetch_add(1, std::memory_order_relaxed);
std::uint64_t revision = 0;
std::vector<uint8_t> bytes;
DWORD fvf = 0;
HRESULT Lock(UINT offset, UINT size, BYTE** data, DWORD) override
{
if (size_t(offset) + size > bytes.size())
return E_FAIL;
*data = bytes.data() + offset;
return S_OK;
}
HRESULT Unlock() override { ++revision; return S_OK; }
};
struct MtCpuIndexBuffer : IDirect3DIndexBuffer8
{
const std::uint64_t id = mt_next_cpu_buffer_id.fetch_add(1, std::memory_order_relaxed);
std::uint64_t revision = 0;
std::vector<uint8_t> bytes;
D3DFORMAT format = D3DFMT_INDEX16;
HRESULT Lock(UINT offset, UINT size, BYTE** data, DWORD) override
{
if (size_t(offset) + size > bytes.size())
return E_FAIL;
*data = bytes.data() + offset;
return S_OK;
}
HRESULT Unlock() override { ++revision; return S_OK; }
};
// D3DXGetFVFVertexSize.
inline unsigned mt_fvf_vertex_size(DWORD fvf)
{
unsigned size = 0;
switch (fvf & D3DFVF_POSITION_MASK)
{
case D3DFVF_XYZ: size += 12; break;
case D3DFVF_XYZRHW: size += 16; break;
case D3DFVF_XYZB1: size += 16; break;
case D3DFVF_XYZB2: size += 20; break;
case D3DFVF_XYZB3: size += 24; break;
case D3DFVF_XYZB4: size += 28; break;
case D3DFVF_XYZB5: size += 32; break;
}
if (fvf & D3DFVF_NORMAL) size += 12;
if (fvf & D3DFVF_PSIZE) size += 4;
if (fvf & D3DFVF_DIFFUSE) size += 4;
if (fvf & D3DFVF_SPECULAR) size += 4;
const unsigned texCount = (fvf & D3DFVF_TEXCOUNT_MASK) >> D3DFVF_TEXCOUNT_SHIFT;
for (unsigned i = 0; i < texCount; ++i)
{
static const unsigned coordSize[4] = { 8, 12, 16, 4 };
size += coordSize[(fvf >> (16 + i * 2)) & 3];
}
return size;
}
+64
View File
@@ -0,0 +1,64 @@
// Platform skeleton for EterLib/DibBar.h (40250 EterLib/DibBar.cpp), generated by platform_stub.py.
// Every MT_PLATFORM_STUB() body is unimplemented: replace it with the platform implementation.
#include "EterLib/StdAfx.h"
#include "EterLib/DibBar.h"
#include "../PlatformStub.h"
CDibBar::CDibBar()
{
MT_PLATFORM_STUB();
}
CDibBar::~CDibBar()
{
MT_PLATFORM_STUB();
}
auto CDibBar::Create(HDC, DWORD, DWORD) -> bool
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<bool>();
}
auto CDibBar::Invalidate() -> void
{
MT_PLATFORM_STUB();
}
auto CDibBar::SetClipRect(const RECT &) -> void
{
MT_PLATFORM_STUB();
}
auto CDibBar::ClearBar() -> void
{
MT_PLATFORM_STUB();
}
auto CDibBar::Render(int, int) -> void
{
MT_PLATFORM_STUB();
}
auto CDibBar::__NearTextureSize(DWORD) -> DWORD
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<DWORD>();
}
auto CDibBar::__DivideTextureSize(DWORD, DWORD, DWORD *, DWORD *, DWORD *) -> void
{
MT_PLATFORM_STUB();
}
auto CDibBar::__BuildTextureBlock(DWORD, DWORD, DWORD, DWORD, DWORD, DWORD) -> CBlockTexture *
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<CBlockTexture *>();
}
auto CDibBar::__BuildTextureBlockList(DWORD, DWORD, DWORD) -> void
{
MT_PLATFORM_STUB();
}
+72
View File
@@ -0,0 +1,72 @@
// Platform skeleton for EterLib/FileLoaderThread.h (40250 EterLib/FileLoaderThread.cpp), generated by platform_stub.py.
// Every MT_PLATFORM_STUB() body is unimplemented: replace it with the platform implementation.
#include "EterLib/StdAfx.h"
#include "EterLib/FileLoaderThread.h"
#include "../PlatformStub.h"
CFileLoaderThread::CFileLoaderThread()
{
MT_PLATFORM_STUB();
}
CFileLoaderThread::~CFileLoaderThread()
{
MT_PLATFORM_STUB();
}
auto CFileLoaderThread::Create(void *) -> int
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<int>();
}
auto CFileLoaderThread::Request(std::string &) -> void
{
MT_PLATFORM_STUB();
}
auto CFileLoaderThread::Fetch(TData **) -> bool
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<bool>();
}
auto CFileLoaderThread::Shutdown() -> void
{
MT_PLATFORM_STUB();
}
auto CFileLoaderThread::EntryPoint(void *) -> UINT
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<UINT>();
}
auto CFileLoaderThread::Run(void *) -> UINT
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<UINT>();
}
auto CFileLoaderThread::Setup() -> UINT
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<UINT>();
}
auto CFileLoaderThread::Execute(void *) -> UINT
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<UINT>();
}
auto CFileLoaderThread::Destroy() -> void
{
MT_PLATFORM_STUB();
}
auto CFileLoaderThread::Process() -> void
{
MT_PLATFORM_STUB();
}
+62
View File
@@ -0,0 +1,62 @@
// Platform skeleton for EterLib/GrpColor.h (40250 EterLib/GrpColor.cpp), generated by platform_stub.py.
// Every MT_PLATFORM_STUB() body is unimplemented: replace it with the platform implementation.
#include "EterLib/StdAfx.h"
#include "EterLib/GrpColor.h"
#include "../PlatformStub.h"
CGraphicColor::CGraphicColor(const CGraphicColor &)
{
MT_PLATFORM_STUB();
}
CGraphicColor::CGraphicColor(float, float, float, float)
{
MT_PLATFORM_STUB();
}
CGraphicColor::CGraphicColor(DWORD)
{
MT_PLATFORM_STUB();
}
CGraphicColor::CGraphicColor()
{
MT_PLATFORM_STUB();
}
CGraphicColor::~CGraphicColor()
{
MT_PLATFORM_STUB();
}
auto CGraphicColor::Clear() -> void
{
MT_PLATFORM_STUB();
}
auto CGraphicColor::Set(float, float, float, float) -> void
{
MT_PLATFORM_STUB();
}
auto CGraphicColor::Set(const CGraphicColor &) -> void
{
MT_PLATFORM_STUB();
}
auto CGraphicColor::Set(DWORD) -> void
{
MT_PLATFORM_STUB();
}
auto CGraphicColor::Blend(float, const CGraphicColor &, const CGraphicColor &) -> void
{
MT_PLATFORM_STUB();
}
auto CGraphicColor::GetPackValue() const -> DWORD
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<DWORD>();
}
+48
View File
@@ -0,0 +1,48 @@
// Platform skeleton for EterLib/GrpColorInstance.h (40250 EterLib/GrpColorInstance.cpp), generated by platform_stub.py.
// Every MT_PLATFORM_STUB() body is unimplemented: replace it with the platform implementation.
#include "EterLib/StdAfx.h"
#include "EterLib/GrpColorInstance.h"
#include "../PlatformStub.h"
CGraphicColorInstance::CGraphicColorInstance()
{
MT_PLATFORM_STUB();
}
CGraphicColorInstance::~CGraphicColorInstance()
{
MT_PLATFORM_STUB();
}
auto CGraphicColorInstance::Clear() -> void
{
MT_PLATFORM_STUB();
}
auto CGraphicColorInstance::SetColorReference(const CGraphicColor &) -> void
{
MT_PLATFORM_STUB();
}
auto CGraphicColorInstance::BlendColorReference(DWORD, const CGraphicColor &) -> void
{
MT_PLATFORM_STUB();
}
auto CGraphicColorInstance::Update() -> void
{
MT_PLATFORM_STUB();
}
auto CGraphicColorInstance::GetCurrentColorReference() const -> const CGraphicColor &
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<const CGraphicColor &>();
}
auto CGraphicColorInstance::GetCurrentTime() -> DWORD
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<DWORD>();
}
+115
View File
@@ -0,0 +1,115 @@
// 40250 EterLib/GrpDIB.cpp, verbatim. The GDI calls are the FreeType-backed platform/Win32Gdi.cpp.
#include "EterLib/StdAfx.h"
#include "EterLib/GrpDIB.h"
CGraphicDib::CGraphicDib()
{
Initialize();
}
CGraphicDib::~CGraphicDib()
{
Destroy();
}
void CGraphicDib::Initialize()
{
m_hDC=NULL;
m_hBmp=NULL;
m_pvBuf=NULL;
m_width=0;
m_height=0;
}
void CGraphicDib::Destroy()
{
if (m_hBmp) DeleteObject(m_hBmp);
if (m_hDC) DeleteDC(m_hDC);
Initialize();
}
bool CGraphicDib::Create(HDC hDC, int width, int height)
{
Destroy();
m_width = width;
m_height = height;
ZeroMemory(&m_bmi.bmiHeader, sizeof(BITMAPINFOHEADER));
m_bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
m_bmi.bmiHeader.biWidth = m_width;
m_bmi.bmiHeader.biHeight = -m_height;
m_bmi.bmiHeader.biPlanes = 1;
m_bmi.bmiHeader.biBitCount = 32;
m_bmi.bmiHeader.biCompression = BI_RGB;
m_hDC=CreateCompatibleDC(hDC);
if (!m_hDC)
{
assert(!"CGraphicDib::Create CreateCompatibleDC Error");
return false;
}
m_hBmp=CreateDIBSection(m_hDC, &m_bmi, DIB_RGB_COLORS, &m_pvBuf, NULL, 0);
if (!m_hBmp)
{
assert(!"CGraphicDib::Create CreateDIBSection Error");
return false;
}
SelectObject(m_hDC, m_hBmp);
::SetTextColor(m_hDC, RGB(255, 255, 255));
return true;
}
HDC CGraphicDib::GetDCHandle()
{
return m_hDC;
}
void CGraphicDib::SetBkMode(int iBkMode)
{
::SetBkMode(m_hDC, iBkMode);
}
void CGraphicDib::TextOut(int ix, int iy, const char * c_szText)
{
::SetBkColor(m_hDC, 0);
::TextOut(m_hDC, ix, iy, c_szText, strlen(c_szText));
}
void CGraphicDib::Put(HDC hDC, int x, int y)
{
SetDIBitsToDevice(
hDC,
x,
y,
m_width,
m_height,
0,
0,
0,
m_height,
m_pvBuf,
&m_bmi,
DIB_RGB_COLORS
);
}
void* CGraphicDib::GetPointer()
{
return m_pvBuf;
}
int CGraphicDib::GetWidth()
{
return m_width;
}
int CGraphicDib::GetHeight()
{
return m_height;
}
+165
View File
@@ -0,0 +1,165 @@
// Platform skeleton for EterLib/GrpDetector.h (40250 EterLib/GrpDetector.cpp), generated by platform_stub.py.
// Every MT_PLATFORM_STUB() body is unimplemented: replace it with the platform implementation.
#include "EterLib/StdAfx.h"
#include "EterLib/GrpDetector.h"
#include "../PlatformStub.h"
auto D3D_SModeInfo::GetString(std::string *) -> void
{
MT_PLATFORM_STUB();
}
auto D3D_CAdapterDisplayModeList::Build(IDirect3D8 &, D3DFORMAT, UINT) -> void
{
MT_PLATFORM_STUB();
}
auto D3D_CAdapterDisplayModeList::GetDisplayModeNum() -> UINT
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<UINT>();
}
auto D3D_CAdapterDisplayModeList::GetPixelFormatNum() -> UINT
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<UINT>();
}
auto D3D_CAdapterDisplayModeList::GetDisplayModer(UINT) -> const D3DDISPLAYMODE &
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<const D3DDISPLAYMODE &>();
}
auto D3D_CAdapterDisplayModeList::GetPixelFormatr(UINT) -> const D3DFORMAT &
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<const D3DFORMAT &>();
}
auto D3D_CDeviceInfo::Build(IDirect3D8 &, UINT, UINT, D3D_CAdapterDisplayModeList &, PFNCONFIRMDEVICE) -> BOOL
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<BOOL>();
}
auto D3D_CDeviceInfo::Find(UINT, UINT, UINT, BOOL, UINT *) -> BOOL
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<BOOL>();
}
auto D3D_CDeviceInfo::GetD3DModeInfoNum() -> UINT
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<UINT>();
}
auto D3D_CDeviceInfo::GetString(std::string *) -> void
{
MT_PLATFORM_STUB();
}
auto D3D_CDeviceInfo::FindDepthStencilFormat(IDirect3D8 &, UINT, D3DDEVTYPE, D3DFORMAT, D3DFORMAT *) -> BOOL
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<BOOL>();
}
auto D3D_CDeviceInfo::GetD3DModeInfor(UINT) -> D3D_SModeInfo &
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<D3D_SModeInfo &>();
}
auto D3D_CDeviceInfo::GetD3DModeInfop(UINT) -> D3D_SModeInfo *
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<D3D_SModeInfo *>();
}
decltype(D3D_CDeviceInfo::msc_aszD3DDevDesc) D3D_CDeviceInfo::msc_aszD3DDevDesc{};
decltype(D3D_CDeviceInfo::msc_aeD3DDevType) D3D_CDeviceInfo::msc_aeD3DDevType{};
auto D3D_CAdapterInfo::Find(UINT, UINT, UINT, BOOL, UINT *, UINT *) -> BOOL
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<BOOL>();
}
auto D3D_CAdapterInfo::Build(IDirect3D8 &, UINT, PFNCONFIRMDEVICE) -> BOOL
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<BOOL>();
}
auto D3D_CAdapterInfo::GetString(std::string *) -> void
{
MT_PLATFORM_STUB();
}
auto D3D_CAdapterInfo::GetDesktopD3DDisplayModer() -> D3DDISPLAYMODE &
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<D3DDISPLAYMODE &>();
}
auto D3D_CAdapterInfo::GetDesktopD3DDisplayModep() -> D3DDISPLAYMODE *
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<D3DDISPLAYMODE *>();
}
auto D3D_CAdapterInfo::GetD3DDeviceInfop(UINT) -> D3D_CDeviceInfo *
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<D3D_CDeviceInfo *>();
}
auto D3D_CAdapterInfo::GetD3DModeInfop(UINT, UINT) -> D3D_SModeInfo *
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<D3D_SModeInfo *>();
}
D3D_CDisplayModeAutoDetector::D3D_CDisplayModeAutoDetector()
{
MT_PLATFORM_STUB();
}
D3D_CDisplayModeAutoDetector::~D3D_CDisplayModeAutoDetector()
{
MT_PLATFORM_STUB();
}
auto D3D_CDisplayModeAutoDetector::Find(UINT, UINT, UINT, BOOL, UINT *, UINT *, UINT *) -> BOOL
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<BOOL>();
}
auto D3D_CDisplayModeAutoDetector::Build(IDirect3D8 &, PFNCONFIRMDEVICE) -> BOOL
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<BOOL>();
}
auto D3D_CDisplayModeAutoDetector::GetD3DAdapterInfop(UINT) -> D3D_CAdapterInfo *
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<D3D_CAdapterInfo *>();
}
auto D3D_CDisplayModeAutoDetector::GetD3DModeInfop(UINT, UINT, UINT) -> D3D_SModeInfo *
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<D3D_SModeInfo *>();
}
auto D3D_CDisplayModeAutoDetector::GetString(std::string *) -> void
{
MT_PLATFORM_STUB();
}
+363
View File
@@ -0,0 +1,363 @@
// 40250 EterLib/GrpDevice.cpp over the platform's recording device (RecordingDevice.h): there is no
// Direct3D object, adapter detection or window; Create makes the device, CStateManager, the matrix
// stack and the default buffers as 40250 does. The remaining MT_PLATFORM_STUB() bodies (device reset,
// web-browser mode, driver warnings) have no platform counterpart yet.
#include "EterLib/StdAfx.h"
#include "EterLib/GrpDevice.h"
#include "EterLib/StateManager.h"
#include "EterBase/Stl.h"
#include "CpuBuffer.h"
#include "RecordingDevice.h"
#include <cstring>
#include "../PlatformStub.h"
bool GRAPHICS_CAPS_CAN_NOT_DRAW_LINE = false;
bool GRAPHICS_CAPS_CAN_NOT_DRAW_SHADOW = false;
bool GRAPHICS_CAPS_HALF_SIZE_IMAGE = false;
bool GRAPHICS_CAPS_CAN_NOT_TEXTURE_ADDRESS_BORDER = false;
bool GRAPHICS_CAPS_SOFTWARE_TILING = false;
CGraphicDevice::CGraphicDevice()
: m_uBackBufferCount(0)
{
__Initialize();
}
CGraphicDevice::~CGraphicDevice()
{
Destroy();
}
void CGraphicDevice::InitBackBufferCount(UINT uBackBufferCount)
{
m_uBackBufferCount=uBackBufferCount;
}
void CGraphicDevice::Destroy()
{
__DestroyPDTVertexBufferList();
__DestroyDefaultIndexBufferList();
// PORT: no DC, vertex shader objects or D3DX meshes; the stream "shaders" are FVF codes.
ms_ptVS = 0;
ms_pntVS = 0;
ms_pnt2VS = 0;
safe_release(ms_lpd3dMatStack);
safe_release(ms_lpd3dDevice);
if (m_pStateManager)
{
delete m_pStateManager;
m_pStateManager = NULL;
}
__Initialize();
}
int CGraphicDevice::Create(HWND hWnd, int iHres, int iVres, bool Windowed, int /*iBit*/, int iReflashRate)
{
int iRet = CREATE_OK;
Destroy();
ms_iWidth = iHres;
ms_iHeight = iVres;
// PORT: in place of Direct3DCreate8, the display-mode detection and CreateDevice: the recording
// device renders through Godot, which supports DXT and has no refresh-rate or T&L failures.
ms_hWnd = hWnd;
ms_lpd3dDevice = MtCreateRecordingDevice(iHres, iVres);
ms_dwD3DBehavior = D3DCREATE_HARDWARE_VERTEXPROCESSING;
ms_d3dPresentParameter.BackBufferWidth = iHres;
ms_d3dPresentParameter.BackBufferHeight = iVres;
ms_d3dPresentParameter.Windowed = Windowed;
if (FAILED((ms_hLastResult = ms_lpd3dDevice->GetDeviceCaps(&ms_d3dCaps))))
{
Tracenf("IDirect3DDevice.GetDeviceCaps - ERROR %d", ms_hLastResult);
return CREATE_GET_DEVICE_CAPS2;
}
ms_lpd3dDevice->GetViewport(&ms_Viewport);
m_pStateManager = new CStateManager(ms_lpd3dDevice);
D3DXCreateMatrixStack(0, &ms_lpd3dMatStack);
ms_lpd3dMatStack->LoadIdentity();
ms_ptVS = CreatePTStreamVertexShader();
ms_pntVS = CreatePNTStreamVertexShader();
ms_pnt2VS = CreatePNT2StreamVertexShader();
D3DXMatrixIdentity(&ms_matIdentity);
D3DXMatrixIdentity(&ms_matView);
D3DXMatrixIdentity(&ms_matProj);
D3DXMatrixIdentity(&ms_matInverseView);
D3DXMatrixIdentity(&ms_matInverseViewYAxis);
D3DXMatrixIdentity(&ms_matWorld);
D3DXMatrixIdentity(&ms_matWorldView);
D3DXMatrixIdentity(&ms_matScreen0);
D3DXMatrixIdentity(&ms_matScreen1);
D3DXMatrixIdentity(&ms_matScreen2);
ms_matScreen0._11 = 1;
ms_matScreen0._22 = -1;
ms_matScreen1._41 = 1;
ms_matScreen1._42 = 1;
ms_matScreen2._11 = (float) iHres / 2;
ms_matScreen2._22 = (float) iVres / 2;
// PORT: no D3DXCreateSphere/D3DXCreateCylinder (debug collision rendering) and no Clear.
if (!__CreateDefaultIndexBufferList())
return false;
if (!__CreatePDTVertexBufferList())
return false;
DWORD dwTexMemSize = GetAvailableTextureMemory();
if (dwTexMemSize < 64 * 1024 * 1024)
ms_isLowTextureMemory = true;
else
ms_isLowTextureMemory = false;
if (dwTexMemSize > 100 * 1024 * 1024)
ms_isHighTextureMemory = true;
else
ms_isHighTextureMemory = false;
if (ms_d3dCaps.TextureAddressCaps & D3DPTADDRESSCAPS_BORDER)
GRAPHICS_CAPS_CAN_NOT_TEXTURE_ADDRESS_BORDER=false;
else
GRAPHICS_CAPS_CAN_NOT_TEXTURE_ADDRESS_BORDER=true;
// PORT: the SIS/3dfx driver checks have no adapter identifier to test.
return (iRet);
}
auto CGraphicDevice::GetDeviceState() -> EDeviceState
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<EDeviceState>();
}
auto CGraphicDevice::Reset() -> bool
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<bool>();
}
auto CGraphicDevice::EnableWebBrowserMode(const RECT &) -> void
{
MT_PLATFORM_STUB();
}
auto CGraphicDevice::DisableWebBrowserMode() -> void
{
MT_PLATFORM_STUB();
}
auto CGraphicDevice::MoveWebBrowserRect(const RECT &) -> void
{
MT_PLATFORM_STUB();
}
auto CGraphicDevice::ResizeBackBuffer(UINT uWidth, UINT uHeight) -> bool
{
ms_iWidth = uWidth;
ms_iHeight = uHeight;
ms_d3dPresentParameter.BackBufferWidth = uWidth;
ms_d3dPresentParameter.BackBufferHeight = uHeight;
return true;
}
auto CGraphicDevice::RegisterWarningString(UINT, const char *) -> void
{
MT_PLATFORM_STUB();
}
void CGraphicDevice::__Initialize()
{
ms_iD3DAdapterInfo=D3DADAPTER_DEFAULT;
ms_iD3DDevInfo=D3DADAPTER_DEFAULT;
ms_iD3DModeInfo=D3DADAPTER_DEFAULT;
ms_lpd3d = NULL;
ms_lpd3dDevice = NULL;
ms_lpd3dMatStack = NULL;
ms_dwWavingEndTime = 0;
ms_dwFlashingEndTime = 0;
m_pStateManager = NULL;
__InitializeDefaultIndexBufferList();
__InitializePDTVertexBufferList();
}
auto CGraphicDevice::__IsInDriverBlackList(D3D_CAdapterInfo &) -> bool
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<bool>();
}
auto CGraphicDevice::__WarningMessage(HWND, UINT) -> void
{
MT_PLATFORM_STUB();
}
void CGraphicDevice::__InitializeDefaultIndexBufferList()
{
for (UINT i=0; i<DEFAULT_IB_NUM; ++i)
ms_alpd3dDefIB[i]=NULL;
}
void CGraphicDevice::__DestroyDefaultIndexBufferList()
{
for (UINT i=0; i<DEFAULT_IB_NUM; ++i)
if (ms_alpd3dDefIB[i])
{
delete ms_alpd3dDefIB[i]; // PORT: CPU buffer, no Release
ms_alpd3dDefIB[i]=NULL;
}
}
bool CGraphicDevice::__CreateDefaultIndexBufferList()
{
static const WORD c_awLineIndices[2] = { 0, 1, };
static const WORD c_awLineTriIndices[6] = { 0, 1, 0, 2, 1, 2, };
static const WORD c_awLineRectIndices[8] = { 0, 1, 0, 2, 1, 3, 2, 3,};
static const WORD c_awLineCubeIndices[24] = {
0, 1, 0, 2, 1, 3, 2, 3,
0, 4, 1, 5, 2, 6, 3, 7,
4, 5, 4, 6, 5, 7, 6, 7,
};
static const WORD c_awFillTriIndices[3]= { 0, 1, 2, };
static const WORD c_awFillRectIndices[6] = { 0, 2, 1, 2, 3, 1, };
static const WORD c_awFillCubeIndices[36] = {
0, 1, 2, 1, 3, 2,
2, 0, 6, 0, 4, 6,
0, 1, 4, 1, 5, 4,
1, 3, 5, 3, 7, 5,
3, 2, 7, 2, 6, 7,
4, 5, 6, 5, 7, 6,
};
if (!__CreateDefaultIndexBuffer(DEFAULT_IB_LINE, 2, c_awLineIndices))
return false;
if (!__CreateDefaultIndexBuffer(DEFAULT_IB_LINE_TRI, 6, c_awLineTriIndices))
return false;
if (!__CreateDefaultIndexBuffer(DEFAULT_IB_LINE_RECT, 8, c_awLineRectIndices))
return false;
if (!__CreateDefaultIndexBuffer(DEFAULT_IB_LINE_CUBE, 24, c_awLineCubeIndices))
return false;
if (!__CreateDefaultIndexBuffer(DEFAULT_IB_FILL_TRI, 3, c_awFillTriIndices))
return false;
if (!__CreateDefaultIndexBuffer(DEFAULT_IB_FILL_RECT, 6, c_awFillRectIndices))
return false;
if (!__CreateDefaultIndexBuffer(DEFAULT_IB_FILL_CUBE, 36, c_awFillCubeIndices))
return false;
return true;
}
bool CGraphicDevice::__CreateDefaultIndexBuffer(UINT eDefIB, UINT uIdxCount, const WORD* c_awIndices)
{
assert(ms_alpd3dDefIB[eDefIB]==NULL);
// PORT: a CPU buffer in place of CreateIndexBuffer (CpuBuffer.h).
MtCpuIndexBuffer* pIB = new MtCpuIndexBuffer;
pIB->bytes.resize(sizeof(WORD)*uIdxCount);
pIB->format = D3DFMT_INDEX16;
ms_alpd3dDefIB[eDefIB] = pIB;
WORD* dstIndices;
if (FAILED(
ms_alpd3dDefIB[eDefIB]->Lock(0, 0, (BYTE**)&dstIndices, 0)
)) return false;
memcpy(dstIndices, c_awIndices, sizeof(WORD)*uIdxCount);
ms_alpd3dDefIB[eDefIB]->Unlock();
return true;
}
void CGraphicDevice::__InitializePDTVertexBufferList()
{
for (UINT i=0; i<PDT_VERTEXBUFFER_NUM; ++i)
ms_alpd3dPDTVB[i]=NULL;
}
void CGraphicDevice::__DestroyPDTVertexBufferList()
{
for (UINT i=0; i<PDT_VERTEXBUFFER_NUM; ++i)
{
if (ms_alpd3dPDTVB[i])
{
delete ms_alpd3dPDTVB[i]; // PORT: CPU buffer, no Release
ms_alpd3dPDTVB[i]=NULL;
}
}
}
bool CGraphicDevice::__CreatePDTVertexBufferList()
{
for (UINT i=0; i<PDT_VERTEXBUFFER_NUM; ++i)
{
// PORT: a CPU buffer in place of CreateVertexBuffer (CpuBuffer.h).
MtCpuVertexBuffer* pVB = new MtCpuVertexBuffer;
pVB->bytes.resize(sizeof(TPDTVertex)*PDT_VERTEX_NUM);
pVB->fvf = D3DFVF_XYZ|D3DFVF_DIFFUSE|D3DFVF_TEX1;
ms_alpd3dPDTVB[i] = pVB;
}
return true;
}
// PORT: the stream vertex shaders are declarations for the fixed-function pipeline; the recording
// device decodes vertices by FVF, so each returns the FVF matching its declaration. PT keeps its
// texture coordinates in stream 1, which the device does not record: stream 0 is position only.
DWORD CGraphicDevice::CreatePTStreamVertexShader()
{
assert(ms_lpd3dDevice != NULL);
return D3DFVF_XYZ;
}
DWORD CGraphicDevice::CreatePNTStreamVertexShader()
{
assert(ms_lpd3dDevice != NULL);
return D3DFVF_XYZ|D3DFVF_NORMAL|D3DFVF_TEX1;
}
DWORD CGraphicDevice::CreatePNT2StreamVertexShader()
{
assert(ms_lpd3dDevice != NULL);
return D3DFVF_XYZ|D3DFVF_NORMAL|D3DFVF_TEX2;
}
auto CGraphicDevice::CreateDoublePNTStreamVertexShader() -> DWORD
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<DWORD>();
}
// 40250 GrpDevice.cpp:298-306; s_MaxTextureWidth/Height come from D3DCAPS8 in __CheckD3DCaps.
// PORT: 4096 is the texture size every Godot renderer on the target GPUs supports.
static DWORD s_MaxTextureWidth = 4096, s_MaxTextureHeight = 4096;
DWORD GetMaxTextureWidth()
{
return s_MaxTextureWidth;
}
DWORD GetMaxTextureHeight()
{
return s_MaxTextureHeight;
}
@@ -0,0 +1,185 @@
// Platform skeleton for EterLib/GrpExpandedImageInstance.h (40250 EterLib/GrpExpandedImageInstance.cpp), generated by platform_stub.py.
// Every MT_PLATFORM_STUB() body is unimplemented: replace it with the platform implementation.
#include "EterLib/StdAfx.h"
#include "EterLib/GrpExpandedImageInstance.h"
#include "../PlatformStub.h"
#include "EterBase/CRC32.h"
#include "UIRenderCommands.h"
#include <cmath>
auto CGraphicExpandedImageInstance::Type() -> DWORD
{
static DWORD type = GetCRC32("CGraphicExpandedImageInstance", sizeof("CGraphicExpandedImageInstance") - 1);
return type;
}
CGraphicExpandedImageInstance::CGraphicExpandedImageInstance()
{
Initialize();
}
CGraphicExpandedImageInstance::~CGraphicExpandedImageInstance()
{
Destroy();
}
auto CGraphicExpandedImageInstance::Destroy() -> void
{
CGraphicImageInstance::Destroy();
Initialize();
}
auto CGraphicExpandedImageInstance::SetDepth(float depth) -> void
{
m_fDepth = depth;
}
auto CGraphicExpandedImageInstance::SetOrigin() -> void
{
m_v2Origin = D3DXVECTOR2(GetWidth() * 0.5f, GetHeight() * 0.5f);
}
auto CGraphicExpandedImageInstance::SetOrigin(float x, float y) -> void
{
m_v2Origin = D3DXVECTOR2(x, y);
}
auto CGraphicExpandedImageInstance::SetRotation(float rotation) -> void
{
m_fRotation = rotation;
}
auto CGraphicExpandedImageInstance::SetScale(float x, float y) -> void
{
m_v2Scale = D3DXVECTOR2(x, y);
}
// In 40250, the arguments are fractions of the image size (uiToolTip gauges, SetPercentage).
auto CGraphicExpandedImageInstance::SetRenderingRect(float fLeft, float fTop, float fRight, float fBottom) -> void
{
if (IsEmpty())
return;
float fWidth = float(GetWidth());
float fHeight = float(GetHeight());
m_RenderingRect.left = fWidth * fLeft;
m_RenderingRect.top = fHeight * fTop;
m_RenderingRect.right = fWidth * fRight;
m_RenderingRect.bottom = fHeight * fBottom;
}
auto CGraphicExpandedImageInstance::SetRenderingMode(int mode) -> void
{
m_iRenderingMode = mode;
}
auto CGraphicExpandedImageInstance::Initialize() -> void
{
m_fDepth = 0;
m_v2Origin = D3DXVECTOR2(0, 0);
m_v2Scale = D3DXVECTOR2(1, 1);
m_fRotation = 0;
m_RenderingRect = {0, 0, 0, 0};
m_iRenderingMode = RENDERING_MODE_NORMAL;
}
// 40250 GrpExpandedImageInstance.cpp:29-142. The vertex and texture-coordinate arithmetic is
// verbatim; the D3D stream/blend-state calls become one UIRenderCommand with the four vertices.
auto CGraphicExpandedImageInstance::OnRender() -> void
{
CGraphicImage * pImage = m_roImage.GetPointer();
CGraphicTexture * pTexture = pImage->GetTexturePointer();
if (pTexture->GetWidth() <= 0 || pTexture->GetHeight() <= 0)
return;
const RECT& c_rRect = pImage->GetRectReference();
float texReverseWidth = 1.0f / float(pTexture->GetWidth());
float texReverseHeight = 1.0f / float(pTexture->GetHeight());
float su = (c_rRect.left - m_RenderingRect.left) * texReverseWidth;
float sv = (c_rRect.top - m_RenderingRect.top) * texReverseHeight;
float eu = (c_rRect.left + m_RenderingRect.right + (c_rRect.right-c_rRect.left)) * texReverseWidth;
float ev = (c_rRect.top + m_RenderingRect.bottom + (c_rRect.bottom-c_rRect.top)) * texReverseHeight;
float x[4], y[4];
for (int i = 0; i < 4; ++i)
{
x[i] = m_v2Position.x-0.5f;
y[i] = m_v2Position.y-0.5f;
}
if (0.0f == m_fRotation)
{
float fimgWidth = float(pImage->GetWidth()) * m_v2Scale.x;
float fimgHeight = float(pImage->GetHeight()) * m_v2Scale.y;
x[0] -= m_RenderingRect.left;
y[0] -= m_RenderingRect.top;
x[1] += fimgWidth + m_RenderingRect.right;
y[1] -= m_RenderingRect.top;
x[2] -= m_RenderingRect.left;
y[2] += fimgHeight + m_RenderingRect.bottom;
x[3] += fimgWidth + m_RenderingRect.right;
y[3] += fimgHeight + m_RenderingRect.bottom;
// PORT: 40250 flips D3DRS_CULLMODE for a mirrored scale; the Godot canvas has no culling.
}
else
{
float fimgHalfWidth = float(pImage->GetWidth())/2.0f * m_v2Scale.x;
float fimgHalfHeight = float(pImage->GetHeight())/2.0f * m_v2Scale.y;
for (int i = 0; i < 4; ++i)
{
x[i] += m_v2Origin.x;
y[i] += m_v2Origin.y;
}
float fRadian = D3DXToRadian(m_fRotation);
x[0] += (-fimgHalfWidth*cosf(fRadian)) - (-fimgHalfHeight*sinf(fRadian));
y[0] += (-fimgHalfWidth*sinf(fRadian)) + (-fimgHalfHeight*cosf(fRadian));
x[1] += (+fimgHalfWidth*cosf(fRadian)) - (-fimgHalfHeight*sinf(fRadian));
y[1] += (+fimgHalfWidth*sinf(fRadian)) + (-fimgHalfHeight*cosf(fRadian));
x[2] += (-fimgHalfWidth*cosf(fRadian)) - (+fimgHalfHeight*sinf(fRadian));
y[2] += (-fimgHalfWidth*sinf(fRadian)) + (+fimgHalfHeight*cosf(fRadian));
x[3] += (+fimgHalfWidth*cosf(fRadian)) - (+fimgHalfHeight*sinf(fRadian));
y[3] += (+fimgHalfWidth*sinf(fRadian)) + (+fimgHalfHeight*cosf(fRadian));
}
UIRenderAddImage(pTexture, x, y, su, sv, eu, ev, UIRenderColor(m_DiffuseColor), m_iRenderingMode);
}
auto CGraphicExpandedImageInstance::OnSetImagePointer() -> void
{
if (!IsEmpty()) SetOrigin();
}
auto CGraphicExpandedImageInstance::OnIsType(DWORD type) -> BOOL
{
return type == Type() || CGraphicImageInstance::OnIsType(type);
}
auto CGraphicExpandedImageInstance::CreateSystem(UINT) -> void
{
MT_PLATFORM_STUB();
}
auto CGraphicExpandedImageInstance::DestroySystem() -> void
{
MT_PLATFORM_STUB();
}
auto CGraphicExpandedImageInstance::New() -> CGraphicExpandedImageInstance *
{
return new CGraphicExpandedImageInstance();
}
auto CGraphicExpandedImageInstance::Delete(CGraphicExpandedImageInstance *instance) -> void
{
if (!instance) return;
instance->Destroy();
delete instance;
}
decltype(CGraphicExpandedImageInstance::ms_kPool) CGraphicExpandedImageInstance::ms_kPool{};
+386
View File
@@ -0,0 +1,386 @@
// 40250 EterLib/GrpFontTexture.cpp, verbatim over the GDI emulation in platform/Win32Gdi.cpp. The
// A4R4G4B4 page textures are CGraphicImageTexture memory textures the Godot canvas samples.
#include "EterLib/StdAfx.h"
#include "EterLib/GrpText.h"
#include "EterBase/Stl.h"
#include "EterLib/Util.h"
#include "UIRenderCommands.h"
#include <unordered_map>
// PORT: HiDPI glyph pages (UISetFontOversample). With a scale s > 1 the page DIB and texture are
// s times larger and each glyph is drawn with an s-times font into the s-scaled cell, while the
// 40250 metrics (width, height, advance), the packing and therefore the page UVs stay the logical
// 1x values: text layout is unchanged, only the texels get finer.
namespace {
int g_font_oversample = 1;
bool g_font_oversample_latched = false;
// The 1x HFONT a CGraphicFontTexture measures with -> its s-times twin that draws.
std::unordered_map<HFONT, HFONT> g_oversampled_fonts;
int FontOversample()
{
g_font_oversample_latched = true;
return g_font_oversample;
}
} // namespace
void UISetFontOversample(int scale)
{
if (g_font_oversample_latched)
return;
g_font_oversample = scale < 1 ? 1 : (scale > 4 ? 4 : scale);
}
int UIFontOversample()
{
return g_font_oversample;
}
CGraphicFontTexture::CGraphicFontTexture()
{
Initialize();
}
CGraphicFontTexture::~CGraphicFontTexture()
{
Destroy();
}
void CGraphicFontTexture::Initialize()
{
CGraphicTexture::Initialize();
m_hFontOld = NULL;
m_hFont = NULL;
m_isDirty = false;
m_bItalic = false;
}
bool CGraphicFontTexture::IsEmpty() const
{
return m_fontMap.size() == 0;
}
void CGraphicFontTexture::Destroy()
{
HDC hDC = m_dib.GetDCHandle();
if (hDC)
SelectObject(hDC, m_hFontOld);
m_dib.Destroy();
m_lpd3dTexture = NULL;
CGraphicTexture::Destroy();
stl_wipe(m_pFontTextureVector);
m_charInfoMap.clear();
if (m_fontMap.size())
{
TFontMap::iterator i = m_fontMap.begin();
while(i != m_fontMap.end())
{
TFontMap::mapped_type hFont = i->second;
auto hi = g_oversampled_fonts.find(hFont);
if (hi != g_oversampled_fonts.end())
{
DeleteObject((HGDIOBJ)hi->second);
g_oversampled_fonts.erase(hi);
}
DeleteObject((HGDIOBJ)i->second);
++i;
}
m_fontMap.clear();
}
Initialize();
}
bool CGraphicFontTexture::CreateDeviceObjects()
{
return true;
}
void CGraphicFontTexture::DestroyDeviceObjects()
{
}
bool CGraphicFontTexture::Create(const char* c_szFontName, int fontSize, bool bItalic)
{
Destroy();
strncpy(m_fontName, c_szFontName, sizeof(m_fontName)-1);
m_fontSize = fontSize;
m_bItalic = bItalic;
m_x = 0;
m_y = 0;
m_step = 0;
DWORD width = 256,height = 256;
if (GetMaxTextureWidth() > 512)
width = 512;
if (GetMaxTextureHeight() > 512)
height = 512;
const int s = FontOversample();
if (!m_dib.Create(ms_hDC, width * s, height * s))
return false;
HDC hDC = m_dib.GetDCHandle();
m_hFont = GetFont(GetDefaultCodePage());
m_hFontOld=(HFONT)SelectObject(hDC, m_hFont);
SetTextColor(hDC, RGB(255, 255, 255));
SetBkColor(hDC, 0);
if (!AppendTexture())
return false;
return true;
}
HFONT CGraphicFontTexture::GetFont(WORD codePage)
{
HFONT hFont = NULL;
TFontMap::iterator i = m_fontMap.find(codePage);
if(i != m_fontMap.end())
{
hFont = i->second;
}
else
{
LOGFONT logFont;
memset(&logFont, 0, sizeof(LOGFONT));
logFont.lfHeight = m_fontSize;
logFont.lfEscapement = 0;
logFont.lfOrientation = 0;
logFont.lfWeight = FW_NORMAL;
logFont.lfItalic = (BYTE) m_bItalic;
logFont.lfUnderline = FALSE;
logFont.lfStrikeOut = FALSE;
logFont.lfCharSet = GetCharsetFromCodePage(codePage);
logFont.lfOutPrecision = OUT_DEFAULT_PRECIS;
logFont.lfClipPrecision = CLIP_DEFAULT_PRECIS;
logFont.lfQuality = ANTIALIASED_QUALITY;
logFont.lfPitchAndFamily = DEFAULT_PITCH;
//Tracenf("font: %s", GetFontFaceFromCodePage(codePage));
strcpy(logFont.lfFaceName, m_fontName); //GetFontFaceFromCodePage(codePage));
//strcpy(logFont.lfFaceName, GetFontFaceFromCodePage(codePage));
hFont = CreateFontIndirect(&logFont);
m_fontMap.insert(TFontMap::value_type(codePage, hFont));
if (const int s = FontOversample(); s > 1 && hFont)
{
logFont.lfHeight = m_fontSize * s;
if (HFONT hHiFont = CreateFontIndirect(&logFont))
g_oversampled_fonts[hFont] = hHiFont;
}
}
return hFont;
}
bool CGraphicFontTexture::AppendTexture()
{
CGraphicImageTexture * pNewTexture = new CGraphicImageTexture;
if (!pNewTexture->Create(m_dib.GetWidth(), m_dib.GetHeight(), D3DFMT_A4R4G4B4))
{
delete pNewTexture;
return false;
}
m_pFontTextureVector.push_back(pNewTexture);
return true;
}
bool CGraphicFontTexture::UpdateTexture()
{
if(!m_isDirty)
return true;
m_isDirty = false;
CGraphicImageTexture * pFontTexture = m_pFontTextureVector.back();
if (!pFontTexture)
return false;
WORD* pwDst;
int pitch;
if (!pFontTexture->Lock(&pitch, (void**)&pwDst))
return false;
pitch /= 2;
int width = m_dib.GetWidth();
int height = m_dib.GetHeight();
DWORD * pdwSrc = (DWORD*)m_dib.GetPointer();
for (int y = 0; y < height; ++y, pwDst += pitch, pdwSrc += width)
for (int x = 0; x < width; ++x)
pwDst[x]=pdwSrc[x];
pFontTexture->Unlock();
return true;
}
CGraphicFontTexture::TCharacterInfomation* CGraphicFontTexture::GetCharacterInfomation(WORD codePage, wchar_t keyValue)
{
TCharacterKey code(codePage, keyValue);
TCharacterInfomationMap::iterator f = m_charInfoMap.find(code);
if (m_charInfoMap.end() == f)
{
return UpdateCharacterInfomation(code);
}
else
{
return &f->second;
}
}
CGraphicFontTexture::TCharacterInfomation* CGraphicFontTexture::UpdateCharacterInfomation(TCharacterKey code)
{
HDC hDC = m_dib.GetDCHandle();
HFONT hFont = GetFont(code.first);
SelectObject(hDC, hFont);
wchar_t keyValue = code.second;
if (keyValue == 0x08)
keyValue = L' '; // 탭은 공백으로 바꾼다 (아랍 출력시 탭 사용: NAME:\tTEXT -> TEXT\t:NAME 로 전환됨 )
ABCFLOAT stABC;
SIZE size;
if (!GetTextExtentPoint32W(hDC, &keyValue, 1, &size) || !GetCharABCWidthsFloatW(hDC, keyValue, keyValue, &stABC))
return NULL;
size.cx = stABC.abcfB;
if( stABC.abcfA > 0.0f )
size.cx += ceilf(stABC.abcfA);
if( stABC.abcfC > 0.0f )
size.cx += ceilf(stABC.abcfC);
size.cx++;
LONG lAdvance = ceilf( stABC.abcfA + stABC.abcfB + stABC.abcfC );
const int s = FontOversample();
int width = m_dib.GetWidth() / s;
int height = m_dib.GetHeight() / s;
if (m_x + size.cx >= (width - 1))
{
m_y += (m_step + 1);
m_step = 0;
m_x = 0;
if (m_y + size.cy >= (height - 1))
{
if (!UpdateTexture())
{
return NULL;
}
if (!AppendTexture())
return NULL;
m_y = 0;
}
}
auto hi = s > 1 ? g_oversampled_fonts.find(hFont) : g_oversampled_fonts.end();
if (hi != g_oversampled_fonts.end())
{
// Draw with the s-times font into the s-scaled cell and keep its anti-aliasing as
// A4R4G4B4 white with coverage alpha (1x keeps 40250's bilevel threshold below).
SelectObject(hDC, hi->second);
TextOutW(hDC, m_x * s, m_y * s, &keyValue, 1);
SelectObject(hDC, hFont);
const int nDIBWidth = m_dib.GetWidth();
DWORD* pdwRow = (DWORD*)m_dib.GetPointer() + nDIBWidth * (m_y * s) + m_x * s;
for (int y = 0; y < size.cy * s; ++y, pdwRow += nDIBWidth)
for (int x = 0; x < size.cx * s; ++x)
{
const DWORD alpha = ((pdwRow[x] & 0xff) * 15 + 127) / 255;
pdwRow[x] = alpha ? ((alpha << 12) | 0x0fff) : 0;
}
}
else
{
TextOutW(hDC, m_x, m_y, &keyValue, 1);
int nChrX;
int nChrY;
int nChrWidth = size.cx;
int nChrHeight = size.cy;
int nDIBWidth = m_dib.GetWidth();
DWORD*pdwDIBData=(DWORD*)m_dib.GetPointer();
DWORD*pdwDIBBase=pdwDIBData+nDIBWidth*m_y+m_x;
DWORD*pdwDIBRow;
pdwDIBRow=pdwDIBBase;
for (nChrY=0; nChrY<nChrHeight; ++nChrY, pdwDIBRow+=nDIBWidth)
{
for (nChrX=0; nChrX<nChrWidth; ++nChrX)
{
pdwDIBRow[nChrX]=(pdwDIBRow[nChrX]&0xff) ? 0xffff : 0;
}
}
}
float rhwidth = 1.0f / float(width);
float rhheight = 1.0f / float(height);
TCharacterInfomation& rNewCharInfo = m_charInfoMap[code];
rNewCharInfo.index = static_cast<short>(m_pFontTextureVector.size() - 1);
rNewCharInfo.width = size.cx;
rNewCharInfo.height = size.cy;
rNewCharInfo.left = float(m_x) * rhwidth;
rNewCharInfo.top = float(m_y) * rhheight;
rNewCharInfo.right = float(m_x+size.cx) * rhwidth;
rNewCharInfo.bottom = float(m_y+size.cy) * rhheight;
rNewCharInfo.advance = (float) lAdvance;
m_x += size.cx;
if (m_step < size.cy)
m_step = size.cy;
m_isDirty = true;
return &rNewCharInfo;
}
bool CGraphicFontTexture::CheckTextureIndex(DWORD dwTexture)
{
if (dwTexture >= m_pFontTextureVector.size())
return false;
return true;
}
void CGraphicFontTexture::SelectTexture(DWORD dwTexture)
{
assert(CheckTextureIndex(dwTexture));
m_lpd3dTexture = m_pFontTextureVector[dwTexture]->GetD3DTexture();
}
+82
View File
@@ -0,0 +1,82 @@
// Platform skeleton for EterLib/GrpImage.h (40250 EterLib/GrpImage.cpp), generated by platform_stub.py.
// Every MT_PLATFORM_STUB() body is unimplemented: replace it with the platform implementation.
#include "EterLib/StdAfx.h"
#include "EterLib/GrpImage.h"
#include "../PlatformStub.h"
auto CGraphicImage::Type() -> TType
{
static TType type = StringToType("CGraphicImage");
return type;
}
CGraphicImage::CGraphicImage(const char * c_szFileName, DWORD dwFilter) : CResource(c_szFileName), m_dwFilter(dwFilter) // initializers as in 40250
{
m_rect = {0, 0, 0, 0};
}
CGraphicImage::~CGraphicImage()
{
MT_PLATFORM_STUB();
}
auto CGraphicImage::CreateDeviceObjects() -> bool
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<bool>();
}
auto CGraphicImage::DestroyDeviceObjects() -> void
{
MT_PLATFORM_STUB();
}
auto CGraphicImage::GetWidth() const -> int
{
return m_rect.right - m_rect.left;
}
auto CGraphicImage::GetHeight() const -> int
{
return m_rect.bottom - m_rect.top;
}
auto CGraphicImage::GetRectReference() const -> const RECT &
{
return m_rect;
}
auto CGraphicImage::GetTextureReference() const -> const CGraphicTexture &
{
return m_imageTexture;
}
auto CGraphicImage::GetTexturePointer() -> CGraphicTexture *
{
return &m_imageTexture;
}
auto CGraphicImage::OnLoad(int size, const void *data) -> bool
{
m_imageTexture.SetFileName(GetFileName());
if (!m_imageTexture.CreateFromMemoryFile(size, data, D3DFMT_UNKNOWN, m_dwFilter)) return false;
m_rect = {0, 0, m_imageTexture.GetWidth(), m_imageTexture.GetHeight()};
return true;
}
auto CGraphicImage::OnClear() -> void
{
m_imageTexture.Destroy();
m_rect = {0, 0, 0, 0};
}
auto CGraphicImage::OnIsEmpty() const -> bool
{
return m_imageTexture.IsEmpty();
}
auto CGraphicImage::OnIsType(TType type) -> bool
{
return type == Type() || CResource::OnIsType(type);
}
+167
View File
@@ -0,0 +1,167 @@
// Platform skeleton for EterLib/GrpImageInstance.h (40250 EterLib/GrpImageInstance.cpp), generated by platform_stub.py.
// Every MT_PLATFORM_STUB() body is unimplemented: replace it with the platform implementation.
#include "EterLib/StdAfx.h"
#include "EterLib/GrpImageInstance.h"
#include "../PlatformStub.h"
#include "UIRenderCommands.h"
#include "EterBase/CRC32.h"
auto CGraphicImageInstance::Type() -> DWORD
{
static DWORD type = GetCRC32("CGraphicImageInstance", sizeof("CGraphicImageInstance") - 1);
return type;
}
auto CGraphicImageInstance::IsType(DWORD type) -> BOOL
{
return OnIsType(type);
}
CGraphicImageInstance::CGraphicImageInstance()
{
m_DiffuseColor = D3DXCOLOR(1, 1, 1, 1);
m_v2Position = D3DXVECTOR2(0, 0);
}
CGraphicImageInstance::~CGraphicImageInstance()
{
Destroy();
}
// 40250 Destroy(): drop the image reference, then Initialize() (white, at the origin).
auto CGraphicImageInstance::Destroy() -> void
{
m_roImage.Clear();
m_DiffuseColor = D3DXCOLOR(1, 1, 1, 1);
m_v2Position = D3DXVECTOR2(0, 0);
}
auto CGraphicImageInstance::Render() -> void
{
if (!IsEmpty()) OnRender();
}
auto CGraphicImageInstance::SetDiffuseColor(float r, float g, float b, float a) -> void
{
m_DiffuseColor = D3DXCOLOR(r, g, b, a);
}
auto CGraphicImageInstance::SetPosition(float x, float y) -> void
{
m_v2Position = D3DXVECTOR2(x, y);
}
auto CGraphicImageInstance::SetImagePointer(CGraphicImage *image) -> void
{
m_roImage.SetPointer(image);
OnSetImagePointer();
}
auto CGraphicImageInstance::ReloadImagePointer(CGraphicImage *) -> void
{
MT_PLATFORM_STUB();
}
auto CGraphicImageInstance::IsEmpty() const -> bool
{
return m_roImage.IsNull() || m_roImage->IsEmpty();
}
auto CGraphicImageInstance::GetWidth() -> int
{
return IsEmpty() ? 0 : m_roImage->GetWidth();
}
auto CGraphicImageInstance::GetHeight() -> int
{
return IsEmpty() ? 0 : m_roImage->GetHeight();
}
auto CGraphicImageInstance::GetTexturePointer() -> CGraphicTexture *
{
CGraphicImage* pkImage = m_roImage.GetPointer();
return pkImage ? pkImage->GetTexturePointer() : NULL;
}
auto CGraphicImageInstance::GetTextureReference() const -> const CGraphicTexture &
{
return m_roImage->GetTextureReference();
}
auto CGraphicImageInstance::GetGraphicImagePointer() -> CGraphicImage *
{
return m_roImage.GetPointer();
}
auto CGraphicImageInstance::operator==(const CGraphicImageInstance &) const -> bool
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<bool>();
}
auto CGraphicImageInstance::Initialize() -> void
{
MT_PLATFORM_STUB();
}
// 40250 GrpImageInstance.cpp:44-96: the image's rect inside its texture (a .sub shares its parent's)
// becomes the texture coordinates of one quad.
auto CGraphicImageInstance::OnRender() -> void
{
CGraphicImage * pImage = m_roImage.GetPointer();
CGraphicTexture * pTexture = pImage->GetTexturePointer();
if (pTexture->GetWidth() <= 0 || pTexture->GetHeight() <= 0)
return;
float fimgWidth = pImage->GetWidth();
float fimgHeight = pImage->GetHeight();
const RECT& c_rRect = pImage->GetRectReference();
float texReverseWidth = 1.0f / float(pTexture->GetWidth());
float texReverseHeight = 1.0f / float(pTexture->GetHeight());
float su = c_rRect.left * texReverseWidth;
float sv = c_rRect.top * texReverseHeight;
float eu = (c_rRect.left + (c_rRect.right-c_rRect.left)) * texReverseWidth;
float ev = (c_rRect.top + (c_rRect.bottom-c_rRect.top)) * texReverseHeight;
const float x[4] = {m_v2Position.x-0.5f, m_v2Position.x + fimgWidth-0.5f,
m_v2Position.x-0.5f, m_v2Position.x + fimgWidth-0.5f};
const float y[4] = {m_v2Position.y-0.5f, m_v2Position.y-0.5f,
m_v2Position.y + fimgHeight-0.5f, m_v2Position.y + fimgHeight-0.5f};
UIRenderAddImage(pTexture, x, y, su, sv, eu, ev, UIRenderColor(m_DiffuseColor));
}
auto CGraphicImageInstance::OnSetImagePointer() -> void
{
MT_PLATFORM_STUB();
}
auto CGraphicImageInstance::OnIsType(DWORD type) -> BOOL
{
return type == Type();
}
auto CGraphicImageInstance::CreateSystem(UINT) -> void
{
MT_PLATFORM_STUB();
}
auto CGraphicImageInstance::DestroySystem() -> void
{
MT_PLATFORM_STUB();
}
auto CGraphicImageInstance::New() -> CGraphicImageInstance *
{
return new CGraphicImageInstance();
}
auto CGraphicImageInstance::Delete(CGraphicImageInstance *instance) -> void
{
if (!instance) return;
instance->Destroy();
delete instance;
}
decltype(CGraphicImageInstance::ms_kPool) CGraphicImageInstance::ms_kPool{};
+338
View File
@@ -0,0 +1,338 @@
// Platform skeleton for EterLib/GrpImageTexture.h (40250 EterLib/GrpImageTexture.cpp), generated by platform_stub.py.
// Every MT_PLATFORM_STUB() body is unimplemented: replace it with the platform implementation.
#include "EterLib/StdAfx.h"
#include "EterLib/GrpImageTexture.h"
#include "../PlatformStub.h"
#include "UIRenderCommands.h"
#include <cstring>
#include <map>
#include <mutex>
#include <set>
namespace {
unsigned little16(const unsigned char* data) { return data[0] | (unsigned(data[1]) << 8); }
unsigned little32(const unsigned char* data) { return little16(data) | (little16(data + 2) << 16); }
unsigned big16(const unsigned char* data) { return (unsigned(data[0]) << 8) | data[1]; }
unsigned big32(const unsigned char* data) { return (unsigned(data[0]) << 24) | (unsigned(data[1]) << 16) | (unsigned(data[2]) << 8) | data[3]; }
// Walks the JPEG markers to the first SOFn (the frame header holds the size), as D3DX does when it
// sniffs a .jpg; login/loading backgrounds (serverlist.jpg, loading/*.jpg) are JPEGs.
bool jpeg_size(const unsigned char* data, unsigned size, unsigned* width, unsigned* height)
{
if (size < 4 || data[0] != 0xFF || data[1] != 0xD8) return false;
unsigned pos = 2;
while (pos + 4 <= size) {
if (data[pos] != 0xFF) return false;
const unsigned char marker = data[pos + 1];
if (marker == 0xFF) { ++pos; continue; }
if (marker == 0xD8 || marker == 0x01 || (marker >= 0xD0 && marker <= 0xD7)) { pos += 2; continue; }
const unsigned length = big16(data + pos + 2);
if (length < 2) return false;
const bool sof = marker >= 0xC0 && marker <= 0xCF && marker != 0xC4 && marker != 0xC8 && marker != 0xCC;
if (sof) {
if (pos + 9 > size) return false;
*height = big16(data + pos + 5);
*width = big16(data + pos + 7);
return true;
}
pos += 2 + length;
}
return false;
}
// PORT: the IDirect3DTexture8 behind a CGraphicImageTexture::Create texture. Lock hands out the
// pixels in the texture's own format (40250 writes A4R4G4B4 words into the font pages); Unlock
// converts them to ARGB32 for the canvas and bumps the revision in the texture's name.
struct MemoryTexture : IDirect3DTexture8
{
unsigned id = 0;
int width = 0;
int height = 0;
D3DFORMAT format = D3DFMT_UNKNOWN;
std::vector<unsigned char> native;
std::vector<std::uint32_t> argb;
std::uint32_t revision = 0;
};
std::mutex g_memory_mutex;
std::map<unsigned, MemoryTexture*> g_memory;
unsigned g_memory_next_id = 1;
int bytes_per_pixel(D3DFORMAT format)
{
switch (format) {
case D3DFMT_A4R4G4B4: case D3DFMT_R5G6B5: case D3DFMT_A1R5G5B5: case D3DFMT_X1R5G5B5: case D3DFMT_X4R4G4B4:
return 2;
default:
return 4;
}
}
std::uint32_t expand(unsigned value, int bits)
{
return bits == 4 ? value * 0x11 : bits == 5 ? (value << 3) | (value >> 2) : bits == 6 ? (value << 2) | (value >> 4) : value;
}
std::uint32_t native_to_argb(D3DFORMAT format, const unsigned char* p)
{
const unsigned w = p[0] | (unsigned(p[1]) << 8);
switch (format) {
case D3DFMT_A4R4G4B4:
return (expand(w >> 12, 4) << 24) | (expand((w >> 8) & 15, 4) << 16) | (expand((w >> 4) & 15, 4) << 8) | expand(w & 15, 4);
case D3DFMT_X4R4G4B4:
return 0xFF000000u | (expand((w >> 8) & 15, 4) << 16) | (expand((w >> 4) & 15, 4) << 8) | expand(w & 15, 4);
case D3DFMT_R5G6B5:
return 0xFF000000u | (expand(w >> 11, 5) << 16) | (expand((w >> 5) & 63, 6) << 8) | expand(w & 31, 5);
case D3DFMT_A1R5G5B5: case D3DFMT_X1R5G5B5:
return ((format == D3DFMT_X1R5G5B5 || (w & 0x8000)) ? 0xFF000000u : 0) | (expand((w >> 10) & 31, 5) << 16) |
(expand((w >> 5) & 31, 5) << 8) | expand(w & 31, 5);
case D3DFMT_X8R8G8B8:
return 0xFF000000u | (p[2] << 16) | (p[1] << 8) | p[0];
default:
return (std::uint32_t(p[3]) << 24) | (p[2] << 16) | (p[1] << 8) | p[0];
}
}
MemoryTexture* live_memory_texture(const IDirect3DTexture8* texture)
{
for (const auto& entry : g_memory)
if (entry.second == texture) return entry.second;
return nullptr;
}
// PORT: the IDirect3DTexture8 behind a file texture (CreateFromMemoryFile). The canvas and the 3D
// renderer decode the file themselves; the handle only carries the pack path so a texture bound
// through STATEMANAGER.SetTexture(stage, GetD3DTexture()) can be named.
struct FileTexture : IDirect3DTexture8
{
std::string name;
};
std::set<const FileTexture*> g_file_textures; // guarded by g_memory_mutex
IDirect3DTexture8* new_file_texture(const std::string& name)
{
auto* file = new FileTexture();
file->name = name;
std::lock_guard<std::mutex> lock(g_memory_mutex);
g_file_textures.insert(file);
return file;
}
}
void UIRenderReleaseMemoryTexture(IDirect3DTexture8* texture)
{
std::lock_guard<std::mutex> lock(g_memory_mutex);
if (MemoryTexture* memory = live_memory_texture(texture)) {
g_memory.erase(memory->id);
delete memory;
} else if (g_file_textures.erase(static_cast<const FileTexture*>(texture))) {
delete static_cast<FileTexture*>(texture);
}
}
std::string UIRenderTextureNameFromHandle(const IDirect3DBaseTexture8* handle)
{
if (!handle) return {};
const auto* texture = static_cast<const IDirect3DTexture8*>(handle);
{
std::lock_guard<std::mutex> lock(g_memory_mutex);
if (const MemoryTexture* memory = live_memory_texture(texture))
return "mem:" + std::to_string(memory->id) + "@" + std::to_string(memory->revision);
const auto* file = static_cast<const FileTexture*>(texture);
if (g_file_textures.count(file))
return file->name;
}
return MtCpuTextureNameFromHandle(handle);
}
bool UIRenderMemoryTexture(const std::string& name, UIMemoryTexture* out)
{
if (name.compare(0, 4, "mem:") != 0 || !out) return false;
if (name.compare(0, 8, "mem:cpu_") == 0)
return MtCpuMemoryTexture(name, out);
const unsigned id = unsigned(std::strtoul(name.c_str() + 4, nullptr, 10));
std::lock_guard<std::mutex> lock(g_memory_mutex);
auto it = g_memory.find(id);
if (it == g_memory.end()) return false;
out->width = it->second->width;
out->height = it->second->height;
out->revision = it->second->revision;
out->argb = it->second->argb;
return true;
}
CGraphicImageTexture::CGraphicImageTexture()
{
Initialize();
}
CGraphicImageTexture::~CGraphicImageTexture()
{
Destroy();
}
auto CGraphicImageTexture::Destroy() -> void
{
CGraphicTexture::Destroy();
Initialize();
}
auto CGraphicImageTexture::Create(UINT width, UINT height, D3DFORMAT d3dFmt, DWORD dwFilter) -> bool
{
Destroy();
m_width = width;
m_height = height;
m_d3dFmt = d3dFmt;
m_dwFilter = dwFilter;
return CreateDeviceObjects();
}
auto CGraphicImageTexture::CreateDeviceObjects() -> bool
{
if (m_stFileName.empty())
{
// PORT: ms_lpd3dDevice->CreateTexture(m_width, m_height, 1, 0, m_d3dFmt, D3DPOOL_MANAGED) becomes a
// memory texture the canvas fetches by name.
if (m_width <= 0 || m_height <= 0)
return false;
auto* memory = new MemoryTexture();
memory->width = m_width;
memory->height = m_height;
memory->format = m_d3dFmt;
memory->native.assign(size_t(m_width) * size_t(m_height) * size_t(bytes_per_pixel(m_d3dFmt)), 0);
memory->argb.assign(size_t(m_width) * size_t(m_height), 0);
{
std::lock_guard<std::mutex> lock(g_memory_mutex);
memory->id = g_memory_next_id++;
g_memory[memory->id] = memory;
}
m_lpd3dTexture = memory;
}
else
{
// PORT: file textures are decoded by the canvas from the pack path; only their size is read here
// (CreateFromMemoryFile), so there is no device object to recreate.
return !m_bEmpty;
}
m_bEmpty = false;
return true;
}
auto CGraphicImageTexture::CreateFromTexturePointer(const CGraphicTexture *source) -> void
{
if (!source) { Destroy(); return; }
m_width = source->GetWidth();
m_height = source->GetHeight();
m_bEmpty = source->IsEmpty();
// 40250 shares the source's D3D texture; the canvas names textures by pack path instead.
if (const auto* image = dynamic_cast<const CGraphicImageTexture*>(source))
m_stFileName = image->m_stFileName;
// PORT: 40250 AddRefs the source's texture; this handle is not reference counted, so the copy gets
// its own named handle.
DestroyDeviceObjects();
if (!m_bEmpty && !m_stFileName.empty())
m_lpd3dTexture = new_file_texture(m_stFileName);
}
auto CGraphicImageTexture::CreateFromDiskFile(const char *, D3DFORMAT, DWORD) -> bool
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<bool>();
}
auto CGraphicImageTexture::CreateFromMemoryFile(UINT size, const void *bytes, D3DFORMAT, DWORD) -> bool
{
if (!bytes) return false;
const auto* data = static_cast<const unsigned char*>(bytes);
unsigned width = 0, height = 0;
if (size >= 20 && std::memcmp(data, "DDS ", 4) == 0) {
height = little32(data + 12); width = little32(data + 16);
} else if (size >= 24 && std::memcmp(data, "\x89PNG\r\n\x1a\n", 8) == 0) {
width = big32(data + 16); height = big32(data + 20);
} else if (jpeg_size(data, size, &width, &height)) {
} else if (size >= 26 && data[0] == 'B' && data[1] == 'M') {
width = little32(data + 18);
const int bmp_height = static_cast<int>(little32(data + 22)); // negative: top-down rows
height = static_cast<unsigned>(bmp_height < 0 ? -bmp_height : bmp_height);
} else if (size >= 18 && (data[2] == 2 || data[2] == 10 || data[2] == 3)) {
width = little16(data + 12); height = little16(data + 14);
}
if (!width || !height || width > 16384 || height > 16384) return false;
m_width = static_cast<int>(width); m_height = static_cast<int>(height);
m_bEmpty = false;
DestroyDeviceObjects();
m_lpd3dTexture = new_file_texture(m_stFileName);
return true;
}
auto CGraphicImageTexture::CreateDDSTexture(CDXTCImage &, const BYTE *) -> bool
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<bool>();
}
auto CGraphicImageTexture::SetFileName(const char *name) -> void
{
m_stFileName = name ? name : "";
}
// PORT: where 40250 binds pTexture->GetD3DTexture(), the canvas gets the pack path of the file the
// texture was decoded from (m_stFileName is protected, hence the derived accessor), or the name of the
// memory texture bound to it (a CGraphicFontTexture after SelectTexture).
std::string UIRenderTextureName(const CGraphicTexture* texture)
{
if (!texture) return {};
if (texture->GetD3DTexture()) {
std::lock_guard<std::mutex> lock(g_memory_mutex);
if (const MemoryTexture* memory = live_memory_texture(texture->GetD3DTexture()))
return "mem:" + std::to_string(memory->id) + "@" + std::to_string(memory->revision);
}
struct Access : CGraphicImageTexture {
static const std::string& name(const CGraphicImageTexture* t) { return t->*(&Access::m_stFileName); }
};
const auto* image = dynamic_cast<const CGraphicImageTexture*>(texture);
return image ? Access::name(image) : std::string();
}
// PORT: LockRect/UnlockRect on the memory texture (one level; the lock is on the whole surface).
auto CGraphicImageTexture::Lock(int* pRetPitch, void** ppRetPixels, int) -> bool
{
std::lock_guard<std::mutex> lock(g_memory_mutex);
MemoryTexture* memory = live_memory_texture(m_lpd3dTexture);
if (!memory)
return false;
*pRetPitch = memory->width * bytes_per_pixel(memory->format);
*ppRetPixels = memory->native.data();
return true;
}
auto CGraphicImageTexture::Unlock(int) -> void
{
std::lock_guard<std::mutex> lock(g_memory_mutex);
MemoryTexture* memory = live_memory_texture(m_lpd3dTexture);
assert(memory != NULL);
if (!memory)
return;
const int bpp = bytes_per_pixel(memory->format);
for (size_t i = 0; i < memory->argb.size(); ++i)
memory->argb[i] = native_to_argb(memory->format, memory->native.data() + i * size_t(bpp));
++memory->revision;
}
auto CGraphicImageTexture::Initialize() -> void
{
CGraphicTexture::Initialize();
m_stFileName = "";
m_d3dFmt=D3DFMT_UNKNOWN;
m_dwFilter=0;
}
+130
View File
@@ -0,0 +1,130 @@
// 40250 EterLib/GrpIndexBuffer.cpp over CPU memory (CpuBuffer.h).
#include "EterLib/StdAfx.h"
#include "EterLib/GrpIndexBuffer.h"
#include "EterLib/StateManager.h"
#include "CpuBuffer.h"
namespace {
BYTE* index_bytes(LPDIRECT3DINDEXBUFFER8 buffer)
{
return static_cast<MtCpuIndexBuffer*>(buffer)->bytes.data();
}
}
LPDIRECT3DINDEXBUFFER8 CGraphicIndexBuffer::GetD3DIndexBuffer() const
{
assert(m_lpd3dIdxBuf!=NULL);
return m_lpd3dIdxBuf;
}
void CGraphicIndexBuffer::SetIndices(int startIndex) const
{
STATEMANAGER.SetIndices(m_lpd3dIdxBuf, startIndex);
}
bool CGraphicIndexBuffer::Lock(void** pretIndices) const
{
assert(m_lpd3dIdxBuf!=NULL);
*pretIndices = index_bytes(m_lpd3dIdxBuf);
return true;
}
void CGraphicIndexBuffer::Unlock() const
{
assert(m_lpd3dIdxBuf!=NULL);
static_cast<MtCpuIndexBuffer*>(m_lpd3dIdxBuf)->revision++;
}
bool CGraphicIndexBuffer::Lock(void** pretIndices)
{
assert(m_lpd3dIdxBuf!=NULL);
*pretIndices = index_bytes(m_lpd3dIdxBuf);
return true;
}
void CGraphicIndexBuffer::Unlock()
{
assert(m_lpd3dIdxBuf!=NULL);
static_cast<MtCpuIndexBuffer*>(m_lpd3dIdxBuf)->revision++;
}
bool CGraphicIndexBuffer::Copy(int bufSize, const void* srcIndices)
{
assert(m_lpd3dIdxBuf!=NULL);
memcpy(index_bytes(m_lpd3dIdxBuf), srcIndices, bufSize);
static_cast<MtCpuIndexBuffer*>(m_lpd3dIdxBuf)->revision++;
return true;
}
bool CGraphicIndexBuffer::Create(int faceCount, TFace* faces)
{
int idxCount = faceCount * 3;
m_iidxCount = idxCount;
if (!Create(idxCount, D3DFMT_INDEX16))
return false;
WORD* dstIndices = reinterpret_cast<WORD*>(index_bytes(m_lpd3dIdxBuf));
for (int i = 0; i<faceCount; ++i, dstIndices+=3)
{
TFace * curFace=faces+i;
dstIndices[0]=curFace->indices[0];
dstIndices[1]=curFace->indices[1];
dstIndices[2]=curFace->indices[2];
}
static_cast<MtCpuIndexBuffer*>(m_lpd3dIdxBuf)->revision++;
return true;
}
bool CGraphicIndexBuffer::CreateDeviceObjects()
{
MtCpuIndexBuffer* buffer = new MtCpuIndexBuffer;
buffer->bytes.assign(m_dwBufferSize, 0);
buffer->format = m_d3dFmt;
m_lpd3dIdxBuf = buffer;
return true;
}
void CGraphicIndexBuffer::DestroyDeviceObjects()
{
delete static_cast<MtCpuIndexBuffer*>(m_lpd3dIdxBuf);
m_lpd3dIdxBuf = NULL;
}
bool CGraphicIndexBuffer::Create(int idxCount, D3DFORMAT d3dFmt)
{
Destroy();
m_iidxCount = idxCount;
m_dwBufferSize = sizeof(WORD) * idxCount;
m_d3dFmt = d3dFmt;
return CreateDeviceObjects();
}
void CGraphicIndexBuffer::Destroy()
{
DestroyDeviceObjects();
}
void CGraphicIndexBuffer::Initialize()
{
m_lpd3dIdxBuf=NULL;
m_iidxCount=0;
m_dwBufferSize=0;
}
CGraphicIndexBuffer::CGraphicIndexBuffer()
{
Initialize();
}
CGraphicIndexBuffer::~CGraphicIndexBuffer()
{
Destroy();
}
+45
View File
@@ -0,0 +1,45 @@
// Platform skeleton for EterLib/GrpMath.h (40250 EterLib/GrpMath.cpp), generated by platform_stub.py.
// Every MT_PLATFORM_STUB() body is unimplemented: replace it with the platform implementation.
#include "EterLib/StdAfx.h"
#include "EterLib/GrpMath.h"
#include "../PlatformStub.h"
auto CrossProduct2D(float, float, float, float) -> float
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<float>();
}
auto IsInTriangle2D(float, float, float, float, float, float, float, float) -> bool
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<bool>();
}
auto D3DXVec3Rotation(D3DXVECTOR3 *, const D3DXVECTOR3 *, const D3DXQUATERNION *) -> D3DXVECTOR3 *
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<D3DXVECTOR3 *>();
}
auto D3DXVec3Translation(D3DXVECTOR3 *, const D3DXVECTOR3 *, const D3DXVECTOR3 *) -> D3DXVECTOR3 *
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<D3DXVECTOR3 *>();
}
auto GetRotationFromMatrix(D3DXVECTOR3 *, const D3DXMATRIX *) -> void
{
MT_PLATFORM_STUB();
}
auto GetPivotAndRotationFromMatrix(D3DXMATRIX *, D3DXVECTOR3 *, D3DXVECTOR3 *) -> void
{
MT_PLATFORM_STUB();
}
auto ExtractMovement(D3DXMATRIX *, D3DXMATRIX *) -> void
{
MT_PLATFORM_STUB();
}
+435
View File
@@ -0,0 +1,435 @@
// Platform skeleton for EterLib/GrpScreen.h (40250 EterLib/GrpScreen.cpp), generated by platform_stub.py.
// Every MT_PLATFORM_STUB() body is unimplemented: replace it with the platform implementation.
#include "EterLib/StdAfx.h"
#include "EterLib/GrpScreen.h"
#include "EterLib/StateManager.h"
#include "EterLib/Camera.h"
#include "../PlatformStub.h"
#include "UIRenderCommands.h"
#include <algorithm>
// 40250 GrpScreen.cpp:838
CScreen::CScreen()
{
}
CScreen::~CScreen()
{
}
auto CScreen::ClearDepthBuffer() -> void
{
if (ms_lpd3dDevice)
ms_lpd3dDevice->Clear(0L, NULL, D3DCLEAR_ZBUFFER, ms_clearColor, ms_clearDepth, ms_clearStencil);
}
auto CScreen::Clear() -> void
{
if (ms_lpd3dDevice)
ms_lpd3dDevice->Clear(0L, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, ms_clearColor, ms_clearDepth, ms_clearStencil);
}
// 40250 GrpScreen.cpp:691. CPythonApplication::Process brackets the frame's render with Begin/End; only
// inside the scene does CStateManager hand transforms to the recording device.
bool CScreen::Begin()
{
assert(ms_lpd3dDevice != NULL);
ResetFaceCount();
if (!STATEMANAGER.BeginScene())
{
Tracenf("BeginScene FAILED\n");
return false;
}
return true;
}
// 40250 GrpScreen.cpp:705
void CScreen::End()
{
STATEMANAGER.EndScene();
}
auto CScreen::Show(HWND) -> void
{
MT_PLATFORM_STUB();
}
auto CScreen::Show(RECT *) -> void
{
MT_PLATFORM_STUB();
}
auto CScreen::Show(RECT *, HWND) -> void
{
MT_PLATFORM_STUB();
}
auto CScreen::RenderLine2d(float sx, float sy, float ex, float ey, float) -> void
{
UIRenderAdd({UIRenderCommand::Line, sx, sy, ex, ey, ms_diffuseColor});
}
auto CScreen::RenderBox2d(float sx, float sy, float ex, float ey, float) -> void
{
// 40250's four line pairs, including its one-pixel extension of the bottom edge.
UIRenderAdd({UIRenderCommand::Line, sx, sy, ex, sy, ms_diffuseColor});
UIRenderAdd({UIRenderCommand::Line, sx, sy, sx, ey, ms_diffuseColor});
UIRenderAdd({UIRenderCommand::Line, ex, sy, ex, ey, ms_diffuseColor});
UIRenderAdd({UIRenderCommand::Line, sx, ey, ex + 1.0f, ey, ms_diffuseColor});
}
auto CScreen::RenderBar2d(float sx, float sy, float ex, float ey, float) -> void
{
UIRenderAdd({UIRenderCommand::Bar, sx, sy, ex, ey, ms_diffuseColor});
}
auto CScreen::RenderGradationBar2d(float sx, float sy, float ex, float ey, DWORD start, DWORD end, float) -> void
{
if (sx == ex || sy == ey)
return;
UIRenderCommand command{UIRenderCommand::GradientBar, sx, sy, ex, ey, start};
command.end_argb = end;
UIRenderAdd(std::move(command));
}
auto CScreen::RenderCircle2d(float, float, float, float, int) -> void
{
MT_PLATFORM_STUB();
}
auto CScreen::RenderCircle3d(float, float, float, float, int) -> void
{
MT_PLATFORM_STUB();
}
auto CScreen::RenderLine3d(float, float, float, float, float, float) -> void
{
MT_PLATFORM_STUB();
}
auto CScreen::RenderBox3d(float, float, float, float, float, float) -> void
{
MT_PLATFORM_STUB();
}
auto CScreen::RenderBar3d(float, float, float, float, float, float) -> void
{
MT_PLATFORM_STUB();
}
auto CScreen::RenderBar3d(const D3DXVECTOR3 *) -> void
{
MT_PLATFORM_STUB();
}
auto CScreen::RenderGradationBar3d(float, float, float, float, float, float, DWORD, DWORD) -> void
{
MT_PLATFORM_STUB();
}
auto CScreen::RenderLineCube(float, float, float, float, float, float) -> void
{
MT_PLATFORM_STUB();
}
auto CScreen::RenderCube(float, float, float, float, float, float) -> void
{
MT_PLATFORM_STUB();
}
auto CScreen::RenderCube(float, float, float, float, float, float, D3DXMATRIX) -> void
{
MT_PLATFORM_STUB();
}
auto CScreen::RenderTextureBox(float, float, float, float, float, float, float, float, float) -> void
{
MT_PLATFORM_STUB();
}
auto CScreen::RenderBillboard(D3DXVECTOR3 *, D3DXCOLOR &) -> void
{
MT_PLATFORM_STUB();
}
auto CScreen::DrawMinorGrid(float, float, float, float, float, float, float) -> void
{
MT_PLATFORM_STUB();
}
auto CScreen::DrawGrid(float, float, float, float, float, float, float, float, float) -> void
{
MT_PLATFORM_STUB();
}
auto CScreen::RenderD3DXMesh(LPD3DXMESH, const D3DXMATRIX *, float, float, float, float, D3DFILLMODE) -> void
{
MT_PLATFORM_STUB();
}
auto CScreen::RenderSphere(const D3DXMATRIX *, float, float, float, float, D3DFILLMODE) -> void
{
MT_PLATFORM_STUB();
}
auto CScreen::RenderCylinder(const D3DXMATRIX *, float, float, float, float, float, D3DFILLMODE) -> void
{
MT_PLATFORM_STUB();
}
// 40250 GrpScreen.cpp
void CScreen::SetColorOperation()
{
STATEMANAGER.SetTexture(0, NULL);
STATEMANAGER.SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_DIFFUSE);
STATEMANAGER.SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
STATEMANAGER.SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_DISABLE);
STATEMANAGER.SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_DISABLE);
STATEMANAGER.SetTextureStageState(1, D3DTSS_ALPHAOP, D3DTOP_DISABLE);
}
// 40250 GrpScreen.cpp
void CScreen::SetDiffuseOperation()
{
STATEMANAGER.SetTexture(0, NULL);
STATEMANAGER.SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE);
STATEMANAGER.SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_DIFFUSE);
STATEMANAGER.SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_MODULATE);
STATEMANAGER.SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_DISABLE);
STATEMANAGER.SetTextureStageState(1, D3DTSS_ALPHAOP, D3DTOP_DISABLE);
}
// 40250 GrpScreen.cpp
void CScreen::SetBlendOperation()
{
STATEMANAGER.SetTexture(0, NULL);
STATEMANAGER.SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE);
STATEMANAGER.SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_CURRENT);
STATEMANAGER.SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_MODULATE);
STATEMANAGER.SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE);
STATEMANAGER.SetTextureStageState(0, D3DTSS_ALPHAARG2, D3DTA_CURRENT);
STATEMANAGER.SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_MODULATE);
STATEMANAGER.SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_DISABLE);
STATEMANAGER.SetTextureStageState(1, D3DTSS_ALPHAOP, D3DTOP_DISABLE);
}
auto CScreen::SetOneColorOperation(D3DXCOLOR &) -> void
{
MT_PLATFORM_STUB();
}
auto CScreen::SetAddColorOperation(D3DXCOLOR &) -> void
{
MT_PLATFORM_STUB();
}
auto CScreen::SetDiffuseColor(DWORD color) -> void
{
ms_diffuseColor = color;
}
auto CScreen::SetDiffuseColor(float r, float g, float b, float a) -> void
{
auto channel = [](float value) -> DWORD {
return static_cast<DWORD>(std::clamp(value, 0.0f, 1.0f) * 255.0f + 0.5f);
};
ms_diffuseColor = (channel(a) << 24) | (channel(r) << 16) | (channel(g) << 8) | channel(b);
}
auto CScreen::SetClearColor(float, float, float, float) -> void
{
MT_PLATFORM_STUB();
}
auto CScreen::SetClearDepth(float) -> void
{
MT_PLATFORM_STUB();
}
auto CScreen::SetClearStencil(DWORD) -> void
{
MT_PLATFORM_STUB();
}
// 40250 GrpScreen.cpp:487, verbatim: the pick ray through the cursor.
void CScreen::SetCursorPosition(int x, int y, int hres, int vres)
{
D3DXVECTOR3 v;
v.x = -(((2.0f * x) / hres) - 1) / ms_matProj._11;
v.y = (((2.0f * y) / vres) - 1) / ms_matProj._22;
v.z = 1.0f;
D3DXMATRIX matViewInverse=ms_matInverseView;
//D3DXMatrixInverse(&matViewInverse, NULL, &ms_matView);
ms_vtPickRayDir.x = v.x * matViewInverse._11 +
v.y * matViewInverse._21 +
v.z * matViewInverse._31;
ms_vtPickRayDir.y = v.x * matViewInverse._12 +
v.y * matViewInverse._22 +
v.z * matViewInverse._32;
ms_vtPickRayDir.z = v.x * matViewInverse._13 +
v.y * matViewInverse._23 +
v.z * matViewInverse._33;
ms_vtPickRayOrig.x = matViewInverse._41;
ms_vtPickRayOrig.y = matViewInverse._42;
ms_vtPickRayOrig.z = matViewInverse._43;
ms_Ray.SetStartPoint(ms_vtPickRayOrig);
ms_Ray.SetDirection(-ms_vtPickRayDir, 51200.0f);
}
auto CScreen::GetCursorPosition(float * px, float * py, float * pz) -> bool
{
if (!GetCursorXYPosition(px, py)) return false;
if (!GetCursorZPosition(pz)) return false;
return true;
}
auto CScreen::GetCursorXYPosition(float * px, float * py) -> bool
{
D3DXVECTOR3 v3Eye = CCameraManager::Instance().GetCurrentCamera()->GetEye();
TPosition posVertices[4];
posVertices[0] = TPosition(v3Eye.x - 90000000.0f, v3Eye.y + 90000000.0f, 0.0f);
posVertices[1] = TPosition(v3Eye.x - 90000000.0f, v3Eye.y - 90000000.0f, 0.0f);
posVertices[2] = TPosition(v3Eye.x + 90000000.0f, v3Eye.y + 90000000.0f, 0.0f);
posVertices[3] = TPosition(v3Eye.x + 90000000.0f, v3Eye.y - 90000000.0f, 0.0f);
static const WORD sc_awFillRectIndices[6] = { 0, 2, 1, 2, 3, 1, };
float u, v, t;
for (int i = 0; i < 2; ++i)
{
if (IntersectTriangle(ms_vtPickRayOrig, ms_vtPickRayDir,
posVertices[sc_awFillRectIndices[i * 3]],
posVertices[sc_awFillRectIndices[i * 3 + 1]],
posVertices[sc_awFillRectIndices[i * 3 + 2]],
&u, &v, &t))
{
*px = u;
*py = v;
return true;
}
}
return false;
}
auto CScreen::GetCursorZPosition(float * pz) -> bool
{
D3DXVECTOR3 v3Eye = CCameraManager::Instance().GetCurrentCamera()->GetEye();
TPosition posVertices[4];
posVertices[0] = TPosition(v3Eye.x - 90000000.0f, 0.0f, v3Eye.z + 90000000.0f);
posVertices[1] = TPosition(v3Eye.x - 90000000.0f, 0.0f, v3Eye.z - 90000000.0f);
posVertices[2] = TPosition(v3Eye.x + 90000000.0f, 0.0f, v3Eye.z + 90000000.0f);
posVertices[3] = TPosition(v3Eye.x + 90000000.0f, 0.0f, v3Eye.z - 90000000.0f);
static const WORD sc_awFillRectIndices[6] = { 0, 2, 1, 2, 3, 1, };
float u, v, t;
for (int i = 0; i < 2; ++i)
{
if (IntersectTriangle(ms_vtPickRayOrig, ms_vtPickRayDir,
posVertices[sc_awFillRectIndices[i * 3]],
posVertices[sc_awFillRectIndices[i * 3 + 1]],
posVertices[sc_awFillRectIndices[i * 3 + 2]],
&u, &v, &t))
{
*pz = t;
return true;
}
}
return false;
}
auto CScreen::GetPickingPosition(float t, float * x, float * y, float * z) -> void
{
*x = ms_vtPickRayOrig.x + ms_vtPickRayDir.x * t;
*y = ms_vtPickRayOrig.y + ms_vtPickRayDir.y * t;
*z = ms_vtPickRayOrig.z + ms_vtPickRayDir.z * t;
}
// 40250 GrpScreen.cpp:749-779.
void CScreen::ProjectPosition(float x, float y, float z, float * pfX, float * pfY)
{
D3DXVECTOR3 Input(x, y, z);
D3DXVECTOR3 Output;
D3DXVec3Project(&Output, &Input, &ms_Viewport, &ms_matProj, &ms_matView, &ms_matIdentity);
*pfX = Output.x;
*pfY = Output.y;
}
void CScreen::ProjectPosition(float x, float y, float z, float * pfX, float * pfY, float * pfZ)
{
D3DXVECTOR3 Input(x, y, z);
D3DXVECTOR3 Output;
D3DXVec3Project(&Output, &Input, &ms_Viewport, &ms_matProj, &ms_matView, &ms_matIdentity);
*pfX = Output.x;
*pfY = Output.y;
*pfZ = Output.z;
}
void CScreen::UnprojectPosition(float x, float y, float z, float * pfX, float * pfY, float * pfZ)
{
D3DXVECTOR3 Input(x, y, z);
D3DXVECTOR3 Output;
D3DXVec3Unproject(&Output, &Input, &ms_Viewport, &ms_matProj, &ms_matView, &ms_matIdentity);
*pfX = Output.x;
*pfY = Output.y;
*pfZ = Output.z;
}
auto CScreen::IsLostDevice() -> BOOL
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<BOOL>();
}
auto CScreen::RestoreDevice() -> BOOL
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<BOOL>();
}
auto CScreen::BuildViewFrustum() -> void
{
CCamera* pkCamera = CCameraManager::Instance().GetCurrentCamera();
if (!pkCamera)
return;
const D3DXVECTOR3& c_rv3Eye = pkCamera->GetEye();
const D3DXVECTOR3& c_rv3View = pkCamera->GetView();
auto vv = ms_matView * ms_matProj;
ms_frustum.BuildViewFrustum2(
vv,
ms_fNearY,
ms_fFarY,
ms_fFieldOfView,
ms_fAspect,
c_rv3Eye, c_rv3View);
}
auto CScreen::Identity() -> void
{
STATEMANAGER.SetTransform(D3DTS_WORLD, &ms_matIdentity);
}
decltype(CScreen::ms_diffuseColor) CScreen::ms_diffuseColor = 0xffffffff;
decltype(CScreen::ms_clearColor) CScreen::ms_clearColor{};
decltype(CScreen::ms_clearStencil) CScreen::ms_clearStencil{};
decltype(CScreen::ms_clearDepth) CScreen::ms_clearDepth = 1.0f;
decltype(CScreen::ms_frustum) CScreen::ms_frustum{};
+100
View File
@@ -0,0 +1,100 @@
#include "EterLib/StdAfx.h"
#include "EterLib/GrpSubImage.h"
#include "EterLib/ResourceManager.h"
#include <algorithm>
#include <cctype>
#include <cstdlib>
#include <cstring>
#include <map>
#include <sstream>
#include <string>
char CGraphicSubImage::m_SearchPath[256] = "D:/Ymir Work/UI/";
auto CGraphicSubImage::Type() -> TType
{
static TType type = StringToType("CGraphicSubImage");
return type;
}
CGraphicSubImage::CGraphicSubImage(const char* name) : CGraphicImage(name) {}
CGraphicSubImage::~CGraphicSubImage() { m_roImage.Clear(); }
bool CGraphicSubImage::CreateDeviceObjects()
{
if (m_roImage.IsNull()) return false;
m_imageTexture.CreateFromTexturePointer(m_roImage->GetTexturePointer());
return true;
}
void CGraphicSubImage::SetImagePointer(CGraphicImage* image)
{
m_roImage.SetPointer(image);
CreateDeviceObjects();
}
bool CGraphicSubImage::SetImageFileName(const char* name)
{
CResource* resource = CResourceManager::Instance().GetResourcePointer(name);
if (!resource || !resource->IsType(CGraphicImage::Type())) return false;
SetImagePointer(static_cast<CGraphicImage*>(resource));
return true;
}
void CGraphicSubImage::SetRectPosition(int left, int top, int right, int bottom)
{
m_rect = {left, top, right, bottom};
}
void CGraphicSubImage::SetRectReference(const RECT& rect) { m_rect = rect; }
void CGraphicSubImage::SetSearchPath(const char* path)
{
if (!path) return;
std::strncpy(m_SearchPath, path, sizeof(m_SearchPath) - 1);
m_SearchPath[sizeof(m_SearchPath) - 1] = 0;
}
bool CGraphicSubImage::OnLoad(int size, const void* bytes)
{
if (!bytes || size <= 0) return false;
std::istringstream input(std::string(static_cast<const char*>(bytes), static_cast<size_t>(size)));
std::map<std::string, std::string> tokens;
std::string line;
while (std::getline(input, line)) {
std::istringstream fields(line);
std::string key, value;
if (!(fields >> key >> value)) continue;
if (!value.empty() && value.front() == '"') {
value.erase(0, 1);
if (!value.empty() && value.back() == '"') value.pop_back();
}
std::transform(key.begin(), key.end(), key.begin(), [](unsigned char c) { return std::tolower(c); });
std::transform(value.begin(), value.end(), value.begin(), [](unsigned char c) { return std::tolower(c); });
tokens[key] = value;
}
if (tokens["title"] != "subimage" || tokens["image"].empty()) return false;
std::string image_path;
if (tokens["version"] == "2.0") {
const std::string parent = GetFileNameString();
const auto slash = parent.find_last_of("\\/");
image_path = slash == std::string::npos ? tokens["image"] : parent.substr(0, slash + 1) + tokens["image"];
} else {
image_path = std::string(m_SearchPath) + tokens["image"];
}
if (!SetImageFileName(image_path.c_str())) return false;
SetRectPosition(std::atoi(tokens["left"].c_str()), std::atoi(tokens["top"].c_str()),
std::atoi(tokens["right"].c_str()), std::atoi(tokens["bottom"].c_str()));
return true;
}
void CGraphicSubImage::OnClear()
{
m_roImage.Clear();
m_imageTexture.Destroy();
m_rect = {0, 0, 0, 0};
}
bool CGraphicSubImage::OnIsEmpty() const { return m_roImage.IsNull() || m_roImage->IsEmpty(); }
bool CGraphicSubImage::OnIsType(TType type) { return type == Type() || CGraphicImage::OnIsType(type); }
+102
View File
@@ -0,0 +1,102 @@
// 40250 EterLib/GrpText.cpp, verbatim.
#include "EterLib/StdAfx.h"
#include "EterBase/Utils.h"
#include "EterLib/GrpText.h"
CGraphicText::CGraphicText(const char* c_szFileName) : CResource(c_szFileName)
{
}
CGraphicText::~CGraphicText()
{
}
bool CGraphicText::CreateDeviceObjects()
{
return m_fontTexture.CreateDeviceObjects();
}
void CGraphicText::DestroyDeviceObjects()
{
m_fontTexture.DestroyDeviceObjects();
}
CGraphicFontTexture* CGraphicText::GetFontTexturePointer()
{
return &m_fontTexture;
}
CGraphicText::TType CGraphicText::Type()
{
static TType s_type = StringToType("CGraphicText");
return s_type;
}
bool CGraphicText::OnLoad(int /*iSize*/, const void* /*c_pvBuf*/)
{
static char strName[32];
int size;
bool bItalic = false;
// format
// 굴림.fnt "굴림" 폰트 기본 사이즈 12 로 로딩
// 굴림:18.fnt "굴림" 폰트 사이즈 18 로 로딩
// 굴림:14i.fnt "굴림" 폰트 사이즈 14 & 이탤릭으로 로딩
const char * p = strrchr(GetFileName(), ':');
if (p)
{
strncpy(strName, GetFileName(), MIN(31, p - GetFileName()));
++p;
static char num[8];
int i = 0;
while (*p && isdigit(*p))
{
num[i++] = *(p++);
}
num[i] = '\0';
if(*p == 'i')
bItalic = true;
size = atoi(num);
}
else
{
p = strrchr(GetFileName(), '.');
if (!p)
{
assert(!"CGraphicText::OnLoadFromFile there is no extension (ie: .fnt)");
strName[0] = '\0';
}
else
strncpy(strName, GetFileName(), MIN(31, p - GetFileName()));
size = 12;
}
if (!m_fontTexture.Create(strName, size, bItalic))
return false;
return true;
}
void CGraphicText::OnClear()
{
m_fontTexture.Destroy();
}
bool CGraphicText::OnIsEmpty() const
{
return m_fontTexture.IsEmpty();
}
bool CGraphicText::OnIsType(TType type)
{
if (CGraphicText::Type() == type)
return true;
return CResource::OnIsType(type);
}
File diff suppressed because it is too large Load Diff
+64
View File
@@ -0,0 +1,64 @@
// Platform skeleton for EterLib/GrpTexture.h (40250 EterLib/GrpTexture.cpp), generated by platform_stub.py.
// Every MT_PLATFORM_STUB() body is unimplemented: replace it with the platform implementation.
#include "EterLib/StdAfx.h"
#include "EterLib/GrpTexture.h"
#include "../PlatformStub.h"
#include "UIRenderCommands.h"
auto CGraphicTexture::IsEmpty() const -> bool
{
return m_bEmpty;
}
auto CGraphicTexture::GetWidth() const -> int
{
return m_width;
}
auto CGraphicTexture::GetHeight() const -> int
{
return m_height;
}
auto CGraphicTexture::SetTextureStage(int) const -> void
{
MT_PLATFORM_STUB();
}
auto CGraphicTexture::GetD3DTexture() const -> LPDIRECT3DTEXTURE8
{
return m_lpd3dTexture;
}
// PORT: safe_release(m_lpd3dTexture); the platform textures are memory textures and file-texture handles.
auto CGraphicTexture::DestroyDeviceObjects() -> void
{
if (m_lpd3dTexture)
UIRenderReleaseMemoryTexture(m_lpd3dTexture);
m_lpd3dTexture = NULL;
}
CGraphicTexture::CGraphicTexture()
{
Initialize();
}
CGraphicTexture::~CGraphicTexture()
{
}
auto CGraphicTexture::Destroy() -> void
{
DestroyDeviceObjects();
Initialize();
}
auto CGraphicTexture::Initialize() -> void
{
m_lpd3dTexture = NULL;
m_width = 0;
m_height = 0;
m_bEmpty = true;
}
+162
View File
@@ -0,0 +1,162 @@
// 40250 EterLib/GrpVertexBuffer.cpp over CPU memory (CpuBuffer.h): the device buffer is a byte vector
// that Lock hands out directly, so Granny vertex loading and deform write real data.
#include "EterLib/StdAfx.h"
#include "EterLib/GrpVertexBuffer.h"
#include "EterLib/StateManager.h"
#include "CpuBuffer.h"
int CGraphicVertexBuffer::GetVertexStride() const
{
int retSize = mt_fvf_vertex_size(m_dwFVF);
return retSize;
}
DWORD CGraphicVertexBuffer::GetFlexibleVertexFormat() const
{
return m_dwFVF;
}
int CGraphicVertexBuffer::GetVertexCount() const
{
return m_vtxCount;
}
void CGraphicVertexBuffer::SetStream(int stride, int layer) const
{
STATEMANAGER.SetStreamSource(layer, m_lpd3dVB, stride);
}
bool CGraphicVertexBuffer::LockRange(unsigned count, void** pretVertices) const
{
if (!m_lpd3dVB)
return false;
*pretVertices = static_cast<MtCpuVertexBuffer*>(m_lpd3dVB)->bytes.data();
return true;
}
bool CGraphicVertexBuffer::Lock(void ** pretVertices) const
{
if (!m_lpd3dVB)
return false;
*pretVertices = static_cast<MtCpuVertexBuffer*>(m_lpd3dVB)->bytes.data();
return true;
}
bool CGraphicVertexBuffer::Unlock() const
{
if (!m_lpd3dVB)
return false;
static_cast<MtCpuVertexBuffer*>(m_lpd3dVB)->revision++;
return true;
}
// Returns true when a buffer exists, as 40250 does.
bool CGraphicVertexBuffer::IsEmpty() const
{
if (m_lpd3dVB)
return true;
else
return false;
}
bool CGraphicVertexBuffer::LockDynamic(void** pretVertices)
{
if (!m_lpd3dVB)
return false;
*pretVertices = static_cast<MtCpuVertexBuffer*>(m_lpd3dVB)->bytes.data();
return true;
}
bool CGraphicVertexBuffer::Lock(void ** pretVertices)
{
if (!m_lpd3dVB)
return false;
*pretVertices = static_cast<MtCpuVertexBuffer*>(m_lpd3dVB)->bytes.data();
return true;
}
bool CGraphicVertexBuffer::Unlock()
{
if (!m_lpd3dVB)
return false;
static_cast<MtCpuVertexBuffer*>(m_lpd3dVB)->revision++;
return true;
}
bool CGraphicVertexBuffer::Copy(int bufSize, const void* srcVertices)
{
void * dstVertices;
if (!Lock(&dstVertices))
return false;
memcpy(dstVertices, srcVertices, bufSize);
Unlock();
return true;
}
bool CGraphicVertexBuffer::CreateDeviceObjects()
{
assert(m_lpd3dVB == NULL);
MtCpuVertexBuffer* buffer = new MtCpuVertexBuffer;
buffer->bytes.assign(m_dwBufferSize, 0);
buffer->fvf = m_dwFVF;
m_lpd3dVB = buffer;
return true;
}
void CGraphicVertexBuffer::DestroyDeviceObjects()
{
delete static_cast<MtCpuVertexBuffer*>(m_lpd3dVB);
m_lpd3dVB = NULL;
}
bool CGraphicVertexBuffer::Create(int vtxCount, DWORD fvf, DWORD usage, D3DPOOL d3dPool)
{
assert(vtxCount > 0);
Destroy();
m_vtxCount = vtxCount;
m_dwBufferSize = mt_fvf_vertex_size(fvf) * m_vtxCount;
m_d3dPool = d3dPool;
m_dwUsage = usage;
m_dwFVF = fvf;
if (usage == D3DUSAGE_WRITEONLY || usage == D3DUSAGE_DYNAMIC)
m_dwLockFlag = 0;
else
m_dwLockFlag = D3DLOCK_READONLY;
return CreateDeviceObjects();
}
void CGraphicVertexBuffer::Destroy()
{
DestroyDeviceObjects();
}
void CGraphicVertexBuffer::Initialize()
{
m_lpd3dVB = NULL;
m_vtxCount = 0;
m_dwBufferSize = 0;
m_dwFVF = 0;
}
CGraphicVertexBuffer::CGraphicVertexBuffer()
{
Initialize();
}
CGraphicVertexBuffer::~CGraphicVertexBuffer()
{
Destroy();
}
@@ -0,0 +1,22 @@
// Platform skeleton for EterLib/GrpVertexBufferDynamic.h (40250 EterLib/GrpVertexBufferDynamic.cpp), generated by platform_stub.py.
// Every MT_PLATFORM_STUB() body is unimplemented: replace it with the platform implementation.
#include "EterLib/StdAfx.h"
#include "EterLib/GrpVertexBufferDynamic.h"
#include "../PlatformStub.h"
CDynamicVertexBuffer::CDynamicVertexBuffer()
{
MT_PLATFORM_STUB();
}
CDynamicVertexBuffer::~CDynamicVertexBuffer()
{
MT_PLATFORM_STUB();
}
auto CDynamicVertexBuffer::Create(int, int) -> bool
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<bool>();
}
+4
View File
@@ -0,0 +1,4 @@
#pragma once
// The cursor in client coordinates, as the host (Godot) last pushed it. 40250 CMSWindow::GetMousePosition
// asks Win32 (GetCursorPos + ScreenToClient); here the host is the only source of mouse input.
void MtHostSetCursor(int x, int y);
+752
View File
@@ -0,0 +1,752 @@
// Platform implementation of EterLib/IME.h (40250 EterLib/IME.cpp).
// The edit buffer (m_wText, cursor, SetText/GetText, OnChar/InsertString, IsMax, the colour-tag aware cursor
// moves) and WMChar are the 40250 bodies verbatim. What 40250 gets from Win32 IMM/TSF — composition strings,
// the candidate list, the reading window, keyboard-layout code pages — has no counterpart under Godot: the
// host delivers committed characters only (Metin2PythonHost.ui_char -> WMChar, or InsertString for text the
// input code page cannot hold, which is what 40250's ResultProcess does with a GCS_RESULTSTR). Those entry
// points keep 40250's "no IME present" behaviour: no composition, empty candidate/reading lists.
#include "EterLib/StdAfx.h"
#include "EterLib/IME.h"
#include "EterLib/TextTag.h"
#include "EterLib/GrpTextInstance.h"
#include "EterLib/Util.h"
#include <algorithm>
#include <cwctype>
namespace
{
// 40250 s_aszIndicator[INDICATOR_NON_IME] (IME.cpp:67); CheckInputLocale overwrites it with the locale's
// two-letter abbreviation, which here is the locale code page's language.
wchar_t s_aszNonImeIndicator[3] = L"En";
}
/*---------------------------------------------------------------------------*/ /* Public */
CIME::CIME()
{
ms_hWnd = NULL;
ms_bCandidateList = false;
ms_bReadingInformation = false;
Clear();
m_max = 0;
m_userMax = 0;
m_bOnlyNumberMode = FALSE;
m_hOrgIMC = NULL;
m_bEnablePaste = false;
m_bUseDefaultIME = false;
}
CIME::~CIME()
{
}
// PORT: 40250 loads imm32.dll, disables Cicero, reads the keyboard layout and sets up the TSF sinks. The
// Godot host has no IMM context; only the part the edit buffer depends on — the input/output code page from
// CheckInputLocale and SetSupportLevel(2) — is kept.
bool CIME::Initialize(HWND hWnd)
{
if(ms_bInitialized)
return true;
ms_hWnd = hWnd;
ms_bDisableIMECompletely = true;
ms_bInitialized = true;
CheckInputLocale();
ChangeInputLanguageWorker();
SetSupportLevel(2);
ms_bUILessMode = false;
CheckToggleState();
return true;
}
void CIME::Uninitialize()
{
if ( !ms_bInitialized )
return;
ms_hWnd = NULL;
m_hOrgIMC = NULL;
ms_bInitialized = false;
}
void CIME::UseDefaultIME()
{
m_bUseDefaultIME = true;
}
bool CIME::IsIMEEnabled()
{
return ms_bImeEnabled;
}
// PORT: 40250 ImmAssociateContext()s the window; ms_bDisableIMECompletely (no imm32) forces bEnable=false,
// which is always the case here.
void CIME::EnableIME(bool bEnable)
{
if (!ms_bInitialized || !ms_hWnd)
return;
if (ms_bDisableIMECompletely)
bEnable = false;
ms_bImeEnabled = bEnable;
if (bEnable)
CheckToggleState();
}
void CIME::DisableIME()
{
EnableIME(false);
}
void CIME::EnableCaptureInput()
{
ms_bCaptureInput = true;
}
void CIME::DisableCaptureInput()
{
ms_bCaptureInput = false;
}
bool CIME::IsCaptureEnabled()
{
return ms_bCaptureInput;
}
void CIME::Clear()
{
ms_lastpos = 0;
ms_curpos = 0;
ms_compLen = 0;
ms_ulbegin = 0;
ms_ulend = 0;
}
int CIME::GetReading(std::string & rstrText)
{
char reading[IMEREADING_MAXLEN];
if(ms_wstrReading.size() == 0)
return 0;
int readingLen = WideCharToMultiByte(ms_uOutputCodePage, 0, &ms_wstrReading[0], ms_wstrReading.size(), reading, sizeof(reading), NULL, NULL);
rstrText.append(GetCodePageText());
rstrText.append(reading, reading + readingLen);
return rstrText.size();
}
int CIME::GetReadingError()
{
return ms_iReadingError;
}
void CIME::SetMax(int iMax)
{
m_max = iMax;
}
void CIME::SetUserMax(int iMax)
{
m_userMax = iMax;
}
void CIME::SetText(const char* szText, int len)
{
ms_compLen = 0;
ms_ulbegin = 0;
ms_ulend = 0;
const char* begin = szText;
const char* end = begin + len;
const char* iter = FindToken(begin, end);
int m_wTextLen = sizeof(m_wText)/sizeof(wchar_t);
ms_lastpos = MultiByteToWideChar(ms_uInputCodePage, 0, begin, iter-begin, m_wText, m_wTextLen);
if (iter < end)
ms_lastpos += MultiByteToWideChar(ReadToken(iter), 0, (iter+5), end-(iter+5), m_wText+ms_lastpos, m_wTextLen-ms_lastpos);
ms_curpos = std::min(ms_curpos, ms_lastpos);
}
int CIME::GetText(std::string & rstrText, bool addCodePage)
{
int outCodePage = ms_uOutputCodePage;
int dataCodePage;
switch (outCodePage)
{
//case 1256: // ARABIC
case 1268: // VIETNAM
dataCodePage = CP_UTF8;
break;
default:
dataCodePage = outCodePage;
}
int len = 0;
char text[IMESTR_MAXLEN];
len += WideCharToMultiByte(dataCodePage, 0, m_wText, ms_curpos, text, sizeof(text)-len, NULL, NULL);
len += WideCharToMultiByte(dataCodePage, 0, m_wszComposition, ms_compLen, text+len, sizeof(text)-len, NULL, NULL);
len += WideCharToMultiByte(dataCodePage, 0, m_wText+ms_curpos, ms_lastpos-ms_curpos, text+len, sizeof(text)-len, NULL, NULL);
int i;
for(i=0; i<len; ++i)
if((BYTE)text[i] > 0x7F) break;
if(i == len)
{
rstrText.append(text, text+len);
}
else
{
rstrText.append(text, text+i);
//if (addCodePage)
// rstrText.append(GetCodePageText());
rstrText.append(text+i, text+len);
}
return rstrText.size();
}
const char* CIME::GetCodePageText()
{
static char szCodePage[16];
const int defCodePage = GetDefaultCodePage();
const int outCodePage = ms_uOutputCodePage;
if (outCodePage != defCodePage)
{
sprintf(szCodePage, "@%04d", outCodePage);
}
else
{
szCodePage[0] = 0;
}
return szCodePage;
}
int CIME::GetCodePage()
{
return ms_uOutputCodePage;
}
int CIME::GetCandidatePageCount()
{
return ms_dwCandidatePageSize;
}
int CIME::GetCandidateCount()
{
return ms_dwCandidateCount;
}
int CIME::GetCandidate(DWORD index, std::string & rstrText)
{
if(index >= MAX_CANDLIST)
return 0;
LPCWSTR wszText = ms_wszCandidate[index];
if(wszText == NULL)
return 0;
int wTextLen = wcslen(wszText);
if(wTextLen == 0)
return 0;
char text[IMESTR_MAXLEN];
int len = ::WideCharToMultiByte(CP_UTF8, 0, wszText, wTextLen, text, sizeof(text), 0, 0);
rstrText.append("@9999");
rstrText.append(text, text+len);
return wTextLen;
}
int CIME::GetCandidateSelection()
{
return ms_dwCandidateSelection;
}
// PORT: 40250 ImmSetConversionStatus / ImmGetConversionStatus. Without an IMM context the conversion mode is
// the alphanumeric one (IME_CMODE_ALPHANUMERIC == 0) and cannot be changed.
void CIME::SetInputMode(DWORD)
{
}
DWORD CIME::GetInputMode()
{
return 0;
}
void CIME::SetNumberMode()
{
m_bOnlyNumberMode = TRUE;
}
void CIME::SetStringMode()
{
m_bOnlyNumberMode = FALSE;
}
void CIME::AddExceptKey(wchar_t key)
{
m_exceptKey.push_back(key);
}
void CIME::ClearExceptKey()
{
m_exceptKey.clear();
}
bool CIME::__IsWritable(wchar_t key)
{
if ( m_exceptKey.end() == std::find(m_exceptKey.begin(),m_exceptKey.end(),key) )
return true;
else
return false;
}
void CIME::EnablePaste(bool bFlag)
{
m_bEnablePaste = bFlag;
}
// PORT: 40250 reads CF_TEXT from the Win32 clipboard. The host clipboard is not wired to the extension yet,
// so this pastes nothing (the same as an empty clipboard).
void CIME::PasteTextFromClipBoard()
{
if (!m_bEnablePaste)
return;
}
// PORT: 40250 cancels the IMM composition string and closes the candidate list. There is no composition
// here; the candidate-list close (and its event) is kept.
void CIME::FinalizeString(bool)
{
static bool s_bProcessing = false; // to avoid infinite recursion
if ( !ms_bInitialized || s_bProcessing )
return;
s_bProcessing = true;
CloseCandidateList();
s_bProcessing = false;
}
int CIME::GetCompLen()
{
return ms_compLen;
}
int CIME::GetULBegin()
{
return ms_ulbegin;
}
int CIME::GetULEnd()
{
return ms_ulend;
}
void CIME::CloseCandidateList()
{
ms_bCandidateList = false;
ms_dwCandidateCount = 0;
memset(&ms_wszCandidate, 0, sizeof(ms_wszCandidate));
if(ms_pEvent)
ms_pEvent->OnCloseCandidateList();
}
void CIME::CloseReadingInformation()
{
CIME::ms_bReadingInformation = false;
if(CIME::ms_pEvent)
CIME::ms_pEvent->OnCloseReadingWnd();
}
// PORT: 40250 re-reads the keyboard layout (GETLANG) and re-applies the IME support level when the language
// changed. The host has one fixed input locale, so only the toggle check and the code-page event remain.
void CIME::ChangeInputLanguage()
{
CheckToggleState();
ChangeInputLanguageWorker();
if(ms_pEvent)
ms_pEvent->OnChangeCodePage();
}
void CIME::ChangeInputLanguageWorker()
{
if ( !ms_bUILessMode )
ms_iCandListIndexBase = 1;
SetupImeApi();
}
// PORT: 40250 forces level 3 for the Korean keyboard layout; there is no keyboard layout here.
void CIME::SetSupportLevel( DWORD dwImeLevel )
{
if ( dwImeLevel < 2 || 3 < dwImeLevel )
return;
ms_dwIMELevel = dwImeLevel;
// cancel current composition string.
FinalizeString();
}
LRESULT CIME::WMInputLanguage(HWND, UINT, WPARAM, LPARAM)
{
ChangeInputLanguage();
return 0;
}
LRESULT CIME::WMStartComposition(HWND, UINT, WPARAM, LPARAM)
{
return 1L;
}
// PORT: 40250 pulls GCS_RESULTSTR/GCS_COMPSTR out of the IMM context. The host never sends compositions.
LRESULT CIME::WMComposition(HWND, UINT, WPARAM, LPARAM)
{
return 0;
}
LRESULT CIME::WMEndComposition(HWND, UINT, WPARAM, LPARAM)
{
ms_compLen = 0;
ms_ulbegin = 0;
ms_ulend = 0;
if(ms_pEvent)
ms_pEvent->OnUpdate();
return 0L;
}
// PORT: 40250 handles IMN_* candidate/reading/toggle notifications from IMM; none are sent here.
LRESULT CIME::WMNotify(HWND, UINT, WPARAM, LPARAM)
{
return 0;
}
LRESULT CIME::WMChar(HWND /*hWnd*/, UINT /*uiMsg*/, WPARAM wParam, LPARAM lParam)
{
unsigned char c = (unsigned char)(wParam & 0xff);
switch (c)
{
case 8:
if(ms_bCaptureInput == false)
return 0;
if (ms_curpos > 0)
{
DecCurPos();
DelCurPos();
}
if(ms_pEvent)
ms_pEvent->OnUpdate();
return 0;
break;
default:
if(ms_pEvent) {
if (ms_pEvent->OnWM_CHAR(wParam, lParam))
break;
}
if(ms_bCaptureInput == false)
return 0;
wchar_t w[10];
MultiByteToWideChar(ms_uInputCodePage, 0, (char*)&c, 1, w, 1);
OnChar(w[0]);
if (w[0] == L'|')
OnChar(w[0]);
if(ms_pEvent)
ms_pEvent->OnUpdate();
break;
}
return 0;
}
/*---------------------------------------------------------------------------*/ /* Protected */
void CIME::IncCurPos()
{
if (ms_curpos < ms_lastpos)
{
int pos = FindColorTagEndPosition(m_wText + ms_curpos, ms_lastpos - ms_curpos);
if (pos > 0)
ms_curpos = std::min(ms_lastpos, std::max(0, ms_curpos + (pos + 1)));
else
++ms_curpos;
//++ms_curpos;
}
}
void CIME::DecCurPos()
{
if (ms_curpos > 0)
{
int pos = FindColorTagStartPosition(m_wText + ms_curpos - 1, ms_curpos);
if (pos > 0)
ms_curpos = std::min(ms_lastpos, std::max(0, ms_curpos - (pos + 1)));
else
--ms_curpos;
//--ms_curpos;
}
}
int CIME::GetCurPos()
{
int pos = GetTextTagOutputLen(m_wText, ms_curpos);
return pos;
//return ms_curpos;
}
void CIME::SetCurPos(int offset)
{
if (offset < 0 || offset > ms_lastpos)
{
ms_curpos = ms_lastpos;
return;
}
else
{
// offset is a position in the rendered text, so it has to be mapped back to the buffer.
//ms_curpos = min(ms_lastpos, offset);
ms_curpos = std::min(ms_lastpos, GetTextTagInternalPosFromRenderPos(m_wText, ms_lastpos, offset));
}
}
void CIME::DelCurPos()
{
if (ms_curpos < ms_lastpos)
{
int eraseCount = FindColorTagEndPosition(m_wText + ms_curpos, ms_lastpos - ms_curpos) + 1;
// PORT: 40250 wcscpy()s the overlapping tail down; that is undefined for overlapping buffers, and the
// buffer is not guaranteed NUL-terminated at ms_lastpos, so move exactly the live tail.
memmove(m_wText + ms_curpos, m_wText + ms_curpos + eraseCount, sizeof(wchar_t) * (ms_lastpos - ms_curpos - eraseCount));
ms_lastpos -= eraseCount;
ms_curpos = std::min(ms_lastpos, ms_curpos);
}
}
void CIME::PasteString(const char * str)
{
const char * begin = str;
const char * end = str + strlen(str);
wchar_t m_wText[IMESTR_MAXLEN];
int wstrLen = MultiByteToWideChar(ms_uInputCodePage, 0, begin, end - begin, m_wText, IMESTR_MAXLEN);
InsertString(m_wText, wstrLen);
if(ms_pEvent)
ms_pEvent->OnUpdate();
}
// PORT: 40250 reads the keyboard layout's default ANSI code page (GetLocaleInfoA LOCALE_IDEFAULTANSICODEPAGE).
// The host's input locale is the client locale, so its code page (SetDefaultCodePage from locale.cfg) is used.
void CIME::CheckInputLocale()
{
static UINT s_uPrevCodePage = 0xFFFF;
ms_uInputCodePage = GetDefaultCodePage();
if ( s_uPrevCodePage == ms_uInputCodePage )
return;
s_uPrevCodePage = ms_uInputCodePage;
ms_bVerticalCandidate = false;
ms_wszCurrentIndicator = s_aszNonImeIndicator;
if(ms_uOutputCodePage != 1256) {
ms_uOutputCodePage = ms_uInputCodePage;
Clear();
}
}
// PORT: 40250 asks IMM whether an IME is open; there is none, so the state is IMEUI_STATE_OFF (0).
void CIME::CheckToggleState()
{
CheckInputLocale();
ms_bChineseIME = false;
ms_dwImeState = 0;
}
/*---------------------------------------------------------------------------*/ /* Private */
void CIME::InsertString(wchar_t* wString, int iSize)
{
if (IsMax(wString, iSize))
return;
if (ms_curpos < ms_lastpos)
memmove(m_wText+ms_curpos+iSize, m_wText+ms_curpos, sizeof(wchar_t)*(ms_lastpos-ms_curpos));
memcpy(m_wText+ms_curpos, wString, sizeof(wchar_t)*iSize);
ms_curpos += iSize;
ms_lastpos += iSize;
}
void CIME::OnChar(wchar_t c)
{
if (m_bOnlyNumberMode)
if (!iswdigit(c))
return;
if (!__IsWritable(c))
return;
InsertString(&c, 1);
}
// PORT: 40250 maps a keyboard-layout LANGID to its ANSI code page. Only CheckInputLocale's code page is used
// here (see there), so this answers with it.
UINT CIME::GetCodePageFromLang(LANGID)
{
return GetDefaultCodePage();
}
// PORT: the IMM composition/candidate/reading processors (40250 IME.cpp:951-1227). No IMM context exists.
void CIME::ResultProcess(HIMC) {}
void CIME::CompositionProcessBuilding(HIMC) {}
void CIME::CompositionProcess(HIMC) {}
void CIME::AttributeProcess(HIMC) {}
void CIME::CandidateProcess(HIMC) {}
void CIME::ReadingProcess(HIMC) {}
bool CIME::IsMax(const wchar_t* wInput, int len)
{
if (ms_lastpos + len > IMESTR_MAXLEN)
return true;
int textLen = WideCharToMultiByte(ms_uOutputCodePage, 0, m_wText, ms_lastpos, 0, 0, NULL, NULL);
int inputLen = WideCharToMultiByte(ms_uOutputCodePage, 0, wInput, len, 0, 0, NULL, NULL);
//return textLen + inputLen > m_max;
if (textLen + inputLen > m_max)
return true;
else if (m_userMax != 0 && m_max != m_userMax)
{
std::wstring str = GetTextTagOutputString(m_wText, ms_lastpos);
std::wstring input = GetTextTagOutputString(wInput, len);
int textLen = WideCharToMultiByte(ms_uOutputCodePage, 0, str.c_str(), str.length(), 0, 0, NULL, NULL);
int inputLen = WideCharToMultiByte(ms_uOutputCodePage, 0, input.c_str(), input.length(), 0, 0, NULL, NULL);
return textLen + inputLen > m_userMax;
}
return false;
}
// PORT: 40250 identifies the CHT/CHS IME DLL version and the reading-window orientation. No IME DLL here.
DWORD CIME::GetImeId(UINT)
{
return 0;
}
bool CIME::GetReadingWindowOrientation()
{
return true;
}
void CIME::SetupImeApi()
{
_GetReadingString = NULL;
_ShowReadingWindow = NULL;
}
decltype(CIME::_ImmLockIMC) CIME::_ImmLockIMC{};
decltype(CIME::_ImmUnlockIMC) CIME::_ImmUnlockIMC{};
decltype(CIME::_ImmLockIMCC) CIME::_ImmLockIMCC{};
decltype(CIME::_ImmUnlockIMCC) CIME::_ImmUnlockIMCC{};
decltype(CIME::_GetReadingString) CIME::_GetReadingString{};
decltype(CIME::_ShowReadingWindow) CIME::_ShowReadingWindow{};
decltype(CIME::ms_bInitialized) CIME::ms_bInitialized{};
decltype(CIME::ms_bDisableIMECompletely) CIME::ms_bDisableIMECompletely{};
decltype(CIME::ms_bUILessMode) CIME::ms_bUILessMode{};
decltype(CIME::ms_bImeEnabled) CIME::ms_bImeEnabled{};
decltype(CIME::ms_bCaptureInput) CIME::ms_bCaptureInput{};
decltype(CIME::ms_bChineseIME) CIME::ms_bChineseIME{};
decltype(CIME::ms_bUseIMMCandidate) CIME::ms_bUseIMMCandidate{};
decltype(CIME::ms_hWnd) CIME::ms_hWnd{};
decltype(CIME::ms_hklCurrent) CIME::ms_hklCurrent{};
decltype(CIME::ms_szKeyboardLayout) CIME::ms_szKeyboardLayout{};
decltype(CIME::ms_stOSVI) CIME::ms_stOSVI{};
decltype(CIME::ms_hImm32Dll) CIME::ms_hImm32Dll{};
decltype(CIME::ms_hCurrentImeDll) CIME::ms_hCurrentImeDll{};
decltype(CIME::ms_dwImeState) CIME::ms_dwImeState{};
decltype(CIME::ms_adwId) CIME::ms_adwId{};
decltype(CIME::ms_dwIMELevel) CIME::ms_dwIMELevel{};
decltype(CIME::ms_dwIMELevelSaved) CIME::ms_dwIMELevelSaved{};
decltype(CIME::ms_bCandidateList) CIME::ms_bCandidateList{};
decltype(CIME::ms_dwCandidateCount) CIME::ms_dwCandidateCount{};
decltype(CIME::ms_bVerticalCandidate) CIME::ms_bVerticalCandidate{};
decltype(CIME::ms_iCandListIndexBase) CIME::ms_iCandListIndexBase{};
decltype(CIME::ms_wszCandidate) CIME::ms_wszCandidate{};
decltype(CIME::ms_dwCandidateSelection) CIME::ms_dwCandidateSelection{};
decltype(CIME::ms_dwCandidatePageSize) CIME::ms_dwCandidatePageSize{};
decltype(CIME::ms_bReadingInformation) CIME::ms_bReadingInformation{};
decltype(CIME::ms_iReadingError) CIME::ms_iReadingError{};
decltype(CIME::ms_bHorizontalReading) CIME::ms_bHorizontalReading{};
decltype(CIME::ms_wstrReading) CIME::ms_wstrReading{};
decltype(CIME::ms_wszCurrentIndicator) CIME::ms_wszCurrentIndicator{};
decltype(CIME::ms_pEvent) CIME::ms_pEvent{};
decltype(CIME::m_wText) CIME::m_wText{};
decltype(CIME::ms_compLen) CIME::ms_compLen{};
decltype(CIME::ms_curpos) CIME::ms_curpos{};
decltype(CIME::ms_lastpos) CIME::ms_lastpos{};
decltype(CIME::ms_ulbegin) CIME::ms_ulbegin{};
decltype(CIME::ms_ulend) CIME::ms_ulend{};
decltype(CIME::ms_uOutputCodePage) CIME::ms_uOutputCodePage{};
decltype(CIME::ms_uInputCodePage) CIME::ms_uInputCodePage{};
+81
View File
@@ -0,0 +1,81 @@
// Platform skeleton for EterLib/Input.h (40250 EterLib/Input.cpp), generated by platform_stub.py.
// Every MT_PLATFORM_STUB() body is unimplemented: replace it with the platform implementation.
#include "EterLib/StdAfx.h"
#include "EterLib/Input.h"
#include "../PlatformStub.h"
CInputDevice::CInputDevice()
{
MT_PLATFORM_STUB();
}
CInputDevice::~CInputDevice()
{
MT_PLATFORM_STUB();
}
auto CInputDevice::CreateDevice(HWND) -> HRESULT
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<HRESULT>();
}
decltype(CInputDevice::ms_lpDI) CInputDevice::ms_lpDI{};
CInputKeyboard::CInputKeyboard()
{
MT_PLATFORM_STUB();
}
CInputKeyboard::~CInputKeyboard()
{
MT_PLATFORM_STUB();
}
auto CInputKeyboard::InitializeKeyboard(HWND) -> bool
{
ResetKeyboard();
return true;
}
auto CInputKeyboard::UpdateKeyboard() -> void
{
}
auto CInputKeyboard::ResetKeyboard() -> void
{
memset(ms_bPressedKey, 0, sizeof(ms_bPressedKey));
memset(ms_diks, 0, sizeof(ms_diks));
}
auto CInputKeyboard::IsPressed(int iIndex) -> bool
{
if (iIndex >= 0 && iIndex < 256)
return (ms_diks[iIndex] & 0x80) != 0;
return false;
}
auto CInputKeyboard::KeyDown(int iIndex) -> void
{
if (iIndex >= 0 && iIndex < 256)
{
ms_bPressedKey[iIndex] = true;
ms_diks[iIndex] = (char)0x80;
}
}
auto CInputKeyboard::KeyUp(int iIndex) -> void
{
if (iIndex >= 0 && iIndex < 256)
{
ms_bPressedKey[iIndex] = false;
ms_diks[iIndex] = 0;
}
}
decltype(CInputKeyboard::ms_lpKeyboard) CInputKeyboard::ms_lpKeyboard{};
decltype(CInputKeyboard::ms_bPressedKey) CInputKeyboard::ms_bPressedKey{};
decltype(CInputKeyboard::ms_diks) CInputKeyboard::ms_diks{};
+49
View File
@@ -0,0 +1,49 @@
// Platform skeleton for EterLib/MSApplication.h (40250 EterLib/MSApplication.cpp), generated by platform_stub.py.
// Every MT_PLATFORM_STUB() body is unimplemented: replace it with the platform implementation.
#include "EterLib/StdAfx.h"
#include "EterLib/MSApplication.h"
#include "../PlatformStub.h"
CMSApplication::CMSApplication()
{
MT_PLATFORM_STUB();
}
CMSApplication::~CMSApplication()
{
MT_PLATFORM_STUB();
}
auto CMSApplication::Initialize(HINSTANCE) -> void
{
MT_PLATFORM_STUB();
}
auto CMSApplication::MessageLoop() -> void
{
MT_PLATFORM_STUB();
}
auto CMSApplication::IsMessage() -> bool
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<bool>();
}
auto CMSApplication::MessageProcess() -> bool
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<bool>();
}
auto CMSApplication::ClearWindowClass() -> void
{
MT_PLATFORM_STUB();
}
auto CMSApplication::WindowProcedure(HWND, UINT, WPARAM, LPARAM) -> LRESULT
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<LRESULT>();
}
+150
View File
@@ -0,0 +1,150 @@
// Platform skeleton for EterLib/MSWindow.h (40250 EterLib/MSWindow.cpp), generated by platform_stub.py.
// Every MT_PLATFORM_STUB() body is unimplemented: replace it with the platform implementation.
#include "EterLib/StdAfx.h"
#include "EterLib/MSWindow.h"
#include "../PlatformStub.h"
#include "HostCursor.h"
CMSWindow::CMSWindow()
{
MT_PLATFORM_STUB();
}
CMSWindow::~CMSWindow()
{
MT_PLATFORM_STUB();
}
auto CMSWindow::Destroy() -> void
{
MT_PLATFORM_STUB();
}
auto CMSWindow::Create(const char *, int, DWORD, DWORD, HICON, int) -> bool
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<bool>();
}
auto CMSWindow::Show() -> void
{
MT_PLATFORM_STUB();
}
auto CMSWindow::Hide() -> void
{
MT_PLATFORM_STUB();
}
auto CMSWindow::SetVisibleMode(bool) -> void
{
MT_PLATFORM_STUB();
}
auto CMSWindow::SetPosition(int, int) -> void
{
MT_PLATFORM_STUB();
}
auto CMSWindow::SetCenterPosition() -> void
{
MT_PLATFORM_STUB();
}
auto CMSWindow::SetText(const char *) -> void
{
MT_PLATFORM_STUB();
}
auto CMSWindow::AdjustSize(int, int) -> void
{
MT_PLATFORM_STUB();
}
auto CMSWindow::SetSize(int, int) -> void
{
MT_PLATFORM_STUB();
}
auto CMSWindow::IsVisible() -> bool
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<bool>();
}
auto CMSWindow::IsActive() -> bool
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<bool>();
}
namespace {
POINT g_host_cursor = {0, 0};
}
void MtHostSetCursor(int x, int y)
{
g_host_cursor.x = x;
g_host_cursor.y = y;
}
auto CMSWindow::GetMousePosition(POINT * ppt) -> void
{
*ppt = g_host_cursor;
}
auto CMSWindow::GetClientRect(RECT *) -> void
{
MT_PLATFORM_STUB();
}
auto CMSWindow::GetWindowRect(RECT *) -> void
{
MT_PLATFORM_STUB();
}
auto CMSWindow::GetScreenWidth() -> int
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<int>();
}
auto CMSWindow::GetScreenHeight() -> int
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<int>();
}
auto CMSWindow::GetWindowHandle() -> HWND
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<HWND>();
}
auto CMSWindow::GetInstance() -> HINSTANCE
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<HINSTANCE>();
}
auto CMSWindow::WindowProcedure(HWND, UINT, WPARAM, LPARAM) -> LRESULT
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<LRESULT>();
}
auto CMSWindow::OnSize(WPARAM, LPARAM) -> void
{
MT_PLATFORM_STUB();
}
auto CMSWindow::RegisterWindowClass(DWORD, int, WNDPROC, HICON, int) -> const char *
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<const char *>();
}
decltype(CMSWindow::ms_stWCSet) CMSWindow::ms_stWCSet{};
decltype(CMSWindow::ms_hInstance) CMSWindow::ms_hInstance{};
+32
View File
@@ -0,0 +1,32 @@
// Platform skeleton for EterLib/Mutex.h (40250 EterLib/Mutex.cpp), generated by platform_stub.py.
// Every MT_PLATFORM_STUB() body is unimplemented: replace it with the platform implementation.
#include "EterLib/StdAfx.h"
#include "EterLib/Mutex.h"
#include "../PlatformStub.h"
Mutex::Mutex()
{
MT_PLATFORM_STUB();
}
Mutex::~Mutex()
{
MT_PLATFORM_STUB();
}
auto Mutex::Lock() -> void
{
MT_PLATFORM_STUB();
}
auto Mutex::Unlock() -> void
{
MT_PLATFORM_STUB();
}
auto Mutex::Trylock() -> bool
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<bool>();
}
File diff suppressed because it is too large Load Diff
+7
View File
@@ -0,0 +1,7 @@
#pragma once
// The platform's IDirect3DDevice8: CGraphicDevice::Create hands it to CStateManager, which keeps
// 40250's state caching; the device remembers the state it is given and turns every draw call into a
// Render3DDraw (RenderCommands3D.h) for the Godot renderer.
#include "EterLib/StdAfx.h"
IDirect3DDevice8* MtCreateRecordingDevice(int width, int height);
+141
View File
@@ -0,0 +1,141 @@
#pragma once
#include <cstdint>
#include <string>
#include <vector>
// The 3D draw calls the ported game render (CPythonApplication::RenderGame) issues through
// CStateManager, recorded by the platform's IDirect3DDevice8 (RecordingDevice.cpp) and consumed by
// Godot. Like UIRenderCommands.h this header stays free of D3D and godot-cpp types.
//
// Matrices are D3D8's row-vector layout (translation in elements 12..14), exactly as 40250 set them.
struct Render3DDraw {
// Stable source-buffer identity and content version. Zero key means an immediate-mode draw
// without a reusable D3D buffer. Geometry may be reused only while both values match.
std::uint64_t geometry_key = 0;
std::uint64_t geometry_revision = 0;
float world[16];
float view[16];
float proj[16];
float viewport[4] = {}; // x, y, width, height
float viewport_z[2] = {0, 1}; // MinZ, MaxZ
// PORT: UIRenderOffsetX() when recorded (a draw from a shifted window layer); the host moves the
// viewport (and a pretransformed draw's screen positions) right by it.
float ui_offset_x = 0;
// IDirect3DDevice8::Clear on the back buffer, kept in draw order. A clear entry has no geometry;
// clear_flags holds D3DCLEAR_TARGET / D3DCLEAR_ZBUFFER / D3DCLEAR_STENCIL.
std::uint32_t clear_flags = 0;
std::uint32_t clear_color = 0; // 0xAARRGGBB
float clear_z = 1;
// Non-zero: the draw (or clear) targets an offscreen render-target texture instead of the back
// buffer -- the 40250 character shadow map. The renderer draws these into the texture named
// Render3DRenderTargetName(render_target, ...) ahead of the back-buffer pass, in recorded order.
// viewport is then in the target's pixels. Only emitted while GPU render targets are enabled.
std::uint32_t render_target = 0;
std::uint32_t target_width = 0, target_height = 0;
// Stage 0/1 textures, named like UIRenderTextureName: the pack path of a file texture or
// "mem:<id>@<revision>"; empty when the stage has no texture.
std::string texture0;
std::string texture1;
// The referenced vertices, rebased so indices start at 0. normals/uv0/uv1/diffuse are empty when
// the vertex format has no such element. pretransformed: D3DFVF_XYZRHW (screen-space x, y, z, rhw
// in positions + rhw).
bool pretransformed = false;
std::vector<float> positions; // x, y, z
std::vector<float> rhw;
// D3D8 vertex fog of an XYZRHW draw: the D3DFVF_SPECULAR alpha (0..1); empty otherwise.
std::vector<float> vertex_fog;
std::vector<float> normals; // x, y, z
std::vector<float> uv0; // u, v
std::vector<float> uv1; // u, v
std::vector<std::uint32_t> diffuse; // 0xAARRGGBB
std::vector<std::uint32_t> indices; // triangle list (strips and fans are expanded), or line list
std::vector<std::uint8_t> bone_indices; // 4 uint8 per vertex (mesh-local bone palette index)
std::vector<float> bone_weights; // 4 floats per vertex
std::vector<float> bone_matrices; // 16 floats per bone in the mesh's palette (D3D row-vector layout)
bool lines = false;
// D3DRS_* / D3DTSS_* values in effect for the draw.
std::uint32_t alpha_blend = 0, src_blend = 0, dest_blend = 0;
std::uint32_t alpha_test = 0, alpha_ref = 0, alpha_func = 0;
std::uint32_t cull_mode = 0, z_enable = 0, z_write = 0, z_func = 0;
std::uint32_t lighting = 0, texture_factor = 0, fog_enable = 0;
std::uint32_t fog_color = 0, fog_vertex_mode = 0, fog_table_mode = 0, fog_range_enable = 0;
float fog_start = 0, fog_end = 0, fog_density = 0;
std::uint32_t color_op[2] = {}, color_arg1[2] = {}, color_arg2[2] = {};
std::uint32_t alpha_op[2] = {}, alpha_arg1[2] = {}, alpha_arg2[2] = {};
std::uint32_t address_u[2] = {}, address_v[2] = {};
std::uint32_t min_filter[2] = {}, mag_filter[2] = {}, mip_filter[2] = {};
std::uint32_t border_color[2] = {};
// D3DTSS_TEXCOORDINDEX (set index | D3DTSS_TCI_* generation mode), D3DTSS_TEXTURETRANSFORMFLAGS and
// D3DTS_TEXTURE0/1 per stage. The renderer generates and transforms texture coordinates from
// these the way the D3D8 fixed-function vertex pipeline does; uv0/uv1 stay the raw vertex sets.
std::uint32_t texcoord_index[2] = {0, 1};
std::uint32_t texture_transform_flags[2] = {};
float texture_matrix[2][16] = {{1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1},
{1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1}};
// D3DMATERIAL8 diffuse/ambient/emissive (r, g, b, a) and light 0 when enabled.
float material_diffuse[4] = {1, 1, 1, 1};
float material_ambient[4] = {};
float material_emissive[4] = {};
bool light0 = false;
float light0_direction[3] = {};
float light0_diffuse[4] = {};
float light0_ambient[4] = {};
std::uint32_t ambient = 0; // D3DRS_AMBIENT
struct Light {
std::uint32_t type = 0; // zero when disabled; D3DLIGHT_POINT/SPOT/DIRECTIONAL otherwise
float position[3] = {};
float direction[3] = {};
float diffuse[4] = {};
float ambient[4] = {};
float attenuation[3] = {};
float range = 0;
float theta = 0, phi = 0, falloff = 0;
} lights[8];
std::uint32_t diffuse_material_source = 0;
std::uint32_t ambient_material_source = 0;
std::uint32_t emissive_material_source = 0;
std::uint32_t color_vertex = 0;
std::uint32_t normalize_normals = 0; // D3DRS_NORMALIZENORMALS
std::uint32_t local_viewer = 1; // D3DRS_LOCALVIEWER
};
// The texture coordinates stage 0/1 samples at each vertex, computed on the CPU with the same
// D3D8 fixed-function rules the native renderer's vertex shader applies (TEXCOORDINDEX generation,
// then D3DTS_TEXTUREn under TEXTURETRANSFORMFLAGS). For consumers without that shader (Godot).
void Render3DStageTexcoords(const Render3DDraw& draw, int stage, std::vector<float>& out);
struct GpuSkinSubrangeView {
std::uint64_t source_mesh_key = 0;
std::uint32_t mesh_base_vertex = 0;
std::uint32_t mesh_vertex_count = 0;
const std::uint8_t* bone_indices = nullptr; // mesh_vertex_count * 4
const float* bone_weights = nullptr; // mesh_vertex_count * 4
const float* bone_matrices = nullptr; // bone_count * 16
std::uint32_t bone_count = 0;
};
void SetNativeTerrainRenderEnabled(bool enabled);
bool IsNativeTerrainRenderEnabled();
void SetGpuSkinningEnabled(bool enabled);
bool IsGpuSkinningEnabled();
bool LookupGpuSkinSubrange(const void* vertex_buffer_base, std::uint32_t stride,
std::uint32_t lo_vertex, std::uint32_t hi_vertex,
GpuSkinSubrangeView* out_view);
// GPU render targets: shadow-map draws are recorded with render_target set and sampled as
// "rt:<id>:<w>x<h>" instead of being rasterized on the CPU into a "mem:cpu_<id>" texture. Off by
// default (the Godot consumer has no offscreen pass); the native Vulkan renderer turns it on.
void SetGpuRenderTargetsEnabled(bool enabled);
bool IsGpuRenderTargetsEnabled();
std::string Render3DRenderTargetName(std::uint32_t id, std::uint32_t width, std::uint32_t height);
void Render3DBeginFrame();
void Render3DAdd(Render3DDraw draw);
const std::vector<Render3DDraw>& Render3DDraws();
+787
View File
@@ -0,0 +1,787 @@
// Platform implementation of EterLib/SkyBox.cpp (40250 EterLib/SkyBox.cpp).
#include "EterLib/StdAfx.h"
#include "EterLib/SkyBox.h"
#include "EterLib/Camera.h"
#include "EterLib/StateManager.h"
#include "EterLib/ResourceManager.h"
#include "EterBase/Timer.h"
#include "RenderCommands3D.h"
CSkyObjectQuad::CSkyObjectQuad()
{
m_Indices[0] = 0;
m_Indices[1] = 2;
m_Indices[2] = 1;
m_Indices[3] = 3;
for (unsigned char uci = 0; uci < 4; ++uci)
{
memset(&m_Vertex[uci], 0, sizeof(TPDTVertex));
}
}
CSkyObjectQuad::~CSkyObjectQuad()
{
}
void CSkyObjectQuad::Clear(const unsigned char & c_rucNumVertex,
const float & c_rfRed,
const float & c_rfGreen,
const float & c_rfBlue,
const float & c_rfAlpha)
{
if (c_rucNumVertex > 3)
return;
m_Helper[c_rucNumVertex].Clear(c_rfRed, c_rfGreen, c_rfBlue, c_rfAlpha);
}
void CSkyObjectQuad::SetSrcColor(const unsigned char & c_rucNumVertex,
const float & c_rfRed,
const float & c_rfGreen,
const float & c_rfBlue,
const float & c_rfAlpha)
{
if (c_rucNumVertex > 3)
return;
m_Helper[c_rucNumVertex].SetSrcColor(c_rfRed, c_rfGreen, c_rfBlue, c_rfAlpha);
}
void CSkyObjectQuad::SetTransition(const unsigned char & c_rucNumVertex,
const float & c_rfRed,
const float & c_rfGreen,
const float & c_rfBlue,
const float & c_rfAlpha,
DWORD dwDuration)
{
if (c_rucNumVertex > 3)
return;
m_Helper[c_rucNumVertex].SetTransition(c_rfRed, c_rfGreen, c_rfBlue, c_rfAlpha, dwDuration);
}
void CSkyObjectQuad::SetVertex(const unsigned char & c_rucNumVertex, const TPDTVertex & c_rPDTVertex)
{
if (c_rucNumVertex > 3)
return;
memcpy(&m_Vertex[m_Indices[c_rucNumVertex]], &c_rPDTVertex, sizeof(TPDTVertex));
}
void CSkyObjectQuad::StartTransition()
{
for (unsigned char uci = 0; uci < 4; ++uci)
{
m_Helper[uci].StartTransition();
}
}
bool CSkyObjectQuad::Update()
{
bool bResult = false;
for (unsigned char uci = 0; uci < 4; ++uci)
{
bResult = m_Helper[uci].Update() || bResult;
m_Vertex[m_Indices[uci]].diffuse = m_Helper[uci].GetCurColor();
}
return bResult;
}
void CSkyObjectQuad::Render()
{
if (CGraphicBase::SetPDTStream(m_Vertex, 4))
STATEMANAGER.DrawPrimitive(D3DPT_TRIANGLESTRIP, 0, 2);
}
CSkyObject::CSkyObject() :
m_v3Position(0.0f, 0.0f, 0.0f),
m_fScaleX(1.0f),
m_fScaleY(1.0f),
m_fScaleZ(1.0f)
{
D3DXMatrixIdentity(&m_matWorld);
D3DXMatrixIdentity(&m_matTranslation);
D3DXMatrixIdentity(&m_matWorldCloud);
D3DXMatrixIdentity(&m_matTranslationCloud);
D3DXMatrixIdentity(&m_matTextureCloud);
m_dwlastTime = CTimer::Instance().GetCurrentMillisecond();
m_fCloudPositionU = 0.0f;
m_fCloudPositionV = 0.0f;
m_fCloudScaleX = 1.0f;
m_fCloudScaleY = 1.0f;
m_fCloudHeight = 0.0f;
m_fCloudTextureScaleX = 1.0f;
m_fCloudTextureScaleY = 1.0f;
m_fCloudScrollSpeedU = 0.0f;
m_fCloudScrollSpeedV = 0.0f;
m_ucRenderMode = SKY_RENDER_MODE_DEFAULT;
m_bTransitionStarted = false;
m_bSkyMatrixUpdated = false;
}
CSkyObject::~CSkyObject()
{
}
void CSkyObject::Destroy()
{
}
void CSkyObject::Update()
{
CCamera* pCamera = CCameraManager::Instance().GetCurrentCamera();
if (!pCamera)
return;
D3DXVECTOR3 v3Eye = pCamera->GetEye();
if (m_v3Position == v3Eye)
if (m_bSkyMatrixUpdated == false)
return;
m_v3Position = v3Eye;
m_matWorld._41 = m_v3Position.x;
m_matWorld._42 = m_v3Position.y;
m_matWorld._43 = m_v3Position.z;
m_matWorldCloud._41 = m_v3Position.x;
m_matWorldCloud._42 = m_v3Position.y;
m_matWorldCloud._43 = m_v3Position.z + m_fCloudHeight;
if (m_bSkyMatrixUpdated)
m_bSkyMatrixUpdated = false;
}
void CSkyObject::Render()
{
}
void CSkyObject::StartTransition()
{
}
CGraphicImageInstance * CSkyObject::GenerateTexture(const char * szfilename)
{
if (!szfilename || !*szfilename)
return NULL;
CResource * pResource = CResourceManager::Instance().GetResourcePointer(szfilename);
if (!pResource || !pResource->IsType(CGraphicImage::Type()))
return NULL;
CGraphicImageInstance * pImageInstance = CGraphicImageInstance::New();
pImageInstance->SetImagePointer(static_cast<CGraphicImage *>(pResource));
return pImageInstance;
}
void CSkyObject::DeleteTexture(CGraphicImageInstance * pImageInstance)
{
if (pImageInstance)
CGraphicImageInstance::Delete(pImageInstance);
}
void CSkyObject::TSkyObjectFace::StartTransition()
{
for (unsigned char uci = 0; uci < m_SkyObjectQuadVector.size(); ++uci)
{
m_SkyObjectQuadVector[uci].StartTransition();
}
}
bool CSkyObject::TSkyObjectFace::Update()
{
bool bResult = false;
for (DWORD dwi = 0; dwi < m_SkyObjectQuadVector.size(); ++dwi)
bResult = m_SkyObjectQuadVector[dwi].Update() || bResult;
return bResult;
}
void CSkyObject::TSkyObjectFace::Render()
{
for (unsigned char uci = 0; uci < m_SkyObjectQuadVector.size(); ++uci)
{
m_SkyObjectQuadVector[uci].Render();
}
}
CSkyBox::CSkyBox()
{
m_ucVirticalGradientLevelUpper = 0;
m_ucVirticalGradientLevelLower = 0;
}
CSkyBox::~CSkyBox()
{
Destroy();
}
void CSkyBox::Destroy()
{
Unload();
}
void CSkyBox::Unload()
{
TGraphicImageInstanceMap::iterator itor = m_GraphicImageInstanceMap.begin();
while (itor != m_GraphicImageInstanceMap.end())
{
DeleteTexture(itor->second);
++itor;
}
m_GraphicImageInstanceMap.clear();
}
void CSkyBox::SetSkyBoxScale(const D3DXVECTOR3 & c_rv3Scale)
{
m_fScaleX = c_rv3Scale.x;
m_fScaleY = c_rv3Scale.y;
m_fScaleZ = c_rv3Scale.z;
m_bSkyMatrixUpdated = true;
D3DXMatrixScaling(&m_matWorld, m_fScaleX, m_fScaleY, m_fScaleZ);
}
void CSkyBox::SetGradientLevel(BYTE byUpper, BYTE byLower)
{
m_ucVirticalGradientLevelUpper = byUpper;
m_ucVirticalGradientLevelLower = byLower;
}
void CSkyBox::SetFaceTexture(const char* c_szFileName, int iFaceIndex)
{
if (iFaceIndex < 0 || iFaceIndex > 5 || !c_szFileName || !*c_szFileName)
return;
TGraphicImageInstanceMap::iterator itor = m_GraphicImageInstanceMap.find(c_szFileName);
if (m_GraphicImageInstanceMap.end() != itor)
return;
m_Faces[iFaceIndex].m_strFaceTextureFileName = c_szFileName;
CGraphicImageInstance * pGraphicImageInstance = GenerateTexture(c_szFileName);
m_GraphicImageInstanceMap.insert(TGraphicImageInstanceMap::value_type(c_szFileName, pGraphicImageInstance));
}
void CSkyBox::SetCloudTexture(const char * c_szFileName)
{
if (!c_szFileName || !*c_szFileName)
return;
TGraphicImageInstanceMap::iterator itor = m_GraphicImageInstanceMap.find(c_szFileName);
if (m_GraphicImageInstanceMap.end() != itor)
return;
m_FaceCloud.m_strfacename = c_szFileName;
CGraphicImageInstance * pGraphicImageInstance = GenerateTexture(c_szFileName);
m_GraphicImageInstanceMap.insert(TGraphicImageInstanceMap::value_type(m_FaceCloud.m_strfacename, pGraphicImageInstance));
}
void CSkyBox::SetCloudScale(const D3DXVECTOR2 & c_rv2CloudScale)
{
m_fCloudScaleX = c_rv2CloudScale.x;
m_fCloudScaleY = c_rv2CloudScale.y;
D3DXMatrixScaling(&m_matWorldCloud, m_fCloudScaleX, m_fCloudScaleY, 1.0f);
}
void CSkyBox::SetCloudHeight(float fHeight)
{
m_fCloudHeight = fHeight;
}
void CSkyBox::SetCloudTextureScale(const D3DXVECTOR2 & c_rv2CloudTextureScale)
{
m_fCloudTextureScaleX = c_rv2CloudTextureScale.x;
m_fCloudTextureScaleY = c_rv2CloudTextureScale.y;
m_matTextureCloud._11 = m_fCloudTextureScaleX;
m_matTextureCloud._22 = m_fCloudTextureScaleY;
}
void CSkyBox::SetCloudScrollSpeed(const D3DXVECTOR2 & c_rv2CloudScrollSpeed)
{
m_fCloudScrollSpeedU = c_rv2CloudScrollSpeed.x;
m_fCloudScrollSpeedV = c_rv2CloudScrollSpeed.y;
}
void CSkyBox::SetSkyObjectQuadVertical(TSkyObjectQuadVector * pSkyObjectQuadVector, const D3DXVECTOR2 * c_pv2QuadPoints)
{
TPDTVertex aPDTVertex;
DWORD dwIndex = 0;
pSkyObjectQuadVector->clear();
pSkyObjectQuadVector->resize(m_ucVirticalGradientLevelUpper + m_ucVirticalGradientLevelLower);
unsigned char ucY;
for (ucY = 0; ucY < m_ucVirticalGradientLevelUpper; ++ucY)
{
CSkyObjectQuad & rSkyObjectQuad = pSkyObjectQuadVector->at(dwIndex++);
aPDTVertex.position.x = c_pv2QuadPoints[0].x;
aPDTVertex.position.y = c_pv2QuadPoints[0].y;
aPDTVertex.position.z = 1.0f - (float)(ucY + 1) / (float)(m_ucVirticalGradientLevelUpper);
aPDTVertex.texCoord.x = 0.0f;
aPDTVertex.texCoord.y = (float)(ucY + 1) / (float)(m_ucVirticalGradientLevelUpper) * 0.5f;
rSkyObjectQuad.SetVertex(0, aPDTVertex);
aPDTVertex.position.x = c_pv2QuadPoints[0].x;
aPDTVertex.position.y = c_pv2QuadPoints[0].y;
aPDTVertex.position.z = 1.0f - (float)(ucY) / (float)(m_ucVirticalGradientLevelUpper);
aPDTVertex.texCoord.x = 0.0f;
aPDTVertex.texCoord.y = (float)(ucY) / (float)(m_ucVirticalGradientLevelUpper) * 0.5f;
rSkyObjectQuad.SetVertex(1, aPDTVertex);
aPDTVertex.position.x = c_pv2QuadPoints[1].x;
aPDTVertex.position.y = c_pv2QuadPoints[1].y;
aPDTVertex.position.z = 1.0f - (float)(ucY + 1) / (float)(m_ucVirticalGradientLevelUpper);
aPDTVertex.texCoord.x = 1.0f;
aPDTVertex.texCoord.y = (float)(ucY + 1) / (float)(m_ucVirticalGradientLevelUpper) * 0.5f;
rSkyObjectQuad.SetVertex(2, aPDTVertex);
aPDTVertex.position.x = c_pv2QuadPoints[1].x;
aPDTVertex.position.y = c_pv2QuadPoints[1].y;
aPDTVertex.position.z = 1.0f - (float)(ucY) / (float)(m_ucVirticalGradientLevelUpper);
aPDTVertex.texCoord.x = 1.0f;
aPDTVertex.texCoord.y = (float)(ucY) / (float)(m_ucVirticalGradientLevelUpper) * 0.5f;
rSkyObjectQuad.SetVertex(3, aPDTVertex);
}
for (ucY = 0; ucY < m_ucVirticalGradientLevelLower; ++ucY)
{
CSkyObjectQuad & rSkyObjectQuad = pSkyObjectQuadVector->at(dwIndex++);
aPDTVertex.position.x = c_pv2QuadPoints[0].x;
aPDTVertex.position.y = c_pv2QuadPoints[0].y;
aPDTVertex.position.z = -(float)(ucY + 1) / (float)(m_ucVirticalGradientLevelLower);
aPDTVertex.texCoord.x = 0.0f;
aPDTVertex.texCoord.y = 0.5f + (float)(ucY + 1) / (float)(m_ucVirticalGradientLevelUpper) * 0.5f;
rSkyObjectQuad.SetVertex(0, aPDTVertex);
aPDTVertex.position.x = c_pv2QuadPoints[0].x;
aPDTVertex.position.y = c_pv2QuadPoints[0].y;
aPDTVertex.position.z = -(float)(ucY) / (float)(m_ucVirticalGradientLevelLower);
aPDTVertex.texCoord.x = 0.0f;
aPDTVertex.texCoord.y = 0.5f + (float)(ucY) / (float)(m_ucVirticalGradientLevelUpper) * 0.5f;
rSkyObjectQuad.SetVertex(1, aPDTVertex);
aPDTVertex.position.x = c_pv2QuadPoints[1].x;
aPDTVertex.position.y = c_pv2QuadPoints[1].y;
aPDTVertex.position.z = -(float)(ucY + 1) / (float)(m_ucVirticalGradientLevelLower);
aPDTVertex.texCoord.x = 1.0f;
aPDTVertex.texCoord.y = 0.5f + (float)(ucY + 1) / (float)(m_ucVirticalGradientLevelUpper) * 0.5f;
rSkyObjectQuad.SetVertex(2, aPDTVertex);
aPDTVertex.position.x = c_pv2QuadPoints[1].x;
aPDTVertex.position.y = c_pv2QuadPoints[1].y;
aPDTVertex.position.z = -(float)(ucY) / (float)(m_ucVirticalGradientLevelLower);
aPDTVertex.texCoord.x = 1.0f;
aPDTVertex.texCoord.y = 0.5f + (float)(ucY) / (float)(m_ucVirticalGradientLevelUpper) * 0.5f;
rSkyObjectQuad.SetVertex(3, aPDTVertex);
}
}
void CSkyBox::SetSkyObjectQuadHorizon(TSkyObjectQuadVector * pSkyObjectQuadVector, const D3DXVECTOR3 * c_pv3QuadPoints)
{
pSkyObjectQuadVector->clear();
pSkyObjectQuadVector->resize(1);
CSkyObjectQuad & rSkyObjectQuad = pSkyObjectQuadVector->at(0);
TPDTVertex aPDTVertex{};
aPDTVertex.position = c_pv3QuadPoints[0];
aPDTVertex.texCoord.x = 0.0f;
aPDTVertex.texCoord.y = 1.0f;
rSkyObjectQuad.SetVertex(0, aPDTVertex);
aPDTVertex.position = c_pv3QuadPoints[1];
aPDTVertex.texCoord.x = 0.0f;
aPDTVertex.texCoord.y = 0.0f;
rSkyObjectQuad.SetVertex(1, aPDTVertex);
aPDTVertex.position = c_pv3QuadPoints[2];
aPDTVertex.texCoord.x = 1.0f;
aPDTVertex.texCoord.y = 1.0f;
rSkyObjectQuad.SetVertex(2, aPDTVertex);
aPDTVertex.position = c_pv3QuadPoints[3];
aPDTVertex.texCoord.x = 1.0f;
aPDTVertex.texCoord.y = 0.0f;
rSkyObjectQuad.SetVertex(3, aPDTVertex);
}
void CSkyBox::Refresh()
{
D3DXVECTOR3 v3QuadPoints[4];
if (m_ucRenderMode == CSkyObject::SKY_RENDER_MODE_DEFAULT || m_ucRenderMode == CSkyObject::SKY_RENDER_MODE_DIFFUSE)
{
if (m_ucVirticalGradientLevelUpper + m_ucVirticalGradientLevelLower <= 0)
return;
D3DXVECTOR2 v2QuadPoints[2];
v2QuadPoints[0] = D3DXVECTOR2(1.0f, -1.0f);
v2QuadPoints[1] = D3DXVECTOR2(-1.0f, -1.0f);
SetSkyObjectQuadVertical(&m_Faces[0].m_SkyObjectQuadVector, v2QuadPoints);
m_Faces[0].m_strfacename = "front";
v2QuadPoints[0] = D3DXVECTOR2(-1.0f, 1.0f);
v2QuadPoints[1] = D3DXVECTOR2(1.0f, 1.0f);
SetSkyObjectQuadVertical(&m_Faces[1].m_SkyObjectQuadVector, v2QuadPoints);
m_Faces[1].m_strfacename = "back";
v2QuadPoints[0] = D3DXVECTOR2(-1.0f, -1.0f);
v2QuadPoints[1] = D3DXVECTOR2(-1.0f, 1.0f);
SetSkyObjectQuadVertical(&m_Faces[2].m_SkyObjectQuadVector, v2QuadPoints);
m_Faces[2].m_strfacename = "left";
v2QuadPoints[0] = D3DXVECTOR2(1.0f, 1.0f);
v2QuadPoints[1] = D3DXVECTOR2(1.0f, -1.0f);
SetSkyObjectQuadVertical(&m_Faces[3].m_SkyObjectQuadVector, v2QuadPoints);
m_Faces[3].m_strfacename = "right";
v3QuadPoints[0] = D3DXVECTOR3(1.0f, 1.0f, 1.0f);
v3QuadPoints[1] = D3DXVECTOR3(-1.0f, 1.0f, 1.0f);
v3QuadPoints[2] = D3DXVECTOR3(1.0f, -1.0f, 1.0f);
v3QuadPoints[3] = D3DXVECTOR3(-1.0f, -1.0f, 1.0f);
SetSkyObjectQuadHorizon(&m_Faces[4].m_SkyObjectQuadVector, v3QuadPoints);
m_Faces[4].m_strfacename = "top";
v3QuadPoints[0] = D3DXVECTOR3(-1.0f, 1.0f, -1.0f);
v3QuadPoints[1] = D3DXVECTOR3(1.0f, 1.0f, -1.0f);
v3QuadPoints[2] = D3DXVECTOR3(-1.0f, -1.0f, -1.0f);
v3QuadPoints[3] = D3DXVECTOR3(1.0f, -1.0f, -1.0f);
SetSkyObjectQuadHorizon(&m_Faces[5].m_SkyObjectQuadVector, v3QuadPoints);
m_Faces[5].m_strfacename = "bottom";
}
else if (m_ucRenderMode == CSkyObject::SKY_RENDER_MODE_TEXTURE)
{
v3QuadPoints[0] = D3DXVECTOR3(1.0f, -1.0f, -1.0f);
v3QuadPoints[1] = D3DXVECTOR3(1.0f, -1.0f, 1.0f);
v3QuadPoints[2] = D3DXVECTOR3(-1.0f, -1.0f, -1.0f);
v3QuadPoints[3] = D3DXVECTOR3(-1.0f, -1.0f, 1.0f);
SetSkyObjectQuadHorizon(&m_Faces[0].m_SkyObjectQuadVector, v3QuadPoints);
m_Faces[0].m_strfacename = "front";
v3QuadPoints[0] = D3DXVECTOR3(-1.0f, 1.0f, -1.0f);
v3QuadPoints[1] = D3DXVECTOR3(-1.0f, 1.0f, 1.0f);
v3QuadPoints[2] = D3DXVECTOR3(1.0f, 1.0f, -1.0f);
v3QuadPoints[3] = D3DXVECTOR3(1.0f, 1.0f, 1.0f);
SetSkyObjectQuadHorizon(&m_Faces[1].m_SkyObjectQuadVector, v3QuadPoints);
m_Faces[1].m_strfacename = "back";
v3QuadPoints[0] = D3DXVECTOR3(1.0f, 1.0f, -1.0f);
v3QuadPoints[1] = D3DXVECTOR3(1.0f, 1.0f, 1.0f);
v3QuadPoints[2] = D3DXVECTOR3(1.0f, -1.0f, -1.0f);
v3QuadPoints[3] = D3DXVECTOR3(1.0f, -1.0f, 1.0f);
SetSkyObjectQuadHorizon(&m_Faces[2].m_SkyObjectQuadVector, v3QuadPoints);
m_Faces[2].m_strfacename = "left";
v3QuadPoints[0] = D3DXVECTOR3(-1.0f, -1.0f, -1.0f);
v3QuadPoints[1] = D3DXVECTOR3(-1.0f, -1.0f, 1.0f);
v3QuadPoints[2] = D3DXVECTOR3(-1.0f, 1.0f, -1.0f);
v3QuadPoints[3] = D3DXVECTOR3(-1.0f, 1.0f, 1.0f);
SetSkyObjectQuadHorizon(&m_Faces[3].m_SkyObjectQuadVector, v3QuadPoints);
m_Faces[3].m_strfacename = "right";
v3QuadPoints[0] = D3DXVECTOR3(1.0f, -1.0f, 1.0f);
v3QuadPoints[1] = D3DXVECTOR3(1.0f, 1.0f, 1.0f);
v3QuadPoints[2] = D3DXVECTOR3(-1.0f, -1.0f, 1.0f);
v3QuadPoints[3] = D3DXVECTOR3(-1.0f, 1.0f, 1.0f);
SetSkyObjectQuadHorizon(&m_Faces[4].m_SkyObjectQuadVector, v3QuadPoints);
m_Faces[4].m_strfacename = "top";
v3QuadPoints[0] = D3DXVECTOR3(1.0f, -1.0f, -1.0f);
v3QuadPoints[1] = D3DXVECTOR3(1.0f, 1.0f, -1.0f);
v3QuadPoints[2] = D3DXVECTOR3(-1.0f, -1.0f, -1.0f);
v3QuadPoints[3] = D3DXVECTOR3(-1.0f, 1.0f, -1.0f);
SetSkyObjectQuadHorizon(&m_Faces[5].m_SkyObjectQuadVector, v3QuadPoints);
m_Faces[5].m_strfacename = "bottom";
}
v3QuadPoints[0] = D3DXVECTOR3(1.0f, 1.0f, 0.0f);
v3QuadPoints[1] = D3DXVECTOR3(-1.0f, 1.0f, 0.0f);
v3QuadPoints[2] = D3DXVECTOR3(1.0f, -1.0f, 0.0f);
v3QuadPoints[3] = D3DXVECTOR3(-1.0f, -1.0f, 0.0f);
SetSkyObjectQuadHorizon(&m_FaceCloud.m_SkyObjectQuadVector, v3QuadPoints);
}
void CSkyBox::SetCloudColor(const TGradientColor & c_rColor, const TGradientColor & c_rNextColor, const DWORD & dwTransitionTime)
{
TSkyObjectFace & aFaceCloud = m_FaceCloud;
for (DWORD dwk = 0; dwk < aFaceCloud.m_SkyObjectQuadVector.size(); ++dwk)
{
CSkyObjectQuad & aSkyObjectQuad = aFaceCloud.m_SkyObjectQuadVector[dwk];
for (unsigned char v = 0; v < 4; ++v)
{
aSkyObjectQuad.SetSrcColor(v,
c_rColor.m_FirstColor.r,
c_rColor.m_FirstColor.g,
c_rColor.m_FirstColor.b,
c_rColor.m_FirstColor.a);
aSkyObjectQuad.SetTransition(v,
c_rNextColor.m_FirstColor.r,
c_rNextColor.m_FirstColor.g,
c_rNextColor.m_FirstColor.b,
c_rNextColor.m_FirstColor.a,
dwTransitionTime);
}
}
}
void CSkyBox::SetSkyColor(const TVectorGradientColor & c_rColorVector, const TVectorGradientColor & c_rNextColorVector, long lTransitionTime)
{
if (c_rColorVector.empty() || c_rNextColorVector.empty())
return;
unsigned long ulVectorGradientColornum = 0;
unsigned long uck;
for (unsigned char ucj = 0; ucj < 4; ++ucj)
{
TSkyObjectFace & aFace = m_Faces[ucj];
ulVectorGradientColornum = 0;
for (uck = 0; uck < aFace.m_SkyObjectQuadVector.size(); ++uck)
{
if (ulVectorGradientColornum >= c_rColorVector.size() || ulVectorGradientColornum >= c_rNextColorVector.size())
break;
CSkyObjectQuad & aSkyObjectQuad = aFace.m_SkyObjectQuadVector[uck];
aSkyObjectQuad.SetSrcColor(0,
c_rColorVector[ulVectorGradientColornum].m_SecondColor.r,
c_rColorVector[ulVectorGradientColornum].m_SecondColor.g,
c_rColorVector[ulVectorGradientColornum].m_SecondColor.b,
c_rColorVector[ulVectorGradientColornum].m_SecondColor.a);
aSkyObjectQuad.SetTransition(0,
c_rNextColorVector[ulVectorGradientColornum].m_SecondColor.r,
c_rNextColorVector[ulVectorGradientColornum].m_SecondColor.g,
c_rNextColorVector[ulVectorGradientColornum].m_SecondColor.b,
c_rNextColorVector[ulVectorGradientColornum].m_SecondColor.a,
lTransitionTime);
aSkyObjectQuad.SetSrcColor(1,
c_rColorVector[ulVectorGradientColornum].m_FirstColor.r,
c_rColorVector[ulVectorGradientColornum].m_FirstColor.g,
c_rColorVector[ulVectorGradientColornum].m_FirstColor.b,
c_rColorVector[ulVectorGradientColornum].m_FirstColor.a);
aSkyObjectQuad.SetTransition(1,
c_rNextColorVector[ulVectorGradientColornum].m_FirstColor.r,
c_rNextColorVector[ulVectorGradientColornum].m_FirstColor.g,
c_rNextColorVector[ulVectorGradientColornum].m_FirstColor.b,
c_rNextColorVector[ulVectorGradientColornum].m_FirstColor.a,
lTransitionTime);
aSkyObjectQuad.SetSrcColor(2,
c_rColorVector[ulVectorGradientColornum].m_SecondColor.r,
c_rColorVector[ulVectorGradientColornum].m_SecondColor.g,
c_rColorVector[ulVectorGradientColornum].m_SecondColor.b,
c_rColorVector[ulVectorGradientColornum].m_SecondColor.a);
aSkyObjectQuad.SetTransition(2,
c_rNextColorVector[ulVectorGradientColornum].m_SecondColor.r,
c_rNextColorVector[ulVectorGradientColornum].m_SecondColor.g,
c_rNextColorVector[ulVectorGradientColornum].m_SecondColor.b,
c_rNextColorVector[ulVectorGradientColornum].m_SecondColor.a,
lTransitionTime);
aSkyObjectQuad.SetSrcColor(3,
c_rColorVector[ulVectorGradientColornum].m_FirstColor.r,
c_rColorVector[ulVectorGradientColornum].m_FirstColor.g,
c_rColorVector[ulVectorGradientColornum].m_FirstColor.b,
c_rColorVector[ulVectorGradientColornum].m_FirstColor.a);
aSkyObjectQuad.SetTransition(3,
c_rNextColorVector[ulVectorGradientColornum].m_FirstColor.r,
c_rNextColorVector[ulVectorGradientColornum].m_FirstColor.g,
c_rNextColorVector[ulVectorGradientColornum].m_FirstColor.b,
c_rNextColorVector[ulVectorGradientColornum].m_FirstColor.a,
lTransitionTime);
ulVectorGradientColornum++;
}
}
TSkyObjectFace & aFaceTop = m_Faces[4];
ulVectorGradientColornum = 0;
for (uck = 0; uck < aFaceTop.m_SkyObjectQuadVector.size(); ++uck)
{
CSkyObjectQuad & aSkyObjectQuad = aFaceTop.m_SkyObjectQuadVector[uck];
for (unsigned char v = 0; v < 4; ++v)
{
aSkyObjectQuad.SetSrcColor(v,
c_rColorVector[ulVectorGradientColornum].m_FirstColor.r,
c_rColorVector[ulVectorGradientColornum].m_FirstColor.g,
c_rColorVector[ulVectorGradientColornum].m_FirstColor.b,
c_rColorVector[ulVectorGradientColornum].m_FirstColor.a);
aSkyObjectQuad.SetTransition(v,
c_rNextColorVector[ulVectorGradientColornum].m_FirstColor.r,
c_rNextColorVector[ulVectorGradientColornum].m_FirstColor.g,
c_rNextColorVector[ulVectorGradientColornum].m_FirstColor.b,
c_rNextColorVector[ulVectorGradientColornum].m_FirstColor.a,
lTransitionTime);
}
}
TSkyObjectFace & aFaceBottom = m_Faces[5];
ulVectorGradientColornum = c_rColorVector.size() - 1;
for (uck = 0; uck < aFaceBottom.m_SkyObjectQuadVector.size(); ++uck)
{
CSkyObjectQuad & aSkyObjectQuad = aFaceBottom.m_SkyObjectQuadVector[uck];
for (unsigned char v = 0; v < 4; ++v)
{
aSkyObjectQuad.SetSrcColor(v,
c_rColorVector[ulVectorGradientColornum].m_SecondColor.r,
c_rColorVector[ulVectorGradientColornum].m_SecondColor.g,
c_rColorVector[ulVectorGradientColornum].m_SecondColor.b,
c_rColorVector[ulVectorGradientColornum].m_SecondColor.a);
aSkyObjectQuad.SetTransition(v,
c_rNextColorVector[ulVectorGradientColornum].m_SecondColor.r,
c_rNextColorVector[ulVectorGradientColornum].m_SecondColor.g,
c_rNextColorVector[ulVectorGradientColornum].m_SecondColor.b,
c_rNextColorVector[ulVectorGradientColornum].m_SecondColor.a,
lTransitionTime);
}
}
}
void CSkyBox::StartTransition()
{
m_bTransitionStarted = true;
for (unsigned char ucj = 0; ucj < 6; ++ucj)
m_Faces[ucj].StartTransition();
m_FaceCloud.StartTransition();
}
void CSkyBox::Update()
{
CSkyObject::Update();
if (!m_bTransitionStarted)
return;
bool bResult = false;
for (unsigned char uci = 0; uci < 6; ++uci)
bResult = m_Faces[uci].Update() || bResult;
bResult = m_FaceCloud.Update() || bResult;
m_bTransitionStarted = bResult;
}
void CSkyBox::Render()
{
if (!IsNativeTerrainRenderEnabled())
return;
STATEMANAGER.SaveRenderState(D3DRS_ZENABLE, TRUE);
STATEMANAGER.SaveRenderState(D3DRS_ZWRITEENABLE, FALSE);
STATEMANAGER.SaveRenderState(D3DRS_LIGHTING, FALSE);
STATEMANAGER.SaveRenderState(D3DRS_FOGENABLE, FALSE);
STATEMANAGER.SaveRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
STATEMANAGER.SaveRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
STATEMANAGER.SaveTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG2);
STATEMANAGER.SaveTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE);
STATEMANAGER.SaveTextureStageState(0, D3DTSS_COLORARG2, D3DTA_DIFFUSE);
STATEMANAGER.SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_DISABLE);
STATEMANAGER.SetTexture(1, NULL);
STATEMANAGER.SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_DISABLE);
STATEMANAGER.SetTextureStageState(1, D3DTSS_ALPHAOP, D3DTOP_DISABLE);
STATEMANAGER.SetVertexShader(D3DFVF_XYZ | D3DFVF_DIFFUSE | D3DFVF_TEX1);
STATEMANAGER.SetTransform(D3DTS_WORLD, &m_matWorld);
if (m_ucRenderMode == CSkyObject::SKY_RENDER_MODE_TEXTURE)
{
STATEMANAGER.SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
STATEMANAGER.SaveTextureStageState(0, D3DTSS_ADDRESSU, D3DTADDRESS_CLAMP);
STATEMANAGER.SaveTextureStageState(0, D3DTSS_ADDRESSV, D3DTADDRESS_CLAMP);
for (unsigned int i = 0; i < 6; ++i)
{
CGraphicImageInstance * pFaceImageInstance = m_GraphicImageInstanceMap[m_Faces[i].m_strFaceTextureFileName];
if (!pFaceImageInstance)
break;
STATEMANAGER.SetTexture(0, pFaceImageInstance->GetTextureReference().GetD3DTexture());
m_Faces[i].Render();
}
STATEMANAGER.RestoreTextureStageState(0, D3DTSS_ADDRESSU);
STATEMANAGER.RestoreTextureStageState(0, D3DTSS_ADDRESSV);
}
else
{
STATEMANAGER.SetTexture(0, NULL);
for (unsigned int i = 0; i < 6; ++i)
{
m_Faces[i].Render();
}
}
STATEMANAGER.RestoreRenderState(D3DRS_CULLMODE);
STATEMANAGER.RestoreRenderState(D3DRS_LIGHTING);
STATEMANAGER.RestoreRenderState(D3DRS_ZENABLE);
STATEMANAGER.RestoreRenderState(D3DRS_ZWRITEENABLE);
STATEMANAGER.RestoreRenderState(D3DRS_FOGENABLE);
STATEMANAGER.RestoreRenderState(D3DRS_ALPHABLENDENABLE);
STATEMANAGER.RestoreTextureStageState(0, D3DTSS_COLOROP);
STATEMANAGER.RestoreTextureStageState(0, D3DTSS_COLORARG1);
STATEMANAGER.RestoreTextureStageState(0, D3DTSS_COLORARG2);
}
void CSkyBox::RenderCloud()
{
if (!IsNativeTerrainRenderEnabled())
return;
CGraphicImageInstance * pCloudGraphicImageInstance = m_GraphicImageInstanceMap[m_FaceCloud.m_strfacename];
if (!pCloudGraphicImageInstance || pCloudGraphicImageInstance->IsEmpty() || !pCloudGraphicImageInstance->GetTexturePointer())
return;
STATEMANAGER.SaveRenderState(D3DRS_ZENABLE, TRUE);
STATEMANAGER.SaveRenderState(D3DRS_ZWRITEENABLE, FALSE);
STATEMANAGER.SaveRenderState(D3DRS_LIGHTING, FALSE);
STATEMANAGER.SaveRenderState(D3DRS_FOGENABLE, FALSE);
STATEMANAGER.SaveRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
STATEMANAGER.SaveRenderState(D3DRS_SRCBLEND, D3DBLEND_ONE);
STATEMANAGER.SaveRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCCOLOR);
STATEMANAGER.SaveRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
STATEMANAGER.SaveTextureStageState(0, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_COUNT2);
m_matTextureCloud._31 = m_fCloudPositionU;
m_matTextureCloud._32 = m_fCloudPositionV;
DWORD dwCurTime = CTimer::Instance().GetCurrentMillisecond();
m_fCloudPositionU += m_fCloudScrollSpeedU * (float)(dwCurTime - m_dwlastTime) * 0.001f;
if (m_fCloudPositionU >= 1.0f)
m_fCloudPositionU = 0.0f;
m_fCloudPositionV += m_fCloudScrollSpeedV * (float)(dwCurTime - m_dwlastTime) * 0.001f;
if (m_fCloudPositionV >= 1.0f)
m_fCloudPositionV = 0.0f;
m_dwlastTime = dwCurTime;
STATEMANAGER.SaveTransform(D3DTS_TEXTURE0, &m_matTextureCloud);
STATEMANAGER.SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_MODULATEINVALPHA_ADDCOLOR);
STATEMANAGER.SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE);
STATEMANAGER.SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_DIFFUSE);
STATEMANAGER.SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1);
STATEMANAGER.SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE);
D3DXMATRIX matProjCloud;
D3DXMatrixPerspectiveFovRH(&matProjCloud, D3DX_PI * 0.25f, 1.33333f, 50.0f, 999999.0f);
STATEMANAGER.SetTransform(D3DTS_WORLD, &m_matWorldCloud);
STATEMANAGER.SaveTransform(D3DTS_PROJECTION, &matProjCloud);
STATEMANAGER.SetTexture(0, pCloudGraphicImageInstance->GetTexturePointer()->GetD3DTexture());
m_FaceCloud.Render();
STATEMANAGER.RestoreTransform(D3DTS_PROJECTION);
STATEMANAGER.RestoreTransform(D3DTS_TEXTURE0);
STATEMANAGER.RestoreTextureStageState(0, D3DTSS_TEXTURETRANSFORMFLAGS);
STATEMANAGER.RestoreRenderState(D3DRS_CULLMODE);
STATEMANAGER.RestoreRenderState(D3DRS_LIGHTING);
STATEMANAGER.RestoreRenderState(D3DRS_ZENABLE);
STATEMANAGER.RestoreRenderState(D3DRS_ZWRITEENABLE);
STATEMANAGER.RestoreRenderState(D3DRS_FOGENABLE);
STATEMANAGER.RestoreRenderState(D3DRS_ALPHABLENDENABLE);
STATEMANAGER.RestoreRenderState(D3DRS_SRCBLEND);
STATEMANAGER.RestoreRenderState(D3DRS_DESTBLEND);
}
+41
View File
@@ -0,0 +1,41 @@
// Platform skeleton for EterLib/TextBar.h (40250 EterLib/TextBar.cpp), generated by platform_stub.py.
// Every MT_PLATFORM_STUB() body is unimplemented: replace it with the platform implementation.
#include "EterLib/StdAfx.h"
#include "EterLib/TextBar.h"
#include "../PlatformStub.h"
CTextBar::CTextBar(int, bool)
{
MT_PLATFORM_STUB();
}
CTextBar::~CTextBar()
{
MT_PLATFORM_STUB();
}
auto CTextBar::TextOut(int, int, const char *) -> void
{
MT_PLATFORM_STUB();
}
auto CTextBar::SetTextColor(int, int, int) -> void
{
MT_PLATFORM_STUB();
}
auto CTextBar::GetTextExtent(const char *, SIZE *) -> void
{
MT_PLATFORM_STUB();
}
auto CTextBar::__SetFont(int, bool) -> void
{
MT_PLATFORM_STUB();
}
auto CTextBar::OnCreate() -> void
{
MT_PLATFORM_STUB();
}
+29
View File
@@ -0,0 +1,29 @@
// Platform skeleton for EterLib/Thread.h (40250 EterLib/Thread.cpp), generated by platform_stub.py.
// Every MT_PLATFORM_STUB() body is unimplemented: replace it with the platform implementation.
#include "EterLib/StdAfx.h"
#include "EterLib/Thread.h"
#include "../PlatformStub.h"
CThread::CThread()
{
MT_PLATFORM_STUB();
}
auto CThread::Create(void *) -> int
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<int>();
}
auto CThread::EntryPoint(void *) -> UINT
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<UINT>();
}
auto CThread::Run(void *) -> UINT
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<UINT>();
}
+147
View File
@@ -0,0 +1,147 @@
#include "EterLib/StdAfx.h"
#include "UIRenderCommands.h"
#include "RenderCommands3D.h"
#include "EterLib/StateManager.h"
#include <algorithm>
namespace {
struct Point { float x, y; };
std::vector<Point> clip_polygon(std::vector<Point> polygon, int edge, float bound) {
std::vector<Point> result;
if (polygon.empty()) return result;
auto inside = [edge, bound](Point p) {
return edge == 0 ? p.x >= bound : edge == 1 ? p.x <= bound
: edge == 2 ? p.y >= bound : p.y <= bound;
};
auto intersect = [edge, bound](Point a, Point b) {
const float t = edge < 2 ? (bound - a.x) / (b.x - a.x)
: (bound - a.y) / (b.y - a.y);
return Point{a.x + t * (b.x - a.x), a.y + t * (b.y - a.y)};
};
Point previous = polygon.back();
for (Point current : polygon) {
const bool was_inside = inside(previous), is_inside = inside(current);
if (was_inside != is_inside) result.push_back(intersect(previous, current));
if (is_inside) result.push_back(current);
previous = current;
}
return result;
}
std::vector<UIRenderCommand> commands;
std::uint64_t frame_id = 0;
int canvas_width = 0;
int canvas_height = 0;
float clip_x1 = 0, clip_y1 = 0, clip_x2 = 0, clip_y2 = 0;
float saved_x1 = 0, saved_y1 = 0, saved_x2 = 0, saved_y2 = 0;
float offset_x = 0;
}
void UIRenderSetOffsetX(float x) { offset_x = x; }
float UIRenderOffsetX() { return offset_x; }
void UIRenderSetSize(int width, int height) { canvas_width = width; canvas_height = height; }
void UIRenderGetSize(unsigned* width, unsigned* height) {
if (width) *width = canvas_width;
if (height) *height = canvas_height;
}
void UIRenderBeginFrame() {
++frame_id;
commands.clear();
clip_x1 = clip_y1 = 0;
clip_x2 = canvas_width;
clip_y2 = canvas_height;
}
std::uint64_t UIRenderFrameId() { return frame_id; }
void UIRenderAdd(UIRenderCommand command) {
if (offset_x != 0) {
command.x1 += offset_x;
command.x2 += offset_x;
if (command.quad)
for (float& x : command.qx) x += offset_x;
}
command.clip_x1 = clip_x1; command.clip_y1 = clip_y1;
command.clip_x2 = clip_x2; command.clip_y2 = clip_y2;
command.behind_3d = Render3DDraws().empty();
if (command.kind == UIRenderCommand::Bar && command.quad) {
// Cooldown fans are triangles. Clip their geometry before either renderer consumes it.
std::vector<Point> polygon{{command.qx[0], command.qy[0]},
{command.qx[1], command.qy[1]},
{command.qx[2], command.qy[2]}};
const float bounds[4] = {clip_x1, clip_x2, clip_y1, clip_y2};
for (int edge = 0; edge < 4; ++edge)
polygon = clip_polygon(std::move(polygon), edge, bounds[edge]);
for (std::size_t i = 1; i + 1 < polygon.size(); ++i) {
UIRenderCommand piece = command;
const Point tri[3] = {polygon[0], polygon[i], polygon[i + 1]};
const float area = (tri[1].x - tri[0].x) * (tri[2].y - tri[0].y) -
(tri[1].y - tri[0].y) * (tri[2].x - tri[0].x);
if (area == 0.0f) continue;
for (int k = 0; k < 4; ++k) {
piece.qx[k] = tri[k < 3 ? k : 2].x;
piece.qy[k] = tri[k < 3 ? k : 2].y;
}
piece.x1 = std::min({tri[0].x, tri[1].x, tri[2].x});
piece.y1 = std::min({tri[0].y, tri[1].y, tri[2].y});
piece.x2 = std::max({tri[0].x, tri[1].x, tri[2].x});
piece.y2 = std::max({tri[0].y, tri[1].y, tri[2].y});
commands.push_back(std::move(piece));
}
return;
}
commands.push_back(command);
}
const std::vector<UIRenderCommand>& UIRenderCommands() { return commands; }
void UIRenderSetClip(float x, float y, float width, float height) {
saved_x1 = clip_x1; saved_y1 = clip_y1; saved_x2 = clip_x2; saved_y2 = clip_y2;
clip_x1 = x + offset_x; clip_y1 = y;
clip_x2 = x + offset_x + width; clip_y2 = y + height;
}
void UIRenderRestoreClip() {
clip_x1 = saved_x1; clip_y1 = saved_y1;
clip_x2 = saved_x2; clip_y2 = saved_y2;
}
void UIRenderAddImage(const CGraphicTexture* texture, const float x[4], const float y[4],
float su, float sv, float eu, float ev, std::uint32_t argb, int blend) {
// 40250 draws the image quad through the device: the UI pass's world transform places it
// (identity except where a caller sets one, e.g. CPythonMiniMap::RenderAtlas's window offset) and a
// stage-0 MODULATE with D3DTA_TFACTOR tints it (the atlas's NPC/warp/waypoint marks).
D3DXMATRIX world;
D3DXMatrixIdentity(&world);
if (CStateManager* state = CStateManager::InstancePtr()) {
state->GetTransform(D3DTS_WORLD, &world);
DWORD op = 0, arg1 = 0, arg2 = 0;
state->GetTextureStageState(0, D3DTSS_COLOROP, &op);
state->GetTextureStageState(0, D3DTSS_COLORARG1, &arg1);
state->GetTextureStageState(0, D3DTSS_COLORARG2, &arg2);
if (op == D3DTOP_MODULATE && (arg1 == D3DTA_TFACTOR || arg2 == D3DTA_TFACTOR)) {
// TFACTOR x TEXTURE drops the vertex colour; TFACTOR x DIFFUSE scales it. The canvas
// multiplies the texture in.
const std::uint32_t factor = state->GetRenderState(D3DRS_TEXTUREFACTOR) & 0x00FFFFFFu;
const DWORD other = arg1 == D3DTA_TFACTOR ? arg2 : arg1;
if (other == D3DTA_DIFFUSE) {
std::uint32_t tinted = argb & 0xFF000000u;
for (int shift = 0; shift < 24; shift += 8)
tinted |= ((((argb >> shift) & 255) * ((factor >> shift) & 255) + 127) / 255) << shift;
argb = tinted;
} else {
argb = (argb & 0xFF000000u) | factor;
}
}
}
UIRenderCommand command{UIRenderCommand::Image, 0, 0, 0, 0, argb};
for (int i = 0; i < 4; ++i) {
command.qx[i] = x[i] * world._11 + y[i] * world._21 + world._41 + 0.5f;
command.qy[i] = x[i] * world._12 + y[i] * world._22 + world._42 + 0.5f;
}
command.x1 = std::min({command.qx[0], command.qx[1], command.qx[2], command.qx[3]});
command.y1 = std::min({command.qy[0], command.qy[1], command.qy[2], command.qy[3]});
command.x2 = std::max({command.qx[0], command.qx[1], command.qx[2], command.qx[3]});
command.y2 = std::max({command.qy[0], command.qy[1], command.qy[2], command.qy[3]});
command.text = UIRenderTextureName(texture);
command.quad = true;
command.su = su; command.sv = sv; command.eu = eu; command.ev = ev;
command.blend = blend;
UIRenderAdd(std::move(command));
}
+86
View File
@@ -0,0 +1,86 @@
#pragma once
#include <cstdint>
#include <string>
#include <vector>
// Commands emitted by the 40250 UI drawing calls, consumed by Godot's CanvasItem.
// The port layer stays independent of godot-cpp.
struct UIRenderCommand {
enum Kind { Bar, Line, Text, Image, GradientBar } kind;
float x1, y1, x2, y2;
std::uint32_t argb;
std::uint32_t end_argb = 0; // GradientBar only: colour on the bottom edge.
float clip_x1 = 0, clip_y1 = 0, clip_x2 = 0, clip_y2 = 0;
std::string text;
// Image only: text is the texture's file, drawn as the quad (vertices 0..3 = TL, TR, BL, BR)
// with texture coordinates su,sv..eu,ev; x1..y2 is the quad's bounding box.
bool quad = false;
float qx[4] = {}, qy[4] = {};
float su = 0, sv = 0, eu = 1, ev = 1;
int blend = 0; // CGraphicExpandedImageInstance::RENDERING_MODE_*
// A second texture stage that modulates the colour and replaces the alpha (40250 CPythonMiniMap's
// circular minimap_image_filter): the mask's texture coordinates at the quad's four corners.
std::string mask;
float mu[4] = {}, mv[4] = {};
bool behind_3d = false;
};
// D3DXCOLOR (0..1 floats) -> the 0xAARRGGBB the commands carry.
template <class Color>
std::uint32_t UIRenderColor(const Color& color) {
auto channel = [](float value) -> std::uint32_t {
return static_cast<std::uint32_t>((value < 0 ? 0 : value > 1 ? 1 : value) * 255.0f + 0.5f);
};
return (channel(color.a) << 24) | (channel(color.r) << 16) | (channel(color.g) << 8) | channel(color.b);
}
class CGraphicTexture;
// A file-backed texture is named by its pack path; a memory texture (CGraphicImageTexture::Create,
// filled through Lock/Unlock: the CGraphicFontTexture glyph pages) by "mem:<id>@<revision>", the
// revision counting Unlocks so the canvas knows when to fetch the pixels again.
std::string UIRenderTextureName(const CGraphicTexture* texture);
// The pixels of memory texture "mem:<id>" (the part of the name before '@'), as 0xAARRGGBB.
struct UIMemoryTexture {
int width = 0;
int height = 0;
std::uint32_t revision = 0;
std::vector<std::uint32_t> argb;
};
bool UIRenderMemoryTexture(const std::string& name, UIMemoryTexture* out);
struct IDirect3DTexture8;
struct IDirect3DBaseTexture8;
// Frees the platform texture behind a CGraphicTexture: a memory texture or a file texture's handle.
void UIRenderReleaseMemoryTexture(IDirect3DTexture8* texture);
// The name (as UIRenderTextureName) of the texture a D3D handle belongs to; "" for null or unknown.
std::string UIRenderTextureNameFromHandle(const IDirect3DBaseTexture8* handle);
std::string MtCpuTextureNameFromHandle(const IDirect3DBaseTexture8* handle);
bool MtCpuMemoryTexture(const std::string& name, UIMemoryTexture* out);
// A textured quad from 40250's TPDTVertex[4] (TL, TR, BL, BR) positions and texture coordinates.
// PORT: D3D8 puts pixel centres on integers, which is why 40250 subtracts 0.5 from every vertex; the
// Godot canvas puts them on .5, so the quad is shifted back by +0.5 here.
void UIRenderAddImage(const CGraphicTexture* texture, const float x[4], const float y[4],
float su, float sv, float eu, float ev, std::uint32_t argb, int blend = 0);
void UIRenderSetSize(int width, int height);
void UIRenderGetSize(unsigned* width, unsigned* height);
void UIRenderBeginFrame();
std::uint64_t UIRenderFrameId();
void UIRenderAdd(UIRenderCommand command);
const std::vector<UIRenderCommand>& UIRenderCommands();
void UIRenderSetClip(float x, float y, float width, float height);
// PORT (mobile safe area): shifts the commands (and clips) recorded after it right by x canvas
// pixels, so the 40250 window layers can sit inside the rounded screen corners while the GAME layer
// (3D world, text tails) keeps the full canvas. 0 is the verbatim 40250 path.
void UIRenderSetOffsetX(float x);
float UIRenderOffsetX();
void UIRenderRestoreClip();
// HiDPI text: CGraphicFontTexture rasterises its glyph pages at this multiple of the logical font
// size (the swapchain's pixels per UI pixel) while keeping the 40250 glyph metrics and page UVs in
// logical pixels. 1 (the default) is the verbatim 40250 path. Latched when the first font page is
// created, so set it before the game creates fonts.
void UISetFontOversample(int scale);
int UIFontOversample();
+109
View File
@@ -0,0 +1,109 @@
// 40250 EterLib/Util.cpp:140-297, the default code page and font face.
//
// The rest of Util.cpp (LoadTextData / base64 / TokenTo*) is logic and not here. The 9x face table has
// CP949/Shift-JIS/GBK/Big5 literals, so this block is copied by hand instead of port_copy.
#include "EterLib/StdAfx.h"
#include "EterLib/Util.h"
#include "EterLocale/CodePageId.h"
static std::string gs_fontFace="";
static DWORD gs_codePage=0;
int GetCharsetFromCodePage(WORD codePage)
{
switch( codePage )
{
case CP_932:
return SHIFTJIS_CHARSET;
case CP_949:
return HANGUL_CHARSET;
case CP_936:
return GB2312_CHARSET;
case CP_950:
return CHINESEBIG5_CHARSET;
case CP_1253:
return GREEK_CHARSET;
case CP_1254:
return TURKISH_CHARSET;
case CP_1255:
return HEBREW_CHARSET;
case CP_1256:
return ARABIC_CHARSET;
case CP_1257:
return BALTIC_CHARSET;
case CP_1258:
return VIETNAMESE_CHARSET;
case CP_874:
return THAI_CHARSET;
case CP_1250:
return EASTEUROPE_CHARSET;
case CP_1251:
return RUSSIAN_CHARSET;
default:
return DEFAULT_CHARSET;
}
}
const char* GetFontFaceFromCodePageNT(WORD codePage)
{
switch( codePage )
{
case CP_932:
return "MS PGothic";
case CP_949:
return "GulimChe";
case CP_936:
return "SimSun";
case CP_950:
return "MingLiU";
case CP_874:
return "Tahoma";
case CP_1252:
return "Arial";
case CP_1256:
return "Tahoma";
case CP_1258:
return "Tahoma";
case CP_65001:
return "Arial";
default:
return "Arial";
}
}
DWORD GetDefaultCodePage()
{
return gs_codePage;
}
const char * GetDefaultFontFace()
{
return gs_fontFace.c_str();
}
// PORT: 40250 asks EnumFontFamiliesEx for the 9x (native-script) face name, then the NT one. The native
// names never match a font file here; CreateFontIndirect (platform/Win32Gdi.cpp) substitutes a missing
// face, so the NT name is the answer.
const char* GetFontFaceFromCodePage(WORD codePage)
{
return GetFontFaceFromCodePageNT(codePage);
}
void SetDefaultFontFace(const char* fontFace)
{
gs_fontFace=fontFace;
}
bool SetDefaultCodePage(DWORD codePage)
{
gs_codePage=codePage;
std::string fontFace=GetFontFaceFromCodePage(codePage);
if (fontFace.empty())
return false;
SetDefaultFontFace(fontFace.c_str());
return true;
}
@@ -0,0 +1,372 @@
// CPythonGraphic(40250 EterPythonLib/PythonGraphic.cpp)的平台骨架 —— 目前只有窗口树链接时真正需要
// 的那一个函数。
//
// CPythonGraphic 是 UI 的 2D 绘制层(D3D8 的正交投影、按钮的立体边框、冷却圈、截图),整份实现属于
// 2V0-f;platform_stub.py 不认 EterPythonLib(port_map 把它划成 python 层),所以这里按手写平台桩的
// 惯例来:先只放被引用到的符号,链接器会告诉我们下一个是谁。
//
// RenderCoolTimeBox:40250 的扇形顶点原样搬来,画法改成 UIRenderCommands(见函数注释)。
#include "EterPythonLib/StdAfx.h"
#include "EterPythonLib/PythonGraphic.h"
#include "EterLib/StateManager.h"
#include "../PlatformStub.h"
#include "../EterLib/UIRenderCommands.h"
#include <algorithm>
// 40250 PythonGraphic.cpp:611
CPythonGraphic::CPythonGraphic()
{
m_lightColor = GetColor(1.0f, 1.0f, 1.0f);
m_darkColor = GetColor(0.0f, 0.0f, 0.0f);
memset(&m_backupViewport, 0, sizeof(D3DVIEWPORT8));
m_fOrthoDepth = 1000.0f;
}
CPythonGraphic::~CPythonGraphic()
{
Tracef("Python Graphic Clear\n");
}
namespace
{
class CDummyDirect3D8 : public IDirect3D8
{
public:
HRESULT GetAdapterIdentifier(UINT, DWORD, D3DADAPTER_IDENTIFIER8* pIdentifier) override
{
if (!pIdentifier) return E_FAIL;
memset(pIdentifier, 0, sizeof(D3DADAPTER_IDENTIFIER8));
strncpy(pIdentifier->Driver, "dummy", sizeof(pIdentifier->Driver));
strncpy(pIdentifier->Description, "Dummy Direct3D8", sizeof(pIdentifier->Description));
return S_OK;
}
HRESULT GetAdapterDisplayMode(UINT, D3DDISPLAYMODE* pMode) override
{
if (!pMode) return E_FAIL;
pMode->Width = 1024;
pMode->Height = 768;
pMode->RefreshRate = 60;
pMode->Format = D3DFMT_X8R8G8B8;
return S_OK;
}
UINT GetAdapterModeCount(UINT) override
{
return 3;
}
HRESULT EnumAdapterModes(UINT, UINT Mode, D3DDISPLAYMODE* pMode) override
{
if (!pMode) return E_FAIL;
static const D3DDISPLAYMODE s_modes[] = {
{ 800, 600, 60, D3DFMT_X8R8G8B8 },
{ 1024, 768, 60, D3DFMT_X8R8G8B8 },
{ 1280, 1024, 60, D3DFMT_X8R8G8B8 },
};
if (Mode >= 3) return E_FAIL;
*pMode = s_modes[Mode];
return S_OK;
}
};
}
LPDIRECT3D8 CPythonGraphic::GetD3D()
{
static CDummyDirect3D8 s_dummyD3D;
return &s_dummyD3D;
}
void CPythonGraphic::SetViewport(float x, float y, float width, float height)
{
if (ms_lpd3dDevice)
{
ms_lpd3dDevice->GetViewport(&m_backupViewport);
D3DVIEWPORT8 vp = { (DWORD)x, (DWORD)y, (DWORD)width, (DWORD)height, 0.0f, 1.0f };
ms_lpd3dDevice->SetViewport(&vp);
}
UIRenderSetClip(x, y, width, height);
}
void CPythonGraphic::RestoreViewport()
{
if (ms_lpd3dDevice)
ms_lpd3dDevice->SetViewport(&m_backupViewport);
UIRenderRestoreClip();
}
void CPythonGraphic::SetOmniLight()
{
D3DMATERIAL8 Material;
Material.Ambient = D3DXCOLOR(0.3f, 0.3f, 0.3f, 1.0f);
Material.Diffuse = D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f);
Material.Emissive = D3DXCOLOR(0.1f, 0.1f, 0.1f, 1.0f);
STATEMANAGER.SetMaterial(&Material);
D3DLIGHT8 Light;
Light.Type = D3DLIGHT_SPOT;
Light.Position = D3DXVECTOR3(50.0f, 150.0f, 350.0f);
Light.Direction = D3DXVECTOR3(-0.15f, -0.3f, -0.9f);
Light.Theta = D3DXToRadian(30.0f);
Light.Phi = D3DXToRadian(45.0f);
Light.Falloff = 1.0f;
Light.Attenuation0 = 0.0f;
Light.Attenuation1 = 0.005f;
Light.Attenuation2 = 0.0f;
Light.Diffuse.r = 1.0f;
Light.Diffuse.g = 1.0f;
Light.Diffuse.b = 1.0f;
Light.Diffuse.a = 1.0f;
Light.Ambient.r = 1.0f;
Light.Ambient.g = 1.0f;
Light.Ambient.b = 1.0f;
Light.Ambient.a = 1.0f;
Light.Range = 500.0f;
if (ms_lpd3dDevice)
{
ms_lpd3dDevice->SetLight(0, &Light);
ms_lpd3dDevice->LightEnable(0, TRUE);
Light.Type = D3DLIGHT_POINT;
Light.Position = D3DXVECTOR3(0.0f, 200.0f, 200.0f);
Light.Attenuation0 = 0.1f;
Light.Attenuation1 = 0.01f;
Light.Attenuation2 = 0.0f;
ms_lpd3dDevice->SetLight(1, &Light);
ms_lpd3dDevice->LightEnable(1, TRUE);
}
}
long CPythonGraphic::GenerateColor(float r, float g, float b, float a) { return GetColor(r, g, b, a); }
// 40250 PythonGraphic.cpp:580
void CPythonGraphic::RenderDownButton(float sx, float sy, float ex, float ey)
{
RenderBox2d(sx, sy, ex, ey);
SetDiffuseColor(m_darkColor);
RenderLine2d(sx, sy, ex, sy);
RenderLine2d(sx, sy, sx, ey);
SetDiffuseColor(m_lightColor);
RenderLine2d(sx, ey, ex, ey);
RenderLine2d(ex, sy, ex, ey);
}
// 40250 PythonGraphic.cpp:593
void CPythonGraphic::RenderUpButton(float sx, float sy, float ex, float ey)
{
RenderBox2d(sx, sy, ex, ey);
SetDiffuseColor(m_lightColor);
RenderLine2d(sx, sy, ex, sy);
RenderLine2d(sx, sy, sx, ey);
SetDiffuseColor(m_darkColor);
RenderLine2d(sx, ey, ex, ey);
RenderLine2d(ex, sy, ex, ey);
}
bool CPythonGraphic::SaveScreenShot(const char*) { MT_PLATFORM_STUB(); return false; }
// 40250 PythonGraphic.cpp:52.
void CPythonGraphic::SetCursorPosition(int x, int y)
{
CScreen::SetCursorPosition(x, y, ms_iWidth, ms_iHeight);
}
// 40250 PythonGraphic.cpp:606
DWORD CPythonGraphic::GetAvailableMemory()
{
return ms_lpd3dDevice->GetAvailableTextureMem();
}
// 40250 PythonGraphic.cpp:124. The recording device reports no D3DCAPS2_FULLSCREENGAMMA (the frame
// goes to a window), so this returns at the caps check like 40250 does on such a device.
void CPythonGraphic::SetGamma(float fGammaFactor)
{
D3DCAPS8 d3dCaps;
D3DGAMMARAMP NewRamp;
int ui, val;
ms_lpd3dDevice->GetDeviceCaps(&d3dCaps);
if (D3DCAPS2_FULLSCREENGAMMA != (d3dCaps.Caps2 & D3DCAPS2_FULLSCREENGAMMA))
return;
for (int i = 0; i < 256; ++i)
{
val = (int) (i * fGammaFactor * 255.0f);
ui = 0;
if (val > 32767)
{
val = val - 32767;
ui = 1;
}
if (val > 32767)
val = 32767;
NewRamp.red[i] = (WORD) (val | (32768 * ui));
NewRamp.green[i] = (WORD) (val | (32768 * ui));
NewRamp.blue[i] = (WORD) (val | (32768 * ui));
}
ms_lpd3dDevice->SetGammaRamp(D3DSGR_NO_CALIBRATION, &NewRamp);
}
// 40250 PythonGraphic.cpp:491. The fan's vertices are built verbatim.
// PORT: 40250 draws them as a D3DPT_TRIANGLEFAN with untextured SELECTARG1(DIFFUSE) colour and alpha;
// the UI here is drawn from UIRenderCommands, so each fan triangle goes out as one untextured quad
// command (vertices centre, j, j+1, j+1) in the same half-transparent black.
void CPythonGraphic::RenderCoolTimeBox(float fxCenter, float fyCenter, float fRadius, float fTime)
{
if (fTime >= 1.0f)
return;
fTime = max(0.0f, fTime);
static D3DXCOLOR color = D3DXCOLOR(0.0f, 0.0f, 0.0f, 0.5f);
static D3DXVECTOR2 s_v2BoxPos[8] =
{
D3DXVECTOR2( -1.0f, -1.0f ),
D3DXVECTOR2( -1.0f, 0.0f ),
D3DXVECTOR2( -1.0f, +1.0f ),
D3DXVECTOR2( 0.0f, +1.0f ),
D3DXVECTOR2( +1.0f, +1.0f ),
D3DXVECTOR2( +1.0f, 0.0f ),
D3DXVECTOR2( +1.0f, -1.0f ),
D3DXVECTOR2( 0.0f, -1.0f ),
};
int iTriCount = int(8 - 8.0f * fTime);
float fLastPercentage = (8 - 8.0f * fTime) - iTriCount;
std::vector<TPDTVertex> vertices;
TPDTVertex vertex;
vertex.position.x = fxCenter;
vertex.position.y = fyCenter;
vertex.position.z = 0.0f;
vertex.diffuse = color;
vertex.texCoord.x = 0.0f;
vertex.texCoord.x = 0.0f;
vertices.push_back(vertex);
vertex.position.x = fxCenter;
vertex.position.y = fyCenter - fRadius;
vertex.position.z = 0.0f;
vertex.diffuse = color;
vertex.texCoord.x = 0.0f;
vertex.texCoord.x = 0.0f;
vertices.push_back(vertex);
for (int j = 0; j < iTriCount; ++j)
{
vertex.position.x = fxCenter + s_v2BoxPos[j].x * fRadius;
vertex.position.y = fyCenter + s_v2BoxPos[j].y * fRadius;
vertices.push_back(vertex);
}
if (fLastPercentage > 0.0f)
{
D3DXVECTOR2 * pv2Pos;
D3DXVECTOR2 * pv2LastPos;
assert((iTriCount-1+8)%8 >= 0 && (iTriCount-1+8)%8 < 8);
assert((iTriCount+8)%8 >= 0 && (iTriCount+8)%8 < 8);
pv2LastPos = &s_v2BoxPos[(iTriCount-1+8)%8];
pv2Pos = &s_v2BoxPos[(iTriCount+8)%8];
vertex.position.x = fxCenter + ((pv2Pos->x-pv2LastPos->x) * fLastPercentage + pv2LastPos->x) * fRadius;
vertex.position.y = fyCenter + ((pv2Pos->y-pv2LastPos->y) * fLastPercentage + pv2LastPos->y) * fRadius;
vertices.push_back(vertex);
++iTriCount;
}
if (vertices.empty())
return;
// PORT: the D3DPT_TRIANGLEFAN of iTriCount triangles, see the function comment.
const std::uint32_t argb = UIRenderColor(color);
for (int j = 0; j < iTriCount && j + 2 < int(vertices.size()); ++j)
{
const TPDTVertex* fan[4] = { &vertices[0], &vertices[j + 1], &vertices[j + 2], &vertices[j + 2] };
UIRenderCommand command{UIRenderCommand::Bar, 0, 0, 0, 0, argb};
for (int k = 0; k < 4; ++k)
{
command.qx[k] = fan[k]->position.x;
command.qy[k] = fan[k]->position.y;
}
command.x1 = std::min({command.qx[0], command.qx[1], command.qx[2]});
command.y1 = std::min({command.qy[0], command.qy[1], command.qy[2]});
command.x2 = std::max({command.qx[0], command.qx[1], command.qx[2]});
command.y2 = std::max({command.qy[0], command.qy[1], command.qy[2]});
command.quad = true;
UIRenderAdd(std::move(command));
}
}
// 40250 PythonGraphic.cpp:17
float CPythonGraphic::GetOrthoDepth()
{
return m_fOrthoDepth;
}
// 40250 PythonGraphic.cpp:22
void CPythonGraphic::SetInterfaceRenderState()
{
STATEMANAGER.SetTransform(D3DTS_PROJECTION, &ms_matIdentity);
STATEMANAGER.SetTransform(D3DTS_VIEW, &ms_matIdentity);
STATEMANAGER.SetTransform(D3DTS_WORLD, &ms_matIdentity);
STATEMANAGER.SetTextureStageState(0, D3DTSS_MINFILTER, D3DTEXF_NONE);
STATEMANAGER.SetTextureStageState(0, D3DTSS_MAGFILTER, D3DTEXF_NONE);
STATEMANAGER.SetTextureStageState(0, D3DTSS_MIPFILTER, D3DTEXF_NONE);
STATEMANAGER.SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
STATEMANAGER.SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);
STATEMANAGER.SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA);
CPythonGraphic::Instance().SetBlendOperation();
CPythonGraphic::Instance().SetOrtho2D(ms_iWidth, ms_iHeight, GetOrthoDepth());
STATEMANAGER.SetRenderState(D3DRS_LIGHTING, FALSE);
}
// 40250 PythonGraphic.cpp:42
void CPythonGraphic::SetGameRenderState()
{
STATEMANAGER.SetTextureStageState(0, D3DTSS_MINFILTER, D3DTEXF_LINEAR);
STATEMANAGER.SetTextureStageState(0, D3DTSS_MAGFILTER, D3DTEXF_LINEAR);
STATEMANAGER.SetTextureStageState(0, D3DTSS_MIPFILTER, D3DTEXF_LINEAR);
STATEMANAGER.SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
STATEMANAGER.SetRenderState(D3DRS_LIGHTING, TRUE);
}
// 40250 PythonGraphic.cpp:387
void CPythonGraphic::PushState()
{
TState curState;
curState.matProj = ms_matProj;
curState.matView = ms_matView;
//STATEMANAGER.SaveTransform(D3DTS_WORLD, &m_SaveWorldMatrix);
m_stateStack.push(curState);
//CCamera::Instance().PushParams();
}
// 40250 PythonGraphic.cpp:399
void CPythonGraphic::PopState()
{
if (m_stateStack.empty())
{
assert(!"PythonGraphic::PopState StateStack is EMPTY");
return;
}
TState & rState = m_stateStack.top();
//STATEMANAGER.RestoreTransform(D3DTS_WORLD);
ms_matProj = rState.matProj;
ms_matView = rState.matView;
UpdatePipeLineMatrix();
m_stateStack.pop();
//CCamera::Instance().PopParams();
}
@@ -0,0 +1,125 @@
// Platform implementation of 40250 GameLib/MapOutdoorCharacterShadow.cpp.
#include "GameLib/StdAfx.h"
#include "EterLib/StateManager.h"
#include "EterLib/Camera.h"
#include "GameLib/MapOutdoor.h"
static int recreate = false;
void CMapOutdoor::SetShadowTextureSize(WORD size)
{
if (m_wShadowMapSize != size)
{
recreate = true;
Tracenf("ShadowTextureSize changed %d -> %d", m_wShadowMapSize, size);
}
m_wShadowMapSize = size;
}
void CMapOutdoor::CreateCharacterShadowTexture()
{
extern bool GRAPHICS_CAPS_CAN_NOT_DRAW_SHADOW;
if (GRAPHICS_CAPS_CAN_NOT_DRAW_SHADOW)
return;
ReleaseCharacterShadowTexture();
if (IsLowTextureMemory())
SetShadowTextureSize(128);
m_ShadowMapViewport.X = 1;
m_ShadowMapViewport.Y = 1;
m_ShadowMapViewport.Width = m_wShadowMapSize - 2;
m_ShadowMapViewport.Height = m_wShadowMapSize - 2;
m_ShadowMapViewport.MinZ = 0.0f;
m_ShadowMapViewport.MaxZ = 1.0f;
if (FAILED(ms_lpd3dDevice->CreateTexture(m_wShadowMapSize, m_wShadowMapSize, 1, D3DUSAGE_RENDERTARGET, D3DFMT_R5G6B5, D3DPOOL_DEFAULT, &m_lpCharacterShadowMapTexture)))
{
TraceError("CMapOutdoor Unable to create Character Shadow render target texture\n");
return;
}
if (FAILED(m_lpCharacterShadowMapTexture->GetSurfaceLevel(0, &m_lpCharacterShadowMapRenderTargetSurface)))
{
TraceError("CMapOutdoor Unable to GetSurfaceLevel Character Shadow render target texture\n");
return;
}
if (FAILED(ms_lpd3dDevice->CreateDepthStencilSurface(m_wShadowMapSize, m_wShadowMapSize, D3DFMT_D16, D3DMULTISAMPLE_NONE, &m_lpCharacterShadowMapDepthSurface)))
{
TraceError("CMapOutdoor Unable to create Character Shadow depth Surface\n");
return;
}
}
void CMapOutdoor::ReleaseCharacterShadowTexture()
{
SAFE_RELEASE(m_lpCharacterShadowMapRenderTargetSurface);
SAFE_RELEASE(m_lpCharacterShadowMapDepthSurface);
SAFE_RELEASE(m_lpCharacterShadowMapTexture);
}
static DWORD dwLightEnable = FALSE;
static bool shadowPassBegun = false;
bool CMapOutdoor::BeginRenderCharacterShadowToTexture()
{
CCamera* camera = CCameraManager::Instance().GetCurrentCamera();
if (!camera)
return false;
if (recreate)
{
CreateCharacterShadowTexture();
recreate = false;
}
if (!m_lpCharacterShadowMapRenderTargetSurface || !m_lpCharacterShadowMapDepthSurface)
return false;
shadowPassBegun = true;
const D3DXVECTOR3 target = camera->GetTarget();
const D3DXVECTOR3 eye(target.x - 1.732f * 1250.0f,
target.y - 1250.0f, target.z + 2.0f * 1.732f * 1250.0f);
const D3DXVECTOR3 up(0.0f, 0.0f, 1.0f);
D3DXMATRIX lightView, lightProj;
D3DXMatrixLookAtRH(&lightView, &eye, &target, &up);
D3DXMatrixOrthoRH(&lightProj, 2550.0f, 2550.0f, 1.0f, 15000.0f);
STATEMANAGER.SaveTransform(D3DTS_VIEW, &lightView);
STATEMANAGER.SaveTransform(D3DTS_PROJECTION, &lightProj);
dwLightEnable = STATEMANAGER.GetRenderState(D3DRS_LIGHTING);
STATEMANAGER.SetRenderState(D3DRS_LIGHTING, FALSE);
STATEMANAGER.SaveRenderState(D3DRS_TEXTUREFACTOR, 0xFF808080);
STATEMANAGER.SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
STATEMANAGER.SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TFACTOR);
STATEMANAGER.SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_DISABLE);
STATEMANAGER.SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_DISABLE);
bool success = SUCCEEDED(ms_lpd3dDevice->GetRenderTarget(&m_lpBackupRenderTargetSurface));
success = SUCCEEDED(ms_lpd3dDevice->GetDepthStencilSurface(&m_lpBackupDepthSurface)) && success;
success = SUCCEEDED(ms_lpd3dDevice->SetRenderTarget(m_lpCharacterShadowMapRenderTargetSurface,
m_lpCharacterShadowMapDepthSurface)) && success;
success = SUCCEEDED(ms_lpd3dDevice->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER,
0xFFFFFFFFu, 1.0f, 0)) && success;
success = SUCCEEDED(ms_lpd3dDevice->GetViewport(&m_BackupViewport)) && success;
success = SUCCEEDED(ms_lpd3dDevice->SetViewport(&m_ShadowMapViewport)) && success;
return success;
}
void CMapOutdoor::EndRenderCharacterShadowToTexture()
{
if (!shadowPassBegun)
return;
shadowPassBegun = false;
ms_lpd3dDevice->SetViewport(&m_BackupViewport);
if (m_lpBackupRenderTargetSurface && m_lpBackupDepthSurface)
ms_lpd3dDevice->SetRenderTarget(m_lpBackupRenderTargetSurface, m_lpBackupDepthSurface);
SAFE_RELEASE(m_lpBackupRenderTargetSurface);
SAFE_RELEASE(m_lpBackupDepthSurface);
STATEMANAGER.RestoreTransform(D3DTS_VIEW);
STATEMANAGER.RestoreTransform(D3DTS_PROJECTION);
STATEMANAGER.SetRenderState(D3DRS_LIGHTING, dwLightEnable);
STATEMANAGER.RestoreRenderState(D3DRS_TEXTUREFACTOR);
}
@@ -0,0 +1,705 @@
// Platform copy of 40250 GameLib/MapOutdoorRenderHTP.cpp (hardware-transform terrain patches), as is
// apart from the includes and the native-terrain gate: the Godot Metin2World adapter draws the terrain
// (PORT-PLAN §3) unless IsNativeTerrainRenderEnabled() (MT_NATIVE_TERRAIN=1 or the standalone native
// renderer). 40250 takes this path on a fast-T&L device with auto tiling, or SOFTWARE_TILING 0.
#include "GameLib/StdAfx.h"
#include "GameLib/MapOutdoor.h"
#include "EterLib/StateManager.h"
#include "../EterLib/RenderCommands3D.h"
void CMapOutdoor::__RenderTerrain_RenderHardwareTransformPatch()
{
// PORT: see the file comment.
if (!IsNativeTerrainRenderEnabled())
return;
DWORD dwFogColor;
float fFogFarDistance;
float fFogNearDistance;
if (mc_pEnvironmentData)
{
dwFogColor=mc_pEnvironmentData->FogColor;
fFogNearDistance=mc_pEnvironmentData->GetFogNearDistance();
fFogFarDistance=mc_pEnvironmentData->GetFogFarDistance();
}
else
{
dwFogColor=0xffffffff;
fFogNearDistance=5000.0f;
fFogFarDistance=10000.0f;
}
//////////////////////////////////////////////////////////////////////////
// Render State & TextureStageState
STATEMANAGER.SaveTextureStageState(0, D3DTSS_TEXCOORDINDEX, D3DTSS_TCI_CAMERASPACEPOSITION);
STATEMANAGER.SaveTextureStageState(0, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_COUNT2);
STATEMANAGER.SaveTextureStageState(1, D3DTSS_TEXCOORDINDEX, D3DTSS_TCI_CAMERASPACEPOSITION);
STATEMANAGER.SaveTextureStageState(1, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_COUNT2);
STATEMANAGER.SaveRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
STATEMANAGER.SaveRenderState(D3DRS_ALPHATESTENABLE, TRUE);
STATEMANAGER.SaveRenderState(D3DRS_ALPHAREF, 0x00000000);
STATEMANAGER.SaveRenderState(D3DRS_ALPHAFUNC, D3DCMP_GREATER);
STATEMANAGER.SaveRenderState(D3DRS_TEXTUREFACTOR, dwFogColor);
STATEMANAGER.SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE);
STATEMANAGER.SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_CURRENT);
STATEMANAGER.SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_MODULATE);
STATEMANAGER.SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE);
STATEMANAGER.SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1);
STATEMANAGER.SetTextureStageState(0, D3DTSS_ADDRESSU, D3DTADDRESS_WRAP);
STATEMANAGER.SetTextureStageState(0, D3DTSS_ADDRESSV, D3DTADDRESS_WRAP);
STATEMANAGER.SetTextureStageState(1, D3DTSS_COLORARG1, D3DTA_CURRENT);
STATEMANAGER.SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
STATEMANAGER.SetTextureStageState(1, D3DTSS_ALPHAARG1, D3DTA_TEXTURE);
STATEMANAGER.SetTextureStageState(1, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1);
STATEMANAGER.SetTextureStageState(1, D3DTSS_ADDRESSU, D3DTADDRESS_CLAMP);
STATEMANAGER.SetTextureStageState(1, D3DTSS_ADDRESSV, D3DTADDRESS_CLAMP);
#ifdef WORLD_EDITOR
if (GetAsyncKeyState(VK_CAPITAL))
{
CSpeedTreeWrapper::ms_bSelfShadowOn = false;
STATEMANAGER.SetTextureStageState(0, D3DTSS_MINFILTER, D3DTEXF_GAUSSIANCUBIC);
STATEMANAGER.SetTextureStageState(0, D3DTSS_MAGFILTER, D3DTEXF_GAUSSIANCUBIC);
STATEMANAGER.SetTextureStageState(0, D3DTSS_MIPFILTER, D3DTEXF_GAUSSIANCUBIC);
STATEMANAGER.SetTextureStageState(1, D3DTSS_MINFILTER, D3DTEXF_GAUSSIANCUBIC);
STATEMANAGER.SetTextureStageState(1, D3DTSS_MAGFILTER, D3DTEXF_GAUSSIANCUBIC);
STATEMANAGER.SetTextureStageState(1, D3DTSS_MIPFILTER, D3DTEXF_GAUSSIANCUBIC);
}
else
{
CSpeedTreeWrapper::ms_bSelfShadowOn = true;
STATEMANAGER.SetTextureStageState(0, D3DTSS_MINFILTER, D3DTEXF_LINEAR);
STATEMANAGER.SetTextureStageState(0, D3DTSS_MAGFILTER, D3DTEXF_LINEAR);
STATEMANAGER.SetTextureStageState(0, D3DTSS_MIPFILTER, D3DTEXF_LINEAR);
STATEMANAGER.SetTextureStageState(1, D3DTSS_MINFILTER, D3DTEXF_LINEAR);
STATEMANAGER.SetTextureStageState(1, D3DTSS_MAGFILTER, D3DTEXF_LINEAR);
STATEMANAGER.SetTextureStageState(1, D3DTSS_MIPFILTER, D3DTEXF_LINEAR);
}
#else
CSpeedTreeWrapper::ms_bSelfShadowOn = true;
STATEMANAGER.SetBestFiltering(0);
STATEMANAGER.SetBestFiltering(1);
#endif
m_matWorldForCommonUse._41 = 0.0f;
m_matWorldForCommonUse._42 = 0.0f;
STATEMANAGER.SetTransform(D3DTS_WORLD, &m_matWorldForCommonUse);
STATEMANAGER.SaveTransform(D3DTS_TEXTURE0, &m_matWorldForCommonUse);
STATEMANAGER.SaveTransform(D3DTS_TEXTURE1, &m_matWorldForCommonUse);
// Render State & TextureStageState
//////////////////////////////////////////////////////////////////////////
STATEMANAGER.SetVertexShader(D3DFVF_XYZ | D3DFVF_NORMAL);
m_iRenderedSplatNumSqSum = 0;
m_iRenderedPatchNum = 0;
m_iRenderedSplatNum = 0;
m_RenderedTextureNumVector.clear();
std::pair<float, long> fog_far(fFogFarDistance+1600.0f, 0);
std::pair<float, long> fog_near(fFogNearDistance-3200.0f, 0);
std::vector<std::pair<float ,long> >::iterator far_it = std::upper_bound(m_PatchVector.begin(),m_PatchVector.end(),fog_far);
std::vector<std::pair<float ,long> >::iterator near_it = std::upper_bound(m_PatchVector.begin(),m_PatchVector.end(),fog_near);
// NOTE: Word Editor 툴에서는 fog far보다 멀리있는 물체를 텍스쳐 없이 그리는 작업을 하지 않음
#ifdef WORLD_EDITOR
near_it = m_PatchVector.begin();
far_it = m_PatchVector.end();
#endif
WORD wPrimitiveCount;
D3DPRIMITIVETYPE ePrimitiveType;
BYTE byCUrrentLODLevel = 0;
float fLODLevel1Distance = __GetNoFogDistance();
float fLODLevel2Distance = __GetFogDistance();
SelectIndexBuffer(0, &wPrimitiveCount, &ePrimitiveType);
DWORD dwFogEnable = STATEMANAGER.GetRenderState(D3DRS_FOGENABLE);
std::vector<std::pair<float, long> >::iterator it = m_PatchVector.begin();
// NOTE: 맵툴에서는 view ~ fog near 사이의 지형을 fog disabled 상태로 그리는 작업을 하지 않음.
#ifndef WORLD_EDITOR
STATEMANAGER.SetRenderState(D3DRS_FOGENABLE, FALSE);
for( ; it != near_it; ++it)
{
if (byCUrrentLODLevel == 0 && fLODLevel1Distance <= it->first)
{
byCUrrentLODLevel = 1;
SelectIndexBuffer(1, &wPrimitiveCount, &ePrimitiveType);
}
else if (byCUrrentLODLevel == 1 && fLODLevel2Distance <= it->first)
{
byCUrrentLODLevel = 2;
SelectIndexBuffer(2, &wPrimitiveCount, &ePrimitiveType);
}
__HardwareTransformPatch_RenderPatchSplat(it->second, wPrimitiveCount, ePrimitiveType);
if (m_iRenderedSplatNum >= m_iSplatLimit)
break;
if (m_bDrawWireFrame)
DrawWireFrame(it->second, wPrimitiveCount, ePrimitiveType);
}
#endif
STATEMANAGER.SetRenderState(D3DRS_FOGENABLE, dwFogEnable);
if (m_iRenderedSplatNum < m_iSplatLimit)
{
for(it = near_it; it != far_it; ++it)
{
if (byCUrrentLODLevel == 0 && fLODLevel1Distance <= it->first)
{
byCUrrentLODLevel = 1;
SelectIndexBuffer(1, &wPrimitiveCount, &ePrimitiveType);
}
else if (byCUrrentLODLevel == 1 && fLODLevel2Distance <= it->first)
{
byCUrrentLODLevel = 2;
SelectIndexBuffer(2, &wPrimitiveCount, &ePrimitiveType);
}
__HardwareTransformPatch_RenderPatchSplat(it->second, wPrimitiveCount, ePrimitiveType);
if (m_iRenderedSplatNum >= m_iSplatLimit)
break;
if (m_bDrawWireFrame)
DrawWireFrame(it->second, wPrimitiveCount, ePrimitiveType);
}
}
STATEMANAGER.SetRenderState(D3DRS_FOGENABLE, FALSE);
STATEMANAGER.SetRenderState(D3DRS_LIGHTING, FALSE);
STATEMANAGER.SetTexture(0, NULL);
STATEMANAGER.SetTextureStageState(0, D3DTSS_TEXTURETRANSFORMFLAGS, FALSE);
STATEMANAGER.SetTexture(1, NULL);
STATEMANAGER.SetTextureStageState(1, D3DTSS_TEXTURETRANSFORMFLAGS, FALSE);
STATEMANAGER.SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TFACTOR);
STATEMANAGER.SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
STATEMANAGER.SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_DISABLE);
STATEMANAGER.SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_DISABLE);
STATEMANAGER.SetTextureStageState(1, D3DTSS_ALPHAOP, D3DTOP_DISABLE);
if (m_iRenderedSplatNum < m_iSplatLimit)
{
for(it = far_it; it != m_PatchVector.end(); ++it)
{
if (byCUrrentLODLevel == 0 && fLODLevel1Distance <= it->first)
{
byCUrrentLODLevel = 1;
SelectIndexBuffer(1, &wPrimitiveCount, &ePrimitiveType);
}
else if (byCUrrentLODLevel == 1 && fLODLevel2Distance <= it->first)
{
byCUrrentLODLevel = 2;
SelectIndexBuffer(2, &wPrimitiveCount, &ePrimitiveType);
}
__HardwareTransformPatch_RenderPatchNone(it->second, wPrimitiveCount, ePrimitiveType);
if (m_iRenderedSplatNum >= m_iSplatLimit)
break;
if (m_bDrawWireFrame)
DrawWireFrame(it->second, wPrimitiveCount, ePrimitiveType);
}
}
STATEMANAGER.SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE);
STATEMANAGER.SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_CURRENT);
STATEMANAGER.SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_MODULATE);
STATEMANAGER.SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE);
STATEMANAGER.SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1);
STATEMANAGER.SetTextureStageState(1, D3DTSS_COLORARG1, D3DTA_CURRENT);
STATEMANAGER.SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
STATEMANAGER.SetTextureStageState(1, D3DTSS_ALPHAARG1, D3DTA_TEXTURE);
STATEMANAGER.SetTextureStageState(1, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1);
STATEMANAGER.SetRenderState(D3DRS_FOGENABLE, dwFogEnable);
STATEMANAGER.SetRenderState(D3DRS_LIGHTING, TRUE);
std::sort(m_RenderedTextureNumVector.begin(),m_RenderedTextureNumVector.end());
//////////////////////////////////////////////////////////////////////////
// Render State & TextureStageState
STATEMANAGER.RestoreRenderState(D3DRS_TEXTUREFACTOR);
STATEMANAGER.RestoreTransform(D3DTS_TEXTURE0);
STATEMANAGER.RestoreTransform(D3DTS_TEXTURE1);
STATEMANAGER.RestoreTextureStageState(0, D3DTSS_TEXCOORDINDEX);
STATEMANAGER.RestoreTextureStageState(0, D3DTSS_TEXTURETRANSFORMFLAGS);
STATEMANAGER.RestoreTextureStageState(1, D3DTSS_TEXCOORDINDEX);
STATEMANAGER.RestoreTextureStageState(1, D3DTSS_TEXTURETRANSFORMFLAGS);
STATEMANAGER.RestoreRenderState(D3DRS_ALPHABLENDENABLE);
STATEMANAGER.RestoreRenderState(D3DRS_ALPHATESTENABLE);
STATEMANAGER.RestoreRenderState(D3DRS_ALPHAREF);
STATEMANAGER.RestoreRenderState(D3DRS_ALPHAFUNC);
// Render State & TextureStageState
//////////////////////////////////////////////////////////////////////////
}
void CMapOutdoor::__HardwareTransformPatch_RenderPatchSplat(long patchnum, WORD wPrimitiveCount, D3DPRIMITIVETYPE ePrimitiveType)
{
assert(NULL!=m_pTerrainPatchProxyList && "__HardwareTransformPatch_RenderPatchSplat");
CTerrainPatchProxy * pTerrainPatchProxy = &m_pTerrainPatchProxyList[patchnum];
if (!pTerrainPatchProxy->isUsed())
return;
long sPatchNum = pTerrainPatchProxy->GetPatchNum();
if (sPatchNum < 0)
return;
BYTE ucTerrainNum = pTerrainPatchProxy->GetTerrainNum();
if (0xFF == ucTerrainNum)
return;
CTerrain * pTerrain;
if (!GetTerrainPointer(ucTerrainNum, &pTerrain))
return;
DWORD dwFogColor;
if (mc_pEnvironmentData)
dwFogColor=mc_pEnvironmentData->FogColor;
else
dwFogColor=0xffffffff;
WORD wCoordX, wCoordY;
pTerrain->GetCoordinate(&wCoordX, &wCoordY);
TTerrainSplatPatch & rTerrainSplatPatch = pTerrain->GetTerrainSplatPatch();
D3DXMATRIX matTexTransform, matSplatAlphaTexTransform, matSplatColorTexTransform;
m_matWorldForCommonUse._41 = -(float) (wCoordX * CTerrainImpl::TERRAIN_XSIZE);
m_matWorldForCommonUse._42 = (float) (wCoordY * CTerrainImpl::TERRAIN_YSIZE);
D3DXMatrixMultiply(&matTexTransform, &m_matViewInverse, &m_matWorldForCommonUse);
D3DXMatrixMultiply(&matSplatAlphaTexTransform, &matTexTransform, &m_matSplatAlpha);
STATEMANAGER.SetTransform(D3DTS_TEXTURE1, &matSplatAlphaTexTransform);
D3DXMATRIX matTiling;
D3DXMatrixScaling(&matTiling, 1.0f/640.0f, -1.0f/640.0f, 0.0f);
matTiling._41=0.0f;
matTiling._42=0.0f;
D3DXMatrixMultiply(&matSplatColorTexTransform, &m_matViewInverse, &matTiling);
STATEMANAGER.SetTransform(D3DTS_TEXTURE0, &matSplatColorTexTransform);
CGraphicVertexBuffer* pkVB=pTerrainPatchProxy->HardwareTransformPatch_GetVertexBufferPtr();
if (!pkVB)
return;
STATEMANAGER.SetStreamSource(0, pkVB->GetD3DVertexBuffer(), m_iPatchTerrainVertexSize);
STATEMANAGER.SetRenderState(D3DRS_LIGHTING, FALSE);
int iPrevRenderedSplatNum=m_iRenderedSplatNum;
#ifdef WORLD_EDITOR
int nRenderTextureCount = 0;
// if (!m_bShowEntirePatchTextureCount && !(GetAsyncKeyState(VK_LCONTROL) & 0x8000) )
if (1)
{
for (DWORD j = 1; j < pTerrain->GetNumTextures(); ++j)
{
TTerainSplat & rSplat = rTerrainSplatPatch.Splats[j];
if (!rSplat.Active)
continue;
if (rTerrainSplatPatch.PatchTileCount[sPatchNum][j] == 0)
continue;
++nRenderTextureCount;
}
DWORD dwTextureFactor = STATEMANAGER.GetRenderState(D3DRS_TEXTUREFACTOR);
int TextureCountThreshold = 8;
DWORD dwTFactor = 0xFFFFFFFF;
if (GetAsyncKeyState(VK_LSHIFT) & 0x8000)
{
if (GetAsyncKeyState(VK_1) & 0x8000)
{
TextureCountThreshold = 2;
dwTFactor = 0xFF0000FF;
}
else if (GetAsyncKeyState(VK_2) & 0x8000)
{
TextureCountThreshold = 3;
dwTFactor = 0xFF00FF00;
}
else if (GetAsyncKeyState(VK_3) & 0x8000)
{
TextureCountThreshold = 4;
dwTFactor = 0xFF00FFFF;
}
else if (GetAsyncKeyState(VK_4) & 0x8000)
{
TextureCountThreshold = 5;
dwTFactor = 0xFFFF0000;
}
else if (GetAsyncKeyState(VK_5) & 0x8000)
{
TextureCountThreshold = 6;
dwTFactor = 0xFFFFFF00;
}
else if (GetAsyncKeyState(VK_6) & 0x8000)
{
TextureCountThreshold = 7;
dwTFactor = 0xFFFF00ff;
}
}
if (nRenderTextureCount>=TextureCountThreshold)
{
STATEMANAGER.SetRenderState(D3DRS_TEXTUREFACTOR, dwTFactor);
STATEMANAGER.SaveTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TFACTOR);
STATEMANAGER.SaveTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
STATEMANAGER.DrawIndexedPrimitive(ePrimitiveType, 0, m_iPatchTerrainVertexCount, 0, wPrimitiveCount);
STATEMANAGER.SetRenderState(D3DRS_TEXTUREFACTOR, dwTextureFactor);
STATEMANAGER.RestoreTextureStageState(0, D3DTSS_COLORARG1);
STATEMANAGER.RestoreTextureStageState(0, D3DTSS_COLOROP);
}
else
{
// 0번 텍스처
if ( 0 < rTerrainSplatPatch.PatchTileCount[sPatchNum][0] )
{
DWORD dwTextureFactorFor0Texture = STATEMANAGER.GetRenderState(D3DRS_TEXTUREFACTOR);
STATEMANAGER.SetRenderState(D3DRS_TEXTUREFACTOR, 0xFF88FF88);
STATEMANAGER.SaveTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TFACTOR);
STATEMANAGER.SaveTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
STATEMANAGER.DrawIndexedPrimitive(ePrimitiveType, 0, m_iPatchTerrainVertexCount, 0, wPrimitiveCount);
STATEMANAGER.SetRenderState(D3DRS_TEXTUREFACTOR, dwTextureFactorFor0Texture);
STATEMANAGER.RestoreTextureStageState(0, D3DTSS_COLORARG1);
STATEMANAGER.RestoreTextureStageState(0, D3DTSS_COLOROP);
}
for (DWORD j = 1; j < pTerrain->GetNumTextures(); ++j)
{
TTerainSplat & rSplat = rTerrainSplatPatch.Splats[j];
if (!rSplat.Active)
continue;
DWORD dwTextureCount = rTerrainSplatPatch.PatchTileCount[sPatchNum][j];
if (dwTextureCount == 0)
continue;
DWORD dwTextureFactorForTextureBalance = 0xFFFFFFFF;
if (!(GetAsyncKeyState(VK_LSHIFT) & 0x8000))
{
const TTerrainTexture & rTexture = m_TextureSet.GetTexture(j);
D3DXMatrixMultiply(&matSplatColorTexTransform, &m_matViewInverse, &rTexture.m_matTransform);
STATEMANAGER.SetTransform(D3DTS_TEXTURE0, &matSplatColorTexTransform);
STATEMANAGER.SetTexture(0, rTexture.pd3dTexture);
STATEMANAGER.SetTexture(1, rSplat.pd3dTexture);
STATEMANAGER.DrawIndexedPrimitive(ePrimitiveType, 0, m_iPatchTerrainVertexCount, 0, wPrimitiveCount);
}
else
{
if (dwTextureCount < 71)
{
dwTextureFactorForTextureBalance = STATEMANAGER.GetRenderState(D3DRS_TEXTUREFACTOR);
if (dwTextureCount < 51)
STATEMANAGER.SetRenderState(D3DRS_TEXTUREFACTOR, 0xFFFF0000);
else
STATEMANAGER.SetRenderState(D3DRS_TEXTUREFACTOR, 0xFF0000FF);
STATEMANAGER.SaveTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TFACTOR);
STATEMANAGER.SaveTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
STATEMANAGER.SetTexture(0, NULL);
}
else
{
const TTerrainTexture & rTexture = m_TextureSet.GetTexture(j);
D3DXMatrixMultiply(&matSplatColorTexTransform, &m_matViewInverse, &rTexture.m_matTransform);
STATEMANAGER.SetTransform(D3DTS_TEXTURE0, &matSplatColorTexTransform);
STATEMANAGER.SetTexture(0, rTexture.pd3dTexture);
}
STATEMANAGER.SetTexture(1, rSplat.pd3dTexture);
STATEMANAGER.DrawIndexedPrimitive(ePrimitiveType, 0, m_iPatchTerrainVertexCount, 0, wPrimitiveCount);
if (dwTextureCount < 71)
{
STATEMANAGER.SetRenderState(D3DRS_TEXTUREFACTOR, dwTextureFactorForTextureBalance);
STATEMANAGER.RestoreTextureStageState(0, D3DTSS_COLORARG1);
STATEMANAGER.RestoreTextureStageState(0, D3DTSS_COLOROP);
}
}
std::vector<int>::iterator aIterator = std::find(m_RenderedTextureNumVector.begin(), m_RenderedTextureNumVector.end(), (int)j);
if (aIterator == m_RenderedTextureNumVector.end())
m_RenderedTextureNumVector.push_back(j);
++m_iRenderedSplatNum;
if (m_iRenderedSplatNum >= m_iSplatLimit)
break;
}
}
}
else
{
int TextureCountThreshold = 6;
DWORD dwTFactor = 0xFFFF00FF;
if (GetAsyncKeyState(VK_LSHIFT) & 0x8000)
{
if (GetAsyncKeyState(VK_1) & 0x8000)
{
TextureCountThreshold = 1;
dwTFactor = 0xFF0000FF;
}
else if (GetAsyncKeyState(VK_2) & 0x8000)
{
TextureCountThreshold = 2;
dwTFactor = 0xFF00FF00;
}
else if (GetAsyncKeyState(VK_3) & 0x8000)
{
TextureCountThreshold = 3;
dwTFactor = 0xFF00FFFF;
}
else if (GetAsyncKeyState(VK_4) & 0x8000)
{
TextureCountThreshold = 4;
dwTFactor = 0xFFFF0000;
}
else if (GetAsyncKeyState(VK_5) & 0x8000)
{
TextureCountThreshold = 5;
dwTFactor = 0xFFFFFF00;
}
}
for (DWORD j = 1; j < pTerrain->GetNumTextures(); ++j)
{
TTerainSplat & rSplat = rTerrainSplatPatch.Splats[j];
if (!rSplat.Active)
continue;
if (rTerrainSplatPatch.PatchTileCount[sPatchNum][j] == 0)
continue;
DWORD dwTextureFactor;
if (nRenderTextureCount>=TextureCountThreshold)
{
dwTextureFactor = STATEMANAGER.GetRenderState(D3DRS_TEXTUREFACTOR);
STATEMANAGER.SetRenderState(D3DRS_TEXTUREFACTOR, dwTFactor);
STATEMANAGER.SaveTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TFACTOR);
STATEMANAGER.SaveTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
STATEMANAGER.SetTexture(0, NULL);
}
else
{
const TTerrainTexture & rTexture = m_TextureSet.GetTexture(j);
D3DXMatrixMultiply(&matSplatColorTexTransform, &m_matViewInverse, &rTexture.m_matTransform);
STATEMANAGER.SetTransform(D3DTS_TEXTURE0, &matSplatColorTexTransform);
STATEMANAGER.SetTexture(0, rTexture.pd3dTexture);
}
STATEMANAGER.SetTexture(1, rSplat.pd3dTexture);
STATEMANAGER.DrawIndexedPrimitive(ePrimitiveType, 0, m_iPatchTerrainVertexCount, 0, wPrimitiveCount);
if (nRenderTextureCount>=TextureCountThreshold)
{
STATEMANAGER.SetRenderState(D3DRS_TEXTUREFACTOR, dwTextureFactor);
STATEMANAGER.RestoreTextureStageState(0, D3DTSS_COLORARG1);
STATEMANAGER.RestoreTextureStageState(0, D3DTSS_COLOROP);
}
++nRenderTextureCount;
std::vector<int>::iterator aIterator = std::find(m_RenderedTextureNumVector.begin(), m_RenderedTextureNumVector.end(), (int)j);
if (aIterator == m_RenderedTextureNumVector.end())
m_RenderedTextureNumVector.push_back(j);
++m_iRenderedSplatNum;
if (m_iRenderedSplatNum >= m_iSplatLimit)
break;
}
}
#else
bool isFirst=true;
for (DWORD j = 1; j < pTerrain->GetNumTextures(); ++j)
{
TTerainSplat & rSplat = rTerrainSplatPatch.Splats[j];
if (!rSplat.Active)
continue;
if (rTerrainSplatPatch.PatchTileCount[sPatchNum][j] == 0)
continue;
const TTerrainTexture & rTexture = m_TextureSet.GetTexture(j);
D3DXMatrixMultiply(&matSplatColorTexTransform, &m_matViewInverse, &rTexture.m_matTransform);
STATEMANAGER.SetTransform(D3DTS_TEXTURE0, &matSplatColorTexTransform);
if (isFirst)
{
STATEMANAGER.SetTextureStageState(1, D3DTSS_ALPHAOP, D3DTOP_DISABLE);
STATEMANAGER.SetTexture(0, rTexture.pd3dTexture);
STATEMANAGER.SetTexture(1, rSplat.pd3dTexture);
STATEMANAGER.DrawIndexedPrimitive(ePrimitiveType, 0, m_iPatchTerrainVertexCount, 0, wPrimitiveCount);
STATEMANAGER.SetTextureStageState(1, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1);
isFirst=false;
}
else
{
STATEMANAGER.SetTexture(0, rTexture.pd3dTexture);
STATEMANAGER.SetTexture(1, rSplat.pd3dTexture);
STATEMANAGER.DrawIndexedPrimitive(ePrimitiveType, 0, m_iPatchTerrainVertexCount, 0, wPrimitiveCount);
}
std::vector<int>::iterator aIterator = std::find(m_RenderedTextureNumVector.begin(), m_RenderedTextureNumVector.end(), (int)j);
if (aIterator == m_RenderedTextureNumVector.end())
m_RenderedTextureNumVector.push_back(j);
++m_iRenderedSplatNum;
if (m_iRenderedSplatNum >= m_iSplatLimit)
break;
}
/*
if (GetAsyncKeyState(VK_CAPITAL) & 0x8000)
{
TTerainSplat & rSplat = rTerrainSplatPatch.Splats[200];
if (rSplat.Active)
{
const TTerrainTexture & rTexture = m_TextureSet.GetTexture(1);
D3DXMatrixMultiply(&matSplatColorTexTransform, &m_matViewInverse, &rTexture.m_matTransform);
STATEMANAGER.SetTransform(D3DTS_TEXTURE0, &matSplatColorTexTransform);
STATEMANAGER.SetTexture(0, NULL);
STATEMANAGER.SetTexture(1, rSplat.pd3dTexture);
STATEMANAGER.DrawIndexedPrimitive(ePrimitiveType, 0, m_iPatchTerrainVertexCount, 0, wPrimitiveCount);
}
}
*/
#endif
// 그림자
if (m_bDrawShadow)
{
STATEMANAGER.SetRenderState(D3DRS_LIGHTING, TRUE);
STATEMANAGER.SetRenderState(D3DRS_FOGCOLOR, 0xFFFFFFFF);
STATEMANAGER.SetRenderState(D3DRS_SRCBLEND, D3DBLEND_ZERO);
STATEMANAGER.SetRenderState(D3DRS_DESTBLEND, D3DBLEND_SRCCOLOR);
D3DXMATRIX matShadowTexTransform;
D3DXMatrixMultiply(&matShadowTexTransform, &matTexTransform, &m_matStaticShadow);
STATEMANAGER.SetTransform(D3DTS_TEXTURE0, &matShadowTexTransform);
STATEMANAGER.SetTexture(0, pTerrain->GetShadowTexture());
STATEMANAGER.SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE);
STATEMANAGER.SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_CURRENT);
STATEMANAGER.SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_MODULATE);
STATEMANAGER.SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE);
STATEMANAGER.SetTextureStageState(0, D3DTSS_ALPHAARG2, D3DTA_CURRENT);
STATEMANAGER.SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_DISABLE);
STATEMANAGER.SetTextureStageState(0, D3DTSS_ADDRESSU, D3DTADDRESS_CLAMP);
STATEMANAGER.SetTextureStageState(0, D3DTSS_ADDRESSV, D3DTADDRESS_CLAMP);
if (m_bDrawChrShadow)
{
STATEMANAGER.SetTransform(D3DTS_TEXTURE1, &m_matDynamicShadow);
STATEMANAGER.SetTexture(1, m_lpCharacterShadowMapTexture);
STATEMANAGER.SetTextureStageState(1, D3DTSS_COLORARG1, D3DTA_TEXTURE);
STATEMANAGER.SetTextureStageState(1, D3DTSS_COLORARG2, D3DTA_CURRENT);
STATEMANAGER.SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_MODULATE);
STATEMANAGER.SetTextureStageState(1, D3DTSS_ALPHAOP, D3DTOP_DISABLE);
STATEMANAGER.SetTextureStageState(1, D3DTSS_ADDRESSU, D3DTADDRESS_CLAMP);
STATEMANAGER.SetTextureStageState(1, D3DTSS_ADDRESSV, D3DTADDRESS_CLAMP);
}
else
{
STATEMANAGER.SetTexture(1, NULL);
}
ms_faceCount += wPrimitiveCount;
STATEMANAGER.DrawIndexedPrimitive(ePrimitiveType, 0, m_iPatchTerrainVertexCount, 0, wPrimitiveCount);
++m_iRenderedSplatNum;
if (m_bDrawChrShadow)
{
STATEMANAGER.SetTextureStageState(1, D3DTSS_COLORARG1, D3DTA_CURRENT);
STATEMANAGER.SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
STATEMANAGER.SetTextureStageState(1, D3DTSS_ALPHAARG1, D3DTA_TEXTURE);
STATEMANAGER.SetTextureStageState(1, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1);
}
STATEMANAGER.SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE);
STATEMANAGER.SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_CURRENT);
STATEMANAGER.SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_MODULATE);
STATEMANAGER.SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE);
STATEMANAGER.SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1);
STATEMANAGER.SetTextureStageState(0, D3DTSS_ADDRESSU, D3DTADDRESS_WRAP);
STATEMANAGER.SetTextureStageState(0, D3DTSS_ADDRESSV, D3DTADDRESS_WRAP);
STATEMANAGER.SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);
STATEMANAGER.SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA);
STATEMANAGER.SetRenderState(D3DRS_FOGCOLOR, dwFogColor);
STATEMANAGER.SetRenderState(D3DRS_LIGHTING, FALSE);
}
++m_iRenderedPatchNum;
int iCurRenderedSplatNum=m_iRenderedSplatNum-iPrevRenderedSplatNum;
m_iRenderedSplatNumSqSum+=iCurRenderedSplatNum*iCurRenderedSplatNum;
}
void CMapOutdoor::__HardwareTransformPatch_RenderPatchNone(long patchnum, WORD wPrimitiveCount, D3DPRIMITIVETYPE ePrimitiveType)
{
assert(NULL!=m_pTerrainPatchProxyList && "__HardwareTransformPatch_RenderPatchNone");
CTerrainPatchProxy * pTerrainPatchProxy = &m_pTerrainPatchProxyList[patchnum];
if (!pTerrainPatchProxy->isUsed())
return;
CGraphicVertexBuffer* pkVB=pTerrainPatchProxy->HardwareTransformPatch_GetVertexBufferPtr();
if (!pkVB)
return;
STATEMANAGER.SetStreamSource(0, pkVB->GetD3DVertexBuffer(), m_iPatchTerrainVertexSize);
STATEMANAGER.DrawIndexedPrimitive(ePrimitiveType, 0, m_iPatchTerrainVertexCount, 0, wPrimitiveCount);
}
@@ -0,0 +1,815 @@
// Platform copy of 40250 GameLib/MapOutdoorRenderSTP.cpp (software-transform terrain patches), as is
// apart from the includes and the native-terrain gate: the Godot Metin2World adapter draws the terrain
// unless IsNativeTerrainRenderEnabled() (see MapOutdoorRenderHTP.cpp). 40250 takes this path when
// SOFTWARE_TILING is 1 in metin2.cfg, or with auto tiling on a device without fast T&L.
#include "GameLib/StdAfx.h"
#include "GameLib/MapOutdoor.h"
#include "GameLib/TerrainPatch.h"
#include "GameLib/TerrainQuadtree.h"
#include "EterLib/Camera.h"
#include "EterLib/StateManager.h"
#include "../EterLib/RenderCommands3D.h"
struct SoftwareTransformPatch_SSplatVertex
{
D3DXVECTOR4 kPosition;
DWORD dwDiffuse;
DWORD dwSpecular;
D3DXVECTOR2 kTex1;
D3DXVECTOR2 kTex2;
};
void CMapOutdoor::__RenderTerrain_RenderSoftwareTransformPatch()
{
// PORT: see the file comment.
if (!IsNativeTerrainRenderEnabled())
return;
SoftwareTransformPatch_SRenderState kTPRS;
DWORD dwFogEnable = STATEMANAGER.GetRenderState(D3DRS_FOGENABLE);
__SoftwareTransformPatch_ApplyRenderState();
__SoftwareTransformPatch_BuildPipeline(kTPRS);
std::pair<float, long> fog_far(kTPRS.m_fFogFarDistance+800.0f, 0);
std::pair<float, long> fog_near(kTPRS.m_fFogNearDistance-3200.0f, 0);
std::vector<std::pair<float ,long> >::iterator far_it = std::upper_bound(m_PatchVector.begin(),m_PatchVector.end(),fog_far);
std::vector<std::pair<float ,long> >::iterator near_it = std::upper_bound(m_PatchVector.begin(),m_PatchVector.end(),fog_near);
WORD wPrimitiveCount;
D3DPRIMITIVETYPE ePrimitiveType;
BYTE byCUrrentLODLevel = 0;
float fLODLevel1Distance = __GetNoFogDistance();
float fLODLevel2Distance = __GetFogDistance();
SelectIndexBuffer(0, &wPrimitiveCount, &ePrimitiveType);
STATEMANAGER.SetVertexShader(D3DFVF_XYZRHW|D3DFVF_DIFFUSE|D3DFVF_SPECULAR|D3DFVF_TEX2);
std::vector<std::pair<float, long> >::iterator it = m_PatchVector.begin();
for( ; it != near_it; ++it)
{
if (byCUrrentLODLevel == 0 && fLODLevel1Distance <= it->first)
{
byCUrrentLODLevel = 1;
SelectIndexBuffer(1, &wPrimitiveCount, &ePrimitiveType);
}
else if (byCUrrentLODLevel == 1 && fLODLevel2Distance <= it->first)
{
byCUrrentLODLevel = 2;
SelectIndexBuffer(2, &wPrimitiveCount, &ePrimitiveType);
}
__SoftwareTransformPatch_RenderPatchSplat(kTPRS, it->second, wPrimitiveCount, ePrimitiveType, false);
if (m_iRenderedSplatNum >= m_iSplatLimit)
break;
}
if (m_iRenderedSplatNum < m_iSplatLimit)
{
for(it = near_it; it != far_it; ++it)
{
if (byCUrrentLODLevel == 0 && fLODLevel1Distance <= it->first)
{
byCUrrentLODLevel = 1;
SelectIndexBuffer(1, &wPrimitiveCount, &ePrimitiveType);
}
else if (byCUrrentLODLevel == 1 && fLODLevel2Distance <= it->first)
{
byCUrrentLODLevel = 2;
SelectIndexBuffer(2, &wPrimitiveCount, &ePrimitiveType);
}
__SoftwareTransformPatch_RenderPatchSplat(kTPRS, it->second, wPrimitiveCount, ePrimitiveType, true);
if (m_iRenderedSplatNum >= m_iSplatLimit)
break;
}
}
STATEMANAGER.SetTexture(0, NULL);
STATEMANAGER.SetTexture(1, NULL);
STATEMANAGER.SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TFACTOR);
STATEMANAGER.SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
STATEMANAGER.SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_DISABLE);
STATEMANAGER.SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_DISABLE);
STATEMANAGER.SetTextureStageState(1, D3DTSS_ALPHAOP, D3DTOP_DISABLE);
STATEMANAGER.SetVertexShader(D3DFVF_XYZRHW);
if (IsFastTNL())
{
if (byCUrrentLODLevel != 2)
{
byCUrrentLODLevel = 2;
SelectIndexBuffer(2, &wPrimitiveCount, &ePrimitiveType);
}
if (m_iRenderedSplatNum < m_iSplatLimit)
{
for(it = far_it; it != m_PatchVector.end(); ++it)
{
__SoftwareTransformPatch_RenderPatchNone(kTPRS, it->second, wPrimitiveCount, ePrimitiveType);
if (m_iRenderedSplatNum >= m_iSplatLimit)
break;
}
}
}
//////////////////////////////////////////////////////////////////////////
// Render State & TextureStageState
__SoftwareTransformPatch_RestoreRenderState(dwFogEnable);
}
void CMapOutdoor::__SoftwareTransformPatch_RenderPatchSplat(SoftwareTransformPatch_SRenderState& rkTPRS, long patchnum, WORD wPrimitiveCount, D3DPRIMITIVETYPE ePrimitiveType, bool isFogEnable)
{
assert(NULL!=m_pTerrainPatchProxyList && "CMapOutdoor::__SoftwareTransformPatch_RenderPatchSplat");
CTerrainPatchProxy * pTerrainPatchProxy = &m_pTerrainPatchProxyList[patchnum];
if (!pTerrainPatchProxy->isUsed())
return;
bool isDynamicShadow = pTerrainPatchProxy->IsIn(rkTPRS.m_v3Player, 3000.0f);
if (!m_bDrawChrShadow)
isDynamicShadow = false;
long sPatchNum = pTerrainPatchProxy->GetPatchNum();
if (sPatchNum < 0)
return;
BYTE ucTerrainNum = pTerrainPatchProxy->GetTerrainNum();
if (0xFF == ucTerrainNum)
return;
CTerrain * pTerrain;
if (!GetTerrainPointer(ucTerrainNum, &pTerrain))
return;
WORD wCoordX, wCoordY;
pTerrain->GetCoordinate(&wCoordX, &wCoordY);
TTerrainSplatPatch & rTerrainSplatPatch = pTerrain->GetTerrainSplatPatch();
SoftwareTransformPatch_STLVertex akTransVertex[CTerrainPatch::TERRAIN_VERTEX_COUNT];
if (!__SoftwareTransformPatch_SetTransform(rkTPRS, akTransVertex, *pTerrainPatchProxy, wCoordX, wCoordY, isFogEnable, isDynamicShadow))
return;
if (!__SoftwareTransformPatch_SetSplatStream(akTransVertex))
return;
if (isFogEnable)
{
STATEMANAGER.SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE);
STATEMANAGER.SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_TFACTOR);
STATEMANAGER.SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_BLENDDIFFUSEALPHA);
}
else
{
STATEMANAGER.SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE);
STATEMANAGER.SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_DIFFUSE);
STATEMANAGER.SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
}
int iPrevRenderedSplatNum=m_iRenderedSplatNum;
bool isFirst=true;
for (DWORD j = 1; j < pTerrain->GetNumTextures(); ++j)
{
TTerainSplat & rSplat = rTerrainSplatPatch.Splats[j];
if (!rSplat.Active)
continue;
if (rTerrainSplatPatch.PatchTileCount[sPatchNum][j] == 0)
continue;
const TTerrainTexture & rTexture = m_TextureSet.GetTexture(j);
if (isFirst)
{
STATEMANAGER.SetTextureStageState(1, D3DTSS_ALPHAOP, D3DTOP_SELECTARG2);
STATEMANAGER.SetTexture(0, rTexture.pd3dTexture);
STATEMANAGER.SetTexture(1, rSplat.pd3dTexture);
STATEMANAGER.DrawIndexedPrimitive(ePrimitiveType, 0, m_iPatchTerrainVertexCount, 0, wPrimitiveCount);
STATEMANAGER.SetTextureStageState(1, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1);
isFirst=false;
}
else
{
STATEMANAGER.SetTexture(0, rTexture.pd3dTexture);
STATEMANAGER.SetTexture(1, rSplat.pd3dTexture);
STATEMANAGER.DrawIndexedPrimitive(ePrimitiveType, 0, m_iPatchTerrainVertexCount, 0, wPrimitiveCount);
}
std::vector<int>::iterator aIterator = std::find(m_RenderedTextureNumVector.begin(), m_RenderedTextureNumVector.end(), (int)j);
if (aIterator == m_RenderedTextureNumVector.end())
m_RenderedTextureNumVector.push_back(j);
++m_iRenderedSplatNum;
if (m_iRenderedSplatNum >= m_iSplatLimit)
break;
}
// 그림자
if (m_bDrawShadow)
{
__SoftwareTransformPatch_SetShadowStream(akTransVertex);
__SoftwareTransformPatch_ApplyStaticShadowRenderState();
if (isDynamicShadow)
__SoftwareTransformPatch_ApplyDynamicShadowRenderState();
else
__SoftwareTransformPatch_ApplyFogShadowRenderState();
if (isFogEnable)
{
STATEMANAGER.SetRenderState(D3DRS_FOGENABLE, TRUE);
STATEMANAGER.SetRenderState(D3DRS_FOGCOLOR, 0xFFFFFFFF);
STATEMANAGER.SetTexture(0, pTerrain->GetShadowTexture());
STATEMANAGER.DrawIndexedPrimitive(ePrimitiveType, 0, m_iPatchTerrainVertexCount, 0, wPrimitiveCount);
STATEMANAGER.SetRenderState(D3DRS_FOGCOLOR, rkTPRS.m_dwFogColor);
STATEMANAGER.SetRenderState(D3DRS_FOGENABLE, FALSE);
}
else
{
STATEMANAGER.SetTexture(0, pTerrain->GetShadowTexture());
STATEMANAGER.DrawIndexedPrimitive(ePrimitiveType, 0, m_iPatchTerrainVertexCount, 0, wPrimitiveCount);
}
if (isDynamicShadow)
__SoftwareTransformPatch_RestoreDynamicShadowRenderState();
else
__SoftwareTransformPatch_RestoreFogShadowRenderState();
ms_faceCount += wPrimitiveCount;
++m_iRenderedSplatNum;
__SoftwareTransformPatch_RestoreStaticShadowRenderState();
}
++m_iRenderedPatchNum;
int iCurRenderedSplatNum=m_iRenderedSplatNum-iPrevRenderedSplatNum;
m_iRenderedSplatNumSqSum+=iCurRenderedSplatNum*iCurRenderedSplatNum;
}
void CMapOutdoor::__SoftwareTransformPatch_RenderPatchNone(SoftwareTransformPatch_SRenderState& rkTPRS, long patchnum, WORD wPrimitiveCount, D3DPRIMITIVETYPE ePrimitiveType)
{
assert(NULL!=m_pTerrainPatchProxyList && "CMapOutdoor::__SoftwareTransformPatch_RenderPatchNone");
CTerrainPatchProxy * pTerrainPatchProxy = &m_pTerrainPatchProxyList[patchnum];
if (!pTerrainPatchProxy->isUsed())
return;
long sPatchNum = pTerrainPatchProxy->GetPatchNum();
if (sPatchNum < 0)
return;
BYTE ucTerrainNum = pTerrainPatchProxy->GetTerrainNum();
if (0xFF == ucTerrainNum)
return;
CTerrain * pTerrain;
if (!GetTerrainPointer(ucTerrainNum, &pTerrain))
return;
WORD wCoordX, wCoordY;
pTerrain->GetCoordinate(&wCoordX, &wCoordY);
SoftwareTransformPatch_SSourceVertex* akSrcVertex=pTerrainPatchProxy->SoftwareTransformPatch_GetTerrainVertexDataPtr();
if (!akSrcVertex)
return;
float fScreenHalfWidth=rkTPRS.m_fScreenHalfWidth;
float fScreenHalfHeight=rkTPRS.m_fScreenHalfHeight;
D3DXMATRIX m4Frustum=rkTPRS.m_m4Frustum;
SoftwareTransformPatch_STVertex akTransVertex[CTerrainPatch::TERRAIN_VERTEX_COUNT];
D3DXVECTOR4* akPosition=(D3DXVECTOR4*)akTransVertex;
D3DXVECTOR4* pkPosition;
for (UINT uIndex=0; uIndex!=CTerrainPatch::TERRAIN_VERTEX_COUNT; ++uIndex)
{
pkPosition=akPosition+uIndex;
D3DXVec3Transform(pkPosition, &akSrcVertex[uIndex].kPosition, &m4Frustum);
pkPosition->w=1.0f/pkPosition->w;
pkPosition->z*=pkPosition->w;
pkPosition->y=(pkPosition->y*pkPosition->w-1.0f)*fScreenHalfHeight;
pkPosition->x=(pkPosition->x*pkPosition->w+1.0f)*fScreenHalfWidth;
}
IDirect3DVertexBuffer8* pkVB=m_kSTPD.m_pkVBNone[m_kSTPD.m_dwNonePos++];
m_kSTPD.m_dwNonePos%=SoftwareTransformPatch_SData::NONE_VB_NUM;
if (!pkVB)
return;
DWORD dwVBSize=sizeof(SoftwareTransformPatch_STVertex)*CTerrainPatch::TERRAIN_VERTEX_COUNT;
SoftwareTransformPatch_STVertex* akDstVertex;
if (FAILED(
pkVB->Lock(0, dwVBSize, (BYTE**)&akDstVertex, D3DLOCK_DISCARD)
)) return;
memcpy(akDstVertex, akTransVertex, dwVBSize);
pkVB->Unlock();
STATEMANAGER.SetStreamSource(0, pkVB, sizeof(SoftwareTransformPatch_STVertex));
STATEMANAGER.DrawIndexedPrimitive(ePrimitiveType, 0, m_iPatchTerrainVertexCount, 0, wPrimitiveCount);
ms_faceCount += wPrimitiveCount;
}
void CMapOutdoor::__SoftwareTransformPatch_ApplyStaticShadowRenderState()
{
STATEMANAGER.SetRenderState(D3DRS_SRCBLEND, D3DBLEND_ZERO);
STATEMANAGER.SetRenderState(D3DRS_DESTBLEND, D3DBLEND_SRCCOLOR);
STATEMANAGER.SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE);
STATEMANAGER.SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_DIFFUSE);
STATEMANAGER.SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_MODULATE);
STATEMANAGER.SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE);
STATEMANAGER.SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1);
STATEMANAGER.SetTextureStageState(0, D3DTSS_ADDRESSU, D3DTADDRESS_CLAMP);
STATEMANAGER.SetTextureStageState(0, D3DTSS_ADDRESSV, D3DTADDRESS_CLAMP);
}
void CMapOutdoor::__SoftwareTransformPatch_ApplyDynamicShadowRenderState()
{
STATEMANAGER.SetTexture(1, m_lpCharacterShadowMapTexture);
STATEMANAGER.SetTextureStageState(1, D3DTSS_COLORARG1, D3DTA_TEXTURE);
STATEMANAGER.SetTextureStageState(1, D3DTSS_COLORARG2, D3DTA_CURRENT);
STATEMANAGER.SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_MODULATE);
STATEMANAGER.SetTextureStageState(1, D3DTSS_ALPHAARG1, D3DTA_CURRENT);
STATEMANAGER.SetTextureStageState(1, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1);
STATEMANAGER.SetTextureStageState(1, D3DTSS_ADDRESSU, D3DTADDRESS_CLAMP);
STATEMANAGER.SetTextureStageState(1, D3DTSS_ADDRESSV, D3DTADDRESS_CLAMP);
}
void CMapOutdoor::__SoftwareTransformPatch_ApplyFogShadowRenderState()
{
STATEMANAGER.SetTexture(1, NULL);
STATEMANAGER.SetTextureStageState(1, D3DTSS_COLORARG1, D3DTA_CURRENT);
STATEMANAGER.SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
STATEMANAGER.SetTextureStageState(1, D3DTSS_ALPHAARG1, D3DTA_CURRENT);
STATEMANAGER.SetTextureStageState(1, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1);
}
void CMapOutdoor::__SoftwareTransformPatch_RestoreStaticShadowRenderState()
{
STATEMANAGER.SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE);
STATEMANAGER.SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
STATEMANAGER.SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE);
STATEMANAGER.SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1);
STATEMANAGER.SetTextureStageState(0, D3DTSS_ADDRESSU, D3DTADDRESS_WRAP);
STATEMANAGER.SetTextureStageState(0, D3DTSS_ADDRESSV, D3DTADDRESS_WRAP);
STATEMANAGER.SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);
STATEMANAGER.SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA);
}
void CMapOutdoor::__SoftwareTransformPatch_RestoreDynamicShadowRenderState()
{
STATEMANAGER.SetTexture(1, NULL);
STATEMANAGER.SetTextureStageState(1, D3DTSS_COLORARG1, D3DTA_CURRENT);
STATEMANAGER.SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
STATEMANAGER.SetTextureStageState(1, D3DTSS_ALPHAARG1, D3DTA_TEXTURE);
STATEMANAGER.SetTextureStageState(1, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1);
STATEMANAGER.SetTextureStageState(1, D3DTSS_ADDRESSU, D3DTADDRESS_CLAMP);
STATEMANAGER.SetTextureStageState(1, D3DTSS_ADDRESSV, D3DTADDRESS_CLAMP);
}
void CMapOutdoor::__SoftwareTransformPatch_RestoreFogShadowRenderState()
{
STATEMANAGER.SetRenderState(D3DRS_FOGENABLE, FALSE);
STATEMANAGER.SetTexture(1, NULL);
STATEMANAGER.SetTextureStageState(1, D3DTSS_COLORARG1, D3DTA_CURRENT);
STATEMANAGER.SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
STATEMANAGER.SetTextureStageState(1, D3DTSS_ALPHAARG1, D3DTA_TEXTURE);
STATEMANAGER.SetTextureStageState(1, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1);
}
void CMapOutdoor::__SoftwareTransformPatch_ApplyRenderState()
{
DWORD dwFogColor=0xffffffff;
if (mc_pEnvironmentData)
dwFogColor=mc_pEnvironmentData->FogColor;
BOOL isSoftwareVertexClipping=FALSE;
if (!IsTLVertexClipping())
isSoftwareVertexClipping=TRUE;
STATEMANAGER.SaveRenderState(D3DRS_SOFTWAREVERTEXPROCESSING, isSoftwareVertexClipping);
STATEMANAGER.SaveRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
STATEMANAGER.SaveRenderState(D3DRS_ALPHATESTENABLE, TRUE);
STATEMANAGER.SaveRenderState(D3DRS_ALPHAREF, 0x00000000);
STATEMANAGER.SaveRenderState(D3DRS_ALPHAFUNC, D3DCMP_GREATER);
STATEMANAGER.SaveRenderState(D3DRS_TEXTUREFACTOR, dwFogColor);
STATEMANAGER.SetRenderState(D3DRS_LIGHTING, FALSE);
STATEMANAGER.SetRenderState(D3DRS_FOGENABLE, FALSE);
STATEMANAGER.SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE);
STATEMANAGER.SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_DIFFUSE);
STATEMANAGER.SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
STATEMANAGER.SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE);
STATEMANAGER.SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1);
STATEMANAGER.SetTextureStageState(0, D3DTSS_ADDRESSU, D3DTADDRESS_WRAP);
STATEMANAGER.SetTextureStageState(0, D3DTSS_ADDRESSV, D3DTADDRESS_WRAP);
STATEMANAGER.SetBestFiltering(0);
STATEMANAGER.SetTextureStageState(1, D3DTSS_COLORARG1, D3DTA_CURRENT);
STATEMANAGER.SetTextureStageState(1, D3DTSS_COLORARG2, D3DTA_TEXTURE);
STATEMANAGER.SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
STATEMANAGER.SetTextureStageState(1, D3DTSS_ALPHAARG1, D3DTA_TEXTURE);
STATEMANAGER.SetTextureStageState(1, D3DTSS_ALPHAARG2, D3DTA_CURRENT);
STATEMANAGER.SetTextureStageState(1, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1);
STATEMANAGER.SetTextureStageState(1, D3DTSS_ADDRESSU, D3DTADDRESS_CLAMP);
STATEMANAGER.SetTextureStageState(1, D3DTSS_ADDRESSV, D3DTADDRESS_CLAMP);
STATEMANAGER.SetBestFiltering(1);
CSpeedTreeWrapper::ms_bSelfShadowOn = true;
// Render State & TextureStageState
//////////////////////////////////////////////////////////////////////////
m_iRenderedSplatNumSqSum = 0;
m_iRenderedPatchNum = 0;
m_iRenderedSplatNum = 0;
m_RenderedTextureNumVector.clear();
m_matWorldForCommonUse._41 = 0.0f;
m_matWorldForCommonUse._42 = 0.0f;
STATEMANAGER.SetTransform(D3DTS_WORLD, &m_matWorldForCommonUse);
}
void CMapOutdoor::__SoftwareTransformPatch_RestoreRenderState(DWORD dwFogEnable)
{
STATEMANAGER.SetRenderState(D3DRS_LIGHTING, TRUE);
STATEMANAGER.SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE);
STATEMANAGER.SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_CURRENT);
STATEMANAGER.SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_MODULATE);
STATEMANAGER.SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE);
STATEMANAGER.SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1);
STATEMANAGER.SetTextureStageState(1, D3DTSS_COLORARG1, D3DTA_CURRENT);
STATEMANAGER.SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
STATEMANAGER.SetTextureStageState(1, D3DTSS_ALPHAARG1, D3DTA_TEXTURE);
STATEMANAGER.SetTextureStageState(1, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1);
STATEMANAGER.SetRenderState(D3DRS_FOGENABLE, dwFogEnable);
std::sort(m_RenderedTextureNumVector.begin(),m_RenderedTextureNumVector.end());
STATEMANAGER.RestoreRenderState(D3DRS_TEXTUREFACTOR);
STATEMANAGER.RestoreRenderState(D3DRS_ALPHABLENDENABLE);
STATEMANAGER.RestoreRenderState(D3DRS_ALPHATESTENABLE);
STATEMANAGER.RestoreRenderState(D3DRS_ALPHAREF);
STATEMANAGER.RestoreRenderState(D3DRS_ALPHAFUNC);
STATEMANAGER.RestoreRenderState(D3DRS_SOFTWAREVERTEXPROCESSING);
// Render State & TextureStageState
//////////////////////////////////////////////////////////////////////////
}
void CMapOutdoor::__SoftwareTransformPatch_BuildPipeline(SoftwareTransformPatch_SRenderState& rkTPRS)
{
memset(&rkTPRS, 0, sizeof(rkTPRS));
if (mc_pEnvironmentData)
{
rkTPRS.m_dwFogColor = mc_pEnvironmentData->FogColor;
rkTPRS.m_fFogNearDistance = mc_pEnvironmentData->GetFogNearDistance();
rkTPRS.m_fFogFarDistance = mc_pEnvironmentData->GetFogFarDistance();
}
else
{
rkTPRS.m_dwFogColor = 0xffffffff;
rkTPRS.m_fFogNearDistance = 5000.0f;
rkTPRS.m_fFogFarDistance = 10000.0f;
}
UINT uScreenWidth;
UINT uScreenHeight;
CScreen::GetBackBufferSize(&uScreenWidth, &uScreenHeight);
rkTPRS.m_fScreenHalfWidth = +float(uScreenWidth) / 2.0f;
rkTPRS.m_fScreenHalfHeight = -float(uScreenHeight) / 2.0f;
STATEMANAGER.GetLight(0, &rkTPRS.m_kLight);
STATEMANAGER.GetMaterial(&rkTPRS.m_kMtrl);
D3DXMATRIX m4View;STATEMANAGER.GetTransform(D3DTS_VIEW, &m4View);
D3DXMATRIX m4Proj;STATEMANAGER.GetTransform(D3DTS_PROJECTION, &m4Proj);
D3DXMatrixMultiply(&rkTPRS.m_m4Frustum, &m4View, &m4Proj);
rkTPRS.m_v3Player.x = +m_v3Player.x;
rkTPRS.m_v3Player.y = -m_v3Player.y;
rkTPRS.m_v3Player.z = +m_v3Player.z;
rkTPRS.m_m4Proj = m4Proj;
rkTPRS.m_m4DynamicShadow = m_matLightView * m_matDynamicShadowScale;
D3DXVECTOR3 kFogNearVector;
const auto farvv = D3DXVECTOR3(0.0f, 0.0f, -rkTPRS.m_fFogNearDistance);
D3DXVec3TransformCoord(&kFogNearVector, &farvv, &rkTPRS.m_m4Proj);
D3DXVECTOR3 kFogFarVector;
const auto nearvv = D3DXVECTOR3(0.0f, 0.0f, -rkTPRS.m_fFogFarDistance);
D3DXVec3TransformCoord(&kFogFarVector, &nearvv, &rkTPRS.m_m4Proj);
float fFogNear = kFogNearVector.z;
float fFogFar = kFogFarVector.z;
float fFogLenInv = 1.0f / (fFogFar-fFogNear);
rkTPRS.m_fFogNearTransZ = fFogNear;
rkTPRS.m_fFogFarTransZ = fFogFar;
rkTPRS.m_fFogLenInv = fFogLenInv;
}
bool CMapOutdoor::__SoftwareTransformPatch_SetTransform(SoftwareTransformPatch_SRenderState& rkTPRS, SoftwareTransformPatch_STLVertex* akTransVertex, CTerrainPatchProxy& rkTerrainPatchProxy, UINT uTerrainX, UINT uTerrainY, bool isFogEnable, bool isDynamicShadow)
{
SoftwareTransformPatch_SSourceVertex* akSrcVertex=rkTerrainPatchProxy.SoftwareTransformPatch_GetTerrainVertexDataPtr();
if (!akSrcVertex)
return false;
rkTerrainPatchProxy.SoftwareTransformPatch_UpdateTerrainLighting(
m_kSTPD.m_dwLightVersion,
rkTPRS.m_kLight, rkTPRS.m_kMtrl);
D3DXVECTOR3* pkSrcPosition;
float fTilePatternX=+1/640.0f;
float fTilePatternY=-1/640.0f;
float fTerrainBaseX=-(float) (uTerrainX * CTerrainImpl::TERRAIN_XSIZE)+m_fTerrainTexCoordBase * 12.30769f;
float fTerrainBaseY=+(float) (uTerrainY * CTerrainImpl::TERRAIN_YSIZE)+m_fTerrainTexCoordBase * 12.30769f;
float fScreenHalfWidth=rkTPRS.m_fScreenHalfWidth;
float fScreenHalfHeight=rkTPRS.m_fScreenHalfHeight;
float fAlphaPatternX=m_matSplatAlpha._11;
float fAlphaPatternY=m_matSplatAlpha._22;
float fAlphaBiasX=m_matSplatAlpha._41;
float fAlphaBiasY=m_matSplatAlpha._42;
float fShadowPatternX=+m_fTerrainTexCoordBase * ((float) CTerrainImpl::PATCH_XSIZE / static_cast<float>(CTerrainImpl::XSIZE));
float fShadowPatternY=-m_fTerrainTexCoordBase * ((float) CTerrainImpl::PATCH_YSIZE / static_cast<float>(CTerrainImpl::YSIZE));
D3DXMATRIX m4Frustum=rkTPRS.m_m4Frustum;
if (isFogEnable)
{
float fFogCur;
float fFogFar=rkTPRS.m_fFogFarTransZ;
float fFogLenInv=rkTPRS.m_fFogLenInv;
float fLocalX;
float fLocalY;
SoftwareTransformPatch_STLVertex kWorkVertex;
for (UINT uIndex=0; uIndex!=CTerrainPatch::TERRAIN_VERTEX_COUNT; ++uIndex)
{
pkSrcPosition=&akSrcVertex[uIndex].kPosition;
D3DXVec3Transform(&kWorkVertex.kPosition, pkSrcPosition, &m4Frustum);
fLocalX=pkSrcPosition->x+fTerrainBaseX;
fLocalY=pkSrcPosition->y+fTerrainBaseY;
kWorkVertex.kPosition.w=1.0f/kWorkVertex.kPosition.w;
kWorkVertex.kPosition.x*=kWorkVertex.kPosition.w;
kWorkVertex.kPosition.y*=kWorkVertex.kPosition.w;
kWorkVertex.kPosition.z*=kWorkVertex.kPosition.w;
kWorkVertex.kPosition.x=(kWorkVertex.kPosition.x+1.0f)*fScreenHalfWidth;
kWorkVertex.kPosition.y=(kWorkVertex.kPosition.y-1.0f)*fScreenHalfHeight;
kWorkVertex.dwDiffuse=akSrcVertex[uIndex].dwDiffuse;
kWorkVertex.kTexTile.x=pkSrcPosition->x*fTilePatternX;
kWorkVertex.kTexTile.y=pkSrcPosition->y*fTilePatternY;
kWorkVertex.kTexAlpha.x=fLocalX*fAlphaPatternX+fAlphaBiasX;
kWorkVertex.kTexAlpha.y=fLocalY*fAlphaPatternY+fAlphaBiasY;
kWorkVertex.kTexStaticShadow.x=fLocalX*fShadowPatternX;
kWorkVertex.kTexStaticShadow.y=fLocalY*fShadowPatternY;
kWorkVertex.kTexDynamicShadow.x=0.0f;
kWorkVertex.kTexDynamicShadow.y=0.0f;
fFogCur=(fFogFar-kWorkVertex.kPosition.z)*fFogLenInv;
if (fFogCur<0.0f)
kWorkVertex.dwFog=kWorkVertex.dwDiffuse=0x0000000|(kWorkVertex.dwDiffuse&0xffffff);
else if (fFogCur>1.0f)
kWorkVertex.dwFog=kWorkVertex.dwDiffuse=0xFF000000|(kWorkVertex.dwDiffuse&0xffffff);
else
kWorkVertex.dwFog=kWorkVertex.dwDiffuse=BYTE(255.0f*fFogCur)<<24|(kWorkVertex.dwDiffuse&0xffffff);
*(akTransVertex+uIndex)=kWorkVertex;
}
}
else
{
float fLocalX;
float fLocalY;
SoftwareTransformPatch_STLVertex kWorkVertex;
for (UINT uIndex=0; uIndex!=CTerrainPatch::TERRAIN_VERTEX_COUNT; ++uIndex)
{
pkSrcPosition=&akSrcVertex[uIndex].kPosition;
D3DXVec3Transform(&kWorkVertex.kPosition, pkSrcPosition, &m4Frustum);
fLocalX=pkSrcPosition->x+fTerrainBaseX;
fLocalY=pkSrcPosition->y+fTerrainBaseY;
kWorkVertex.kPosition.w=1.0f/kWorkVertex.kPosition.w;
kWorkVertex.kPosition.x*=kWorkVertex.kPosition.w;
kWorkVertex.kPosition.y*=kWorkVertex.kPosition.w;
kWorkVertex.kPosition.z*=kWorkVertex.kPosition.w;
kWorkVertex.kPosition.x=(kWorkVertex.kPosition.x+1.0f)*fScreenHalfWidth;
kWorkVertex.kPosition.y=(kWorkVertex.kPosition.y-1.0f)*fScreenHalfHeight;
kWorkVertex.dwDiffuse=akSrcVertex[uIndex].dwDiffuse;
kWorkVertex.dwFog=0xffffffff;
kWorkVertex.kTexTile.x=pkSrcPosition->x*fTilePatternX;
kWorkVertex.kTexTile.y=pkSrcPosition->y*fTilePatternY;
kWorkVertex.kTexAlpha.x=fLocalX*fAlphaPatternX+fAlphaBiasX;
kWorkVertex.kTexAlpha.y=fLocalY*fAlphaPatternY+fAlphaBiasY;
kWorkVertex.kTexStaticShadow.x=fLocalX*fShadowPatternX;
kWorkVertex.kTexStaticShadow.y=fLocalY*fShadowPatternY;
kWorkVertex.kTexDynamicShadow.x=0.0f;
kWorkVertex.kTexDynamicShadow.y=0.0f;
*(akTransVertex+uIndex)=kWorkVertex;
}
}
if (isDynamicShadow)
{
D3DXMATRIX m4DynamicShadow=rkTPRS.m_m4DynamicShadow;
D3DXVECTOR3 v3Shadow;
for (UINT uIndex=0; uIndex!=CTerrainPatch::TERRAIN_VERTEX_COUNT; ++uIndex)
{
D3DXVec3TransformCoord(&v3Shadow, &akSrcVertex[uIndex].kPosition, &m4DynamicShadow);
akTransVertex[uIndex].kTexDynamicShadow.x=v3Shadow.x;
akTransVertex[uIndex].kTexDynamicShadow.y=v3Shadow.y;
}
}
return true;
}
bool CMapOutdoor::__SoftwareTransformPatch_SetSplatStream(SoftwareTransformPatch_STLVertex* akSrcVertex)
{
IDirect3DVertexBuffer8* pkVB=m_kSTPD.m_pkVBSplat[m_kSTPD.m_dwSplatPos++];
m_kSTPD.m_dwSplatPos%=SoftwareTransformPatch_SData::SPLAT_VB_NUM;
if (!pkVB)
return false;
DWORD dwVBSize=sizeof(SoftwareTransformPatch_SSplatVertex)*CTerrainPatch::TERRAIN_VERTEX_COUNT;
SoftwareTransformPatch_SSplatVertex* akDstVertex;
if (FAILED(
pkVB->Lock(0, dwVBSize, (BYTE**)&akDstVertex, 0)//D3DLOCK_DISCARD)
)) return false;
for (UINT uIndex=0; uIndex!=CTerrainPatch::TERRAIN_VERTEX_COUNT; ++uIndex)
*(akDstVertex+uIndex)=*((SoftwareTransformPatch_SSplatVertex*)(akSrcVertex+uIndex));
pkVB->Unlock();
STATEMANAGER.SetStreamSource(0, pkVB, sizeof(SoftwareTransformPatch_SSplatVertex));
return true;
}
bool CMapOutdoor::__SoftwareTransformPatch_SetShadowStream(SoftwareTransformPatch_STLVertex* akSrcVertex)
{
IDirect3DVertexBuffer8* pkVB=m_kSTPD.m_pkVBSplat[m_kSTPD.m_dwSplatPos++];
m_kSTPD.m_dwSplatPos%=SoftwareTransformPatch_SData::SPLAT_VB_NUM;
if (!pkVB)
return false;
DWORD dwVBSize=sizeof(SoftwareTransformPatch_SSplatVertex)*CTerrainPatch::TERRAIN_VERTEX_COUNT;
SoftwareTransformPatch_SSplatVertex* akDstVertex;
if (FAILED(
pkVB->Lock(0, dwVBSize, (BYTE**)&akDstVertex, 0)//D3DLOCK_DISCARD)
)) return false;
SoftwareTransformPatch_STLVertex* pkSrcVertex;
SoftwareTransformPatch_SSplatVertex* pkDstVertex;
for (UINT uIndex=0; uIndex!=CTerrainPatch::TERRAIN_VERTEX_COUNT; ++uIndex)
{
pkSrcVertex=akSrcVertex+uIndex;
pkDstVertex=akDstVertex+uIndex;
pkDstVertex->kPosition=pkSrcVertex->kPosition;
pkDstVertex->dwDiffuse=pkSrcVertex->dwDiffuse;
pkDstVertex->dwSpecular=pkSrcVertex->dwFog;
pkDstVertex->kTex1=pkSrcVertex->kTexStaticShadow;
pkDstVertex->kTex2=pkSrcVertex->kTexDynamicShadow;
}
pkVB->Unlock();
ms_lpd3dDevice->SetStreamSource(0, pkVB, sizeof(SoftwareTransformPatch_SSplatVertex));
return true;
}
void CMapOutdoor::__SoftwareTransformPatch_Initialize()
{
{
for (UINT uIndex=0; uIndex!=SoftwareTransformPatch_SData::SPLAT_VB_NUM; ++uIndex)
m_kSTPD.m_pkVBSplat[uIndex]=NULL;
m_kSTPD.m_dwSplatPos=0;
}
{
for (UINT uIndex=0; uIndex!=SoftwareTransformPatch_SData::NONE_VB_NUM; ++uIndex)
m_kSTPD.m_pkVBNone[uIndex]=NULL;
m_kSTPD.m_dwNonePos=0;
}
}
bool CMapOutdoor::__SoftwareTransformPatch_Create()
{
{
for (UINT uIndex=0; uIndex!=SoftwareTransformPatch_SData::SPLAT_VB_NUM; ++uIndex)
{
assert(NULL==m_kSTPD.m_pkVBSplat[uIndex]);
if (FAILED(
ms_lpd3dDevice->CreateVertexBuffer(
sizeof(SoftwareTransformPatch_SSplatVertex)*CTerrainPatch::TERRAIN_VERTEX_COUNT,
D3DUSAGE_DYNAMIC|D3DUSAGE_WRITEONLY,
D3DFVF_XYZRHW|D3DFVF_DIFFUSE|D3DFVF_SPECULAR|D3DFVF_TEX2,
D3DPOOL_SYSTEMMEM,
&m_kSTPD.m_pkVBSplat[uIndex]
)
)) return false;
}
}
{
for (UINT uIndex=0; uIndex!=SoftwareTransformPatch_SData::NONE_VB_NUM; ++uIndex)
{
assert(NULL==m_kSTPD.m_pkVBNone[uIndex]);
if (FAILED(
ms_lpd3dDevice->CreateVertexBuffer(
sizeof(SoftwareTransformPatch_STVertex)*CTerrainPatch::TERRAIN_VERTEX_COUNT,
D3DUSAGE_DYNAMIC|D3DUSAGE_WRITEONLY,
D3DFVF_XYZRHW,
D3DPOOL_SYSTEMMEM,
&m_kSTPD.m_pkVBNone[uIndex]
)
)) return false;
}
}
return true;
}
void CMapOutdoor::__SoftwareTransformPatch_Destroy()
{
{
for (UINT uIndex=0; uIndex!=SoftwareTransformPatch_SData::SPLAT_VB_NUM; ++uIndex)
{
if (m_kSTPD.m_pkVBSplat[uIndex])
m_kSTPD.m_pkVBSplat[uIndex]->Release();
}
}
{
for (UINT uIndex=0; uIndex!=SoftwareTransformPatch_SData::NONE_VB_NUM; ++uIndex)
{
if (m_kSTPD.m_pkVBNone[uIndex])
m_kSTPD.m_pkVBNone[uIndex]->Release();
}
}
__SoftwareTransformPatch_Initialize();
}
+182
View File
@@ -0,0 +1,182 @@
// Platform copy of 40250 GameLib/MapOutdoorWater.cpp, as is apart from the includes and the
// native-terrain gate: the Godot water adapter draws the surface (PORT-PLAN §3) unless
// IsNativeTerrainRenderEnabled().
#include "GameLib/StdAfx.h"
#include "EterLib/StateManager.h"
#include "EterLib/ResourceManager.h"
#include "EterBase/Timer.h"
#include "../EterLib/RenderCommands3D.h"
#include "GameLib/MapOutdoor.h"
#include "GameLib/TerrainPatch.h"
void CMapOutdoor::LoadWaterTexture()
{
UnloadWaterTexture();
char buf[256];
for (int i = 0; i < 30; ++i)
{
sprintf(buf, "d:/ymir Work/special/water/%02d.dds", i+1);
m_WaterInstances[i].SetImagePointer((CGraphicImage *) CResourceManager::Instance().GetResourcePointer(buf));
}
}
void CMapOutdoor::UnloadWaterTexture()
{
for (int i = 0; i < 30; ++i)
m_WaterInstances[i].Destroy();
}
void CMapOutdoor::RenderWater()
{
if (m_PatchVector.empty())
return;
if (!IsVisiblePart(PART_WATER))
return;
// PORT: see the file comment.
if (!IsNativeTerrainRenderEnabled())
return;
CGraphicTexture* pWaterTexture = m_WaterInstances[((ELTimer_GetMSec() / 70) % 30)].GetTexturePointer();
if (!pWaterTexture)
return;
//////////////////////////////////////////////////////////////////////////
// RenderState
D3DXMATRIX matTexTransformWater;
STATEMANAGER.SaveRenderState(D3DRS_ZWRITEENABLE, FALSE);
STATEMANAGER.SaveRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
STATEMANAGER.SaveRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
STATEMANAGER.SaveRenderState(D3DRS_DIFFUSEMATERIALSOURCE, D3DMCS_COLOR1);
STATEMANAGER.SaveRenderState(D3DRS_COLORVERTEX, TRUE);
STATEMANAGER.SetTexture(0, pWaterTexture->GetD3DTexture());
D3DXMatrixScaling(&matTexTransformWater, m_fWaterTexCoordBase, -m_fWaterTexCoordBase, 0.0f);
D3DXMatrixMultiply(&matTexTransformWater, &m_matViewInverse, &matTexTransformWater);
STATEMANAGER.SaveTransform(D3DTS_TEXTURE0, &matTexTransformWater);
STATEMANAGER.SaveVertexShader(D3DFVF_XYZ|D3DFVF_DIFFUSE);
STATEMANAGER.SaveTextureStageState(0, D3DTSS_TEXCOORDINDEX, D3DTSS_TCI_CAMERASPACEPOSITION);
STATEMANAGER.SaveTextureStageState(0, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_COUNT2);
STATEMANAGER.SaveTextureStageState(0, D3DTSS_MINFILTER, D3DTEXF_LINEAR);
STATEMANAGER.SaveTextureStageState(0, D3DTSS_MAGFILTER, D3DTEXF_LINEAR);
STATEMANAGER.SaveTextureStageState(0, D3DTSS_MIPFILTER, D3DTEXF_LINEAR);
STATEMANAGER.SaveTextureStageState(0, D3DTSS_ADDRESSU, D3DTADDRESS_WRAP);
STATEMANAGER.SaveTextureStageState(0, D3DTSS_ADDRESSV, D3DTADDRESS_WRAP);
STATEMANAGER.SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE);
STATEMANAGER.SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
STATEMANAGER.SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_DIFFUSE);
STATEMANAGER.SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1);
STATEMANAGER.SetTexture(1,NULL);
STATEMANAGER.SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_DISABLE);
STATEMANAGER.SetTextureStageState(1, D3DTSS_ALPHAOP, D3DTOP_DISABLE);
// RenderState
//////////////////////////////////////////////////////////////////////////
// 물 위 아래 애니시키기...
static float s_fWaterHeightCurrent = 0;
static float s_fWaterHeightBegin = 0;
static float s_fWaterHeightEnd = 0;
static DWORD s_dwLastHeightChangeTime = CTimer::Instance().GetCurrentMillisecond();
static DWORD s_dwBlendtime = 300;
// 1.5초 마다 변경
if ((CTimer::Instance().GetCurrentMillisecond() - s_dwLastHeightChangeTime) > s_dwBlendtime)
{
s_dwBlendtime = random_range(1000, 3000);
if (s_fWaterHeightEnd == 0)
s_fWaterHeightEnd = -random_range(0, 15);
else
s_fWaterHeightEnd = 0;
s_fWaterHeightBegin = s_fWaterHeightCurrent;
s_dwLastHeightChangeTime = CTimer::Instance().GetCurrentMillisecond();
}
s_fWaterHeightCurrent = s_fWaterHeightBegin + (s_fWaterHeightEnd - s_fWaterHeightBegin) * (float) ((CTimer::Instance().GetCurrentMillisecond() - s_dwLastHeightChangeTime) / (float) s_dwBlendtime);
m_matWorldForCommonUse._43 = s_fWaterHeightCurrent;
m_matWorldForCommonUse._41 = 0.0f;
m_matWorldForCommonUse._42 = 0.0f;
STATEMANAGER.SetTransform(D3DTS_WORLD, &m_matWorldForCommonUse);
float fFogDistance = __GetFogDistance();
std::vector<std::pair<float, long> >::iterator i;
for(i = m_PatchVector.begin();i != m_PatchVector.end(); ++i)
{
if (i->first<fFogDistance)
DrawWater(i->second);
}
STATEMANAGER.SetTexture(0, NULL);
STATEMANAGER.SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
for(i = m_PatchVector.begin();i != m_PatchVector.end(); ++i)
{
if (i->first>=fFogDistance)
DrawWater(i->second);
}
// 렌더링 한 후에는 물 z 위치를 복구
m_matWorldForCommonUse._43 = 0.0f;
//////////////////////////////////////////////////////////////////////////
// RenderState
STATEMANAGER.RestoreVertexShader();
STATEMANAGER.RestoreTransform(D3DTS_TEXTURE0);
STATEMANAGER.RestoreTextureStageState(0, D3DTSS_MINFILTER);
STATEMANAGER.RestoreTextureStageState(0, D3DTSS_MAGFILTER);
STATEMANAGER.RestoreTextureStageState(0, D3DTSS_MIPFILTER);
STATEMANAGER.RestoreTextureStageState(0, D3DTSS_ADDRESSU);
STATEMANAGER.RestoreTextureStageState(0, D3DTSS_ADDRESSV);
STATEMANAGER.RestoreTextureStageState(0, D3DTSS_TEXCOORDINDEX);
STATEMANAGER.RestoreTextureStageState(0, D3DTSS_TEXTURETRANSFORMFLAGS);
STATEMANAGER.RestoreRenderState(D3DRS_DIFFUSEMATERIALSOURCE);
STATEMANAGER.RestoreRenderState(D3DRS_COLORVERTEX);
STATEMANAGER.RestoreRenderState(D3DRS_ZWRITEENABLE);
STATEMANAGER.RestoreRenderState(D3DRS_ALPHABLENDENABLE);
STATEMANAGER.RestoreRenderState(D3DRS_CULLMODE);
}
void CMapOutdoor::DrawWater(long patchnum)
{
assert(NULL!=m_pTerrainPatchProxyList);
if (!m_pTerrainPatchProxyList)
return;
CTerrainPatchProxy& rkTerrainPatchProxy = m_pTerrainPatchProxyList[patchnum];
if (!rkTerrainPatchProxy.isUsed())
return;
if (!rkTerrainPatchProxy.isWaterExists())
return;
CGraphicVertexBuffer* pkVB=rkTerrainPatchProxy.GetWaterVertexBufferPointer();
if (!pkVB)
return;
if (!pkVB->GetD3DVertexBuffer())
return;
UINT uPriCount=rkTerrainPatchProxy.GetWaterFaceCount();
if (!uPriCount)
return;
STATEMANAGER.SetStreamSource(0, pkVB->GetD3DVertexBuffer(), sizeof(SWaterVertex));
STATEMANAGER.DrawPrimitive(D3DPT_TRIANGLELIST, 0, uPriCount);
ms_faceCount += uPriCount;
}
+23
View File
@@ -0,0 +1,23 @@
#include "AudioCommands.h"
#include <mutex>
namespace
{
std::mutex g_audio_mutex;
std::vector<AudioCommand> g_audio_commands;
}
void PushAudioCommand(const AudioCommand& cmd)
{
std::lock_guard<std::mutex> lock(g_audio_mutex);
g_audio_commands.push_back(cmd);
}
std::vector<AudioCommand> DrainAudioCommands()
{
std::lock_guard<std::mutex> lock(g_audio_mutex);
std::vector<AudioCommand> out;
out.swap(g_audio_commands);
return out;
}
+36
View File
@@ -0,0 +1,36 @@
#pragma once
#include <string>
#include <vector>
struct AudioCommand
{
enum Type
{
PlaySound2D = 1,
PlaySound3D = 2,
StopSound3D = 3,
StopAllSound3D = 4,
PlayMusic = 5,
FadeOutMusic = 6,
FadeOutAllMusic = 7,
SetSoundVolume = 8,
SetMusicVolume = 9,
FadeInMusic = 10,
FadeLimitOutMusic = 11,
SetSoundVolume3D = 12,
};
Type type = PlaySound2D;
std::string filename;
float x = 0.0f;
float y = 0.0f;
float z = 0.0f;
float volume = 1.0f;
float speed = 0.0f;
int play_count = 1;
int id = 0;
};
void PushAudioCommand(const AudioCommand& cmd);
std::vector<AudioCommand> DrainAudioCommands();
+50
View File
@@ -0,0 +1,50 @@
// Platform skeleton for MilesLib/SoundBase.h (40250 MilesLib/SoundBase.cpp), generated by platform_stub.py.
// Every MT_PLATFORM_STUB() body is unimplemented: replace it with the platform implementation.
#include "MilesLib/Stdafx.h"
#include "MilesLib/SoundBase.h"
#include "../PlatformStub.h"
CSoundBase::CSoundBase()
{
MT_PLATFORM_STUB();
}
CSoundBase::~CSoundBase()
{
MT_PLATFORM_STUB();
}
auto CSoundBase::Initialize() -> void
{
MT_PLATFORM_STUB();
}
auto CSoundBase::Destroy() -> void
{
MT_PLATFORM_STUB();
}
auto CSoundBase::AddFile(DWORD, const char *) -> CSoundData *
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<CSoundData *>();
}
auto CSoundBase::GetFileCRC(const char *) -> DWORD
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<DWORD>();
}
decltype(CSoundBase::ms_iRefCount) CSoundBase::ms_iRefCount{};
decltype(CSoundBase::ms_DIGDriver) CSoundBase::ms_DIGDriver{};
decltype(CSoundBase::ms_pProviderDefault) CSoundBase::ms_pProviderDefault{};
decltype(CSoundBase::ms_ProviderVector) CSoundBase::ms_ProviderVector{};
decltype(CSoundBase::ms_dataMap) CSoundBase::ms_dataMap{};
decltype(CSoundBase::ms_bInitialized) CSoundBase::ms_bInitialized{};
+116
View File
@@ -0,0 +1,116 @@
// Platform skeleton for MilesLib/SoundData.h (40250 MilesLib/SoundData.cpp), generated by platform_stub.py.
// Every MT_PLATFORM_STUB() body is unimplemented: replace it with the platform implementation.
#include "MilesLib/Stdafx.h"
#include "MilesLib/SoundData.h"
#include "../PlatformStub.h"
auto CSoundData::SetPackMode() -> void
{
MT_PLATFORM_STUB();
}
CSoundData::CSoundData()
{
MT_PLATFORM_STUB();
}
CSoundData::~CSoundData()
{
MT_PLATFORM_STUB();
}
auto CSoundData::Assign(const char *) -> void
{
MT_PLATFORM_STUB();
}
auto CSoundData::Get() -> LPVOID
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<LPVOID>();
}
auto CSoundData::GetSize() -> ULONG
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<ULONG>();
}
auto CSoundData::Release() -> void
{
MT_PLATFORM_STUB();
}
auto CSoundData::GetAccessTime() -> DWORD
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<DWORD>();
}
auto CSoundData::GetFileName() -> const char *
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<const char *>();
}
auto CSoundData::SetPlayTime(DWORD) -> void
{
MT_PLATFORM_STUB();
}
auto CSoundData::GetPlayTime() -> DWORD
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<DWORD>();
}
auto CSoundData::ReadFromDisk() -> bool
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<bool>();
}
auto CSoundData::Destroy() -> void
{
MT_PLATFORM_STUB();
}
auto CSoundData::open_callback(const char *, U32 *) -> U32
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<U32>();
}
auto CSoundData::close_callback(U32) -> void
{
MT_PLATFORM_STUB();
}
auto CSoundData::seek_callback(U32, S32, U32) -> S32
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<S32>();
}
auto CSoundData::read_callback(U32, void *, U32) -> U32
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<U32>();
}
auto CSoundData::isSlotIndex(DWORD) -> bool
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<bool>();
}
auto CSoundData::GetEmptySlotIndex() -> int
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<int>();
}
decltype(CSoundData::ms_isSoundFile) CSoundData::ms_isSoundFile{};
decltype(CSoundData::ms_SoundFile) CSoundData::ms_SoundFile{};
+256
View File
@@ -0,0 +1,256 @@
// Platform skeleton for MilesLib/SoundInstance.h, generated by platform_stub.py.
// Every MT_PLATFORM_STUB() body is unimplemented: replace it with the platform implementation.
#include "MilesLib/Stdafx.h"
#include "MilesLib/SoundInstance.h"
#include "../PlatformStub.h"
CSoundInstance2D::CSoundInstance2D()
{
MT_PLATFORM_STUB();
}
CSoundInstance2D::~CSoundInstance2D()
{
MT_PLATFORM_STUB();
}
auto CSoundInstance2D::Initialize() -> bool
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<bool>();
}
auto CSoundInstance2D::Destroy() -> void
{
MT_PLATFORM_STUB();
}
auto CSoundInstance2D::SetSound(CSoundData *) -> bool
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<bool>();
}
auto CSoundInstance2D::Play(int, DWORD) const -> void
{
MT_PLATFORM_STUB();
}
auto CSoundInstance2D::Pause() const -> void
{
MT_PLATFORM_STUB();
}
auto CSoundInstance2D::Resume() const -> void
{
MT_PLATFORM_STUB();
}
auto CSoundInstance2D::Stop() -> void
{
MT_PLATFORM_STUB();
}
auto CSoundInstance2D::GetVolume(float &) const -> void
{
MT_PLATFORM_STUB();
}
auto CSoundInstance2D::SetVolume(float) const -> void
{
MT_PLATFORM_STUB();
}
auto CSoundInstance2D::IsDone() const -> bool
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<bool>();
}
auto CSoundInstance2D::SetPosition(float, float, float) const -> void
{
MT_PLATFORM_STUB();
}
auto CSoundInstance2D::SetOrientation(float, float, float, float, float, float) const -> void
{
MT_PLATFORM_STUB();
}
auto CSoundInstance2D::SetVelocity(float, float, float, float) const -> void
{
MT_PLATFORM_STUB();
}
CSoundInstance3D::CSoundInstance3D()
{
MT_PLATFORM_STUB();
}
CSoundInstance3D::~CSoundInstance3D()
{
MT_PLATFORM_STUB();
}
auto CSoundInstance3D::Initialize() -> bool
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<bool>();
}
auto CSoundInstance3D::Destroy() -> void
{
MT_PLATFORM_STUB();
}
auto CSoundInstance3D::SetSound(CSoundData *) -> bool
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<bool>();
}
auto CSoundInstance3D::Play(int, DWORD) const -> void
{
MT_PLATFORM_STUB();
}
auto CSoundInstance3D::Pause() const -> void
{
MT_PLATFORM_STUB();
}
auto CSoundInstance3D::Resume() const -> void
{
MT_PLATFORM_STUB();
}
auto CSoundInstance3D::Stop() -> void
{
MT_PLATFORM_STUB();
}
auto CSoundInstance3D::GetVolume(float &) const -> void
{
MT_PLATFORM_STUB();
}
auto CSoundInstance3D::SetVolume(float) const -> void
{
MT_PLATFORM_STUB();
}
auto CSoundInstance3D::IsDone() const -> bool
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<bool>();
}
auto CSoundInstance3D::SetPosition(float, float, float) const -> void
{
MT_PLATFORM_STUB();
}
auto CSoundInstance3D::SetOrientation(float, float, float, float, float, float) const -> void
{
MT_PLATFORM_STUB();
}
auto CSoundInstance3D::SetVelocity(float, float, float, float) const -> void
{
MT_PLATFORM_STUB();
}
auto CSoundInstance3D::UpdatePosition(float) -> void
{
MT_PLATFORM_STUB();
}
CSoundInstanceStream::CSoundInstanceStream()
{
MT_PLATFORM_STUB();
}
CSoundInstanceStream::~CSoundInstanceStream()
{
MT_PLATFORM_STUB();
}
auto CSoundInstanceStream::Initialize() -> bool
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<bool>();
}
auto CSoundInstanceStream::Destroy() -> void
{
MT_PLATFORM_STUB();
}
auto CSoundInstanceStream::SetStream(HSTREAM) -> void
{
MT_PLATFORM_STUB();
}
auto CSoundInstanceStream::SetSound(CSoundData *) -> bool
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<bool>();
}
auto CSoundInstanceStream::Play(int, DWORD) const -> void
{
MT_PLATFORM_STUB();
}
auto CSoundInstanceStream::Pause() const -> void
{
MT_PLATFORM_STUB();
}
auto CSoundInstanceStream::Resume() const -> void
{
MT_PLATFORM_STUB();
}
auto CSoundInstanceStream::Stop() -> void
{
MT_PLATFORM_STUB();
}
auto CSoundInstanceStream::GetVolume(float &) const -> void
{
MT_PLATFORM_STUB();
}
auto CSoundInstanceStream::SetVolume(float) const -> void
{
MT_PLATFORM_STUB();
}
auto CSoundInstanceStream::IsDone() const -> bool
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<bool>();
}
auto CSoundInstanceStream::IsData() const -> bool
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<bool>();
}
auto CSoundInstanceStream::SetPosition(float, float, float) const -> void
{
MT_PLATFORM_STUB();
}
auto CSoundInstanceStream::SetOrientation(float, float, float, float, float, float) const -> void
{
MT_PLATFORM_STUB();
}
auto CSoundInstanceStream::SetVelocity(float, float, float, float) const -> void
{
MT_PLATFORM_STUB();
}
+368
View File
@@ -0,0 +1,368 @@
// Platform implementation of MilesLib/SoundManager.h for port/headless execution.
#include "MilesLib/Stdafx.h"
#include "MilesLib/SoundManager.h"
#include "AudioCommands.h"
#include <cmath>
#include <algorithm>
decltype(CSoundManager::ms_SoundManager2D) CSoundManager::ms_SoundManager2D{};
decltype(CSoundManager::ms_SoundManager3D) CSoundManager::ms_SoundManager3D{};
decltype(CSoundManager::ms_SoundManagerStream) CSoundManager::ms_SoundManagerStream{};
CSoundManager::CSoundManager()
{
m_bInitialized = FALSE;
m_isSoundDisable = FALSE;
m_fxPosition = 0.0f;
m_fyPosition = 0.0f;
m_fzPosition = 0.0f;
m_fSoundScale = 200.0f;
m_fAmbienceSoundScale = 1000.0f;
m_fSoundVolume = 1.0f;
m_fMusicVolume = 1.0f;
m_fBackupMusicVolume = 0.0f;
m_fBackupSoundVolume = 0.0f;
for (int i = 0; i < CSoundManagerStream::MUSIC_INSTANCE_MAX_NUM; ++i)
{
TMusicInstance & rInstance = m_MusicInstances[i];
rInstance.dwMusicFileNameCRC = 0;
rInstance.MusicState = MUSIC_STATE_OFF;
rInstance.fVolume = 0.0f;
rInstance.fLimitVolume = 0.0f;
rInstance.fVolumeSpeed = 0.0f;
}
}
CSoundManager::~CSoundManager()
{
}
BOOL CSoundManager::Create()
{
m_bInitialized = TRUE;
return TRUE;
}
void CSoundManager::Destroy()
{
m_PlaySoundHistoryMap.clear();
m_bInitialized = FALSE;
}
void CSoundManager::SetPosition(float fx, float fy, float fz)
{
m_fxPosition = fx;
m_fyPosition = fy;
m_fzPosition = fz;
}
void CSoundManager::SetDirection(float, float, float, float, float, float)
{
}
void CSoundManager::Update()
{
}
float CSoundManager::GetSoundScale()
{
return m_fSoundScale;
}
void CSoundManager::SetSoundScale(float fScale)
{
m_fSoundScale = fScale;
}
void CSoundManager::SetAmbienceSoundScale(float fScale)
{
m_fAmbienceSoundScale = fScale;
}
float CSoundManager::__ConvertRatioVolumeToApplyVolume(float fRatioVolume)
{
if (0.1f > fRatioVolume)
return fRatioVolume;
return (float)pow(10.0f, (-1.0f + fRatioVolume));
}
float CSoundManager::__ConvertGradeVolumeToApplyVolume(int nGradeVolume)
{
return __ConvertRatioVolumeToApplyVolume(nGradeVolume / 5.0f);
}
void CSoundManager::SetSoundVolume(float fVolume)
{
if (m_isSoundDisable)
{
m_fBackupSoundVolume = fVolume;
return;
}
if (fVolume < 0.0f) fVolume = 0.0f;
if (fVolume > 1.0f) fVolume = 1.0f;
m_fSoundVolume = fVolume;
if (!m_isSoundDisable)
{
m_fBackupSoundVolume = fVolume;
}
AudioCommand cmd;
cmd.type = AudioCommand::SetSoundVolume;
cmd.volume = m_fSoundVolume;
PushAudioCommand(cmd);
}
void CSoundManager::SetSoundVolumeRatio(float fRatio)
{
float fVolume = __ConvertRatioVolumeToApplyVolume(fRatio);
SetSoundVolume(fVolume);
}
void CSoundManager::SetSoundVolumeGrade(int iGrade)
{
float fVolume = __ConvertGradeVolumeToApplyVolume(iGrade);
SetSoundVolume(fVolume);
}
void CSoundManager::__SetMusicVolume(float fVolume)
{
if (m_isSoundDisable)
{
m_fBackupMusicVolume = fVolume;
return;
}
if (fVolume < 0.0f) fVolume = 0.0f;
if (fVolume > 1.0f) fVolume = 1.0f;
m_fMusicVolume = fVolume;
if (!m_isSoundDisable)
{
m_fBackupMusicVolume = fVolume;
}
AudioCommand cmd;
cmd.type = AudioCommand::SetMusicVolume;
cmd.volume = m_fMusicVolume;
PushAudioCommand(cmd);
}
void CSoundManager::SetMusicVolume(float fVolume)
{
__SetMusicVolume(fVolume);
}
void CSoundManager::SetMusicVolumeRatio(float fRatio)
{
float fVolume = __ConvertRatioVolumeToApplyVolume(fRatio);
SetMusicVolume(fVolume);
}
void CSoundManager::SetMusicVolumeGrade(int iGrade)
{
float fVolume = __ConvertGradeVolumeToApplyVolume(iGrade);
SetMusicVolume(fVolume);
}
void CSoundManager::SaveVolume()
{
if (m_isSoundDisable)
return;
const float musicVolume = m_fMusicVolume;
const float soundVolume = m_fSoundVolume;
SetMusicVolume(0.0f);
SetSoundVolume(0.0f);
m_fBackupMusicVolume = musicVolume;
m_fBackupSoundVolume = soundVolume;
m_isSoundDisable = TRUE;
}
void CSoundManager::RestoreVolume()
{
m_isSoundDisable = FALSE;
SetMusicVolume(m_fBackupMusicVolume);
SetSoundVolume(m_fBackupSoundVolume);
}
float CSoundManager::GetSoundVolume()
{
return m_fSoundVolume;
}
float CSoundManager::GetMusicVolume()
{
return m_fMusicVolume;
}
void CSoundManager::PlaySound2D(const char * c_szFileName)
{
if (m_isSoundDisable || !c_szFileName || !c_szFileName[0])
return;
AudioCommand cmd;
cmd.type = AudioCommand::PlaySound2D;
cmd.filename = c_szFileName;
cmd.volume = m_fSoundVolume;
PushAudioCommand(cmd);
}
void CSoundManager::PlaySound3D(float fx, float fy, float fz, const char * c_szFileName, int iPlayCount)
{
if (m_isSoundDisable || !c_szFileName || !c_szFileName[0])
return;
AudioCommand cmd;
cmd.type = AudioCommand::PlaySound3D;
cmd.filename = c_szFileName;
cmd.x = fx;
cmd.y = fy;
cmd.z = fz;
cmd.play_count = iPlayCount;
cmd.volume = m_fSoundVolume;
PushAudioCommand(cmd);
}
void CSoundManager::StopSound3D(int iIndex)
{
AudioCommand cmd;
cmd.type = AudioCommand::StopSound3D;
cmd.id = iIndex;
PushAudioCommand(cmd);
}
int CSoundManager::PlayAmbienceSound3D(float fx, float fy, float fz, const char * c_szFileName, int iPlayCount)
{
if (m_isSoundDisable || !c_szFileName || !c_szFileName[0])
return -1;
static int s_next_id = 1;
int id = s_next_id++;
AudioCommand cmd;
cmd.type = AudioCommand::PlaySound3D;
cmd.filename = c_szFileName;
cmd.x = fx;
cmd.y = fy;
cmd.z = fz;
cmd.play_count = iPlayCount;
cmd.volume = m_fSoundVolume;
cmd.id = id;
PushAudioCommand(cmd);
return id;
}
void CSoundManager::PlayCharacterSound3D(float fx, float fy, float fz, const char * c_szFileName, BOOL)
{
PlaySound3D(fx, fy, fz, c_szFileName, 1);
}
void CSoundManager::SetSoundVolume3D(int index, float volume)
{
AudioCommand cmd;
cmd.type = AudioCommand::SetSoundVolume3D;
cmd.id = index;
cmd.volume = volume;
PushAudioCommand(cmd);
}
void CSoundManager::StopAllSound3D()
{
m_PlaySoundHistoryMap.clear();
AudioCommand cmd;
cmd.type = AudioCommand::StopAllSound3D;
PushAudioCommand(cmd);
}
void CSoundManager::PlayMusic(const char * c_szFileName)
{
if (!c_szFileName || !c_szFileName[0])
return;
AudioCommand cmd;
cmd.type = AudioCommand::PlayMusic;
cmd.filename = c_szFileName;
cmd.volume = m_fMusicVolume;
PushAudioCommand(cmd);
}
void CSoundManager::FadeInMusic(const char * c_szFileName, float speed)
{
if (!c_szFileName || !c_szFileName[0])
return;
AudioCommand cmd;
cmd.type = AudioCommand::FadeInMusic;
cmd.filename = c_szFileName;
cmd.volume = m_fMusicVolume;
cmd.speed = speed;
PushAudioCommand(cmd);
}
void CSoundManager::FadeOutMusic(const char * c_szFileName, float fSpeed)
{
AudioCommand cmd;
cmd.type = AudioCommand::FadeOutMusic;
cmd.filename = c_szFileName ? c_szFileName : "";
cmd.speed = fSpeed;
PushAudioCommand(cmd);
}
void CSoundManager::FadeLimitOutMusic(const char * c_szFileName, float limit, float speed)
{
AudioCommand cmd;
cmd.type = AudioCommand::FadeLimitOutMusic;
cmd.filename = c_szFileName ? c_szFileName : "";
cmd.volume = __ConvertRatioVolumeToApplyVolume(limit);
cmd.speed = speed;
PushAudioCommand(cmd);
}
void CSoundManager::FadeOutAllMusic()
{
AudioCommand cmd;
cmd.type = AudioCommand::FadeOutAllMusic;
PushAudioCommand(cmd);
}
void CSoundManager::FadeAll()
{
FadeOutAllMusic();
}
void CSoundManager::UpdateSoundData(DWORD, const NSound::TSoundDataVector *)
{
}
void CSoundManager::UpdateSoundData(float, float, float, DWORD, const NSound::TSoundDataVector *)
{
}
void CSoundManager::UpdateSoundInstance(float, float, float, DWORD, const NSound::TSoundInstanceVector *, BOOL)
{
}
void CSoundManager::UpdateSoundInstance(DWORD, const NSound::TSoundInstanceVector *)
{
}
void CSoundManager::PlayMusic(DWORD, const char *, float, float)
{
}
void CSoundManager::StopMusic(DWORD)
{
}
BOOL CSoundManager::GetMusicIndex(const char *, DWORD *)
{
return FALSE;
}
BOOL CSoundManager::GetSoundInstance2D(const char *, ISoundInstance **)
{
return FALSE;
}
BOOL CSoundManager::GetSoundInstance3D(const char *, ISoundInstance **)
{
return FALSE;
}
+33
View File
@@ -0,0 +1,33 @@
// Platform skeleton for MilesLib/SoundManager2D.h (40250 MilesLib/SoundManager2D.cpp), generated by platform_stub.py.
// Every MT_PLATFORM_STUB() body is unimplemented: replace it with the platform implementation.
#include "MilesLib/Stdafx.h"
#include "MilesLib/SoundManager2D.h"
#include "../PlatformStub.h"
CSoundManager2D::CSoundManager2D()
{
MT_PLATFORM_STUB();
}
CSoundManager2D::~CSoundManager2D()
{
MT_PLATFORM_STUB();
}
auto CSoundManager2D::Initialize() -> bool
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<bool>();
}
auto CSoundManager2D::Destroy() -> void
{
MT_PLATFORM_STUB();
}
auto CSoundManager2D::GetInstance(const char *) -> ISoundInstance *
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<ISoundInstance *>();
}
+76
View File
@@ -0,0 +1,76 @@
// Platform skeleton for MilesLib/SoundManager3D.h (40250 MilesLib/SoundManager3D.cpp), generated by platform_stub.py.
// Every MT_PLATFORM_STUB() body is unimplemented: replace it with the platform implementation.
#include "MilesLib/Stdafx.h"
#include "MilesLib/SoundManager3D.h"
#include "../PlatformStub.h"
CSoundManager3D::CSoundManager3D()
{
MT_PLATFORM_STUB();
}
CSoundManager3D::~CSoundManager3D()
{
MT_PLATFORM_STUB();
}
auto CSoundManager3D::Initialize() -> bool
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<bool>();
}
auto CSoundManager3D::Destroy() -> void
{
MT_PLATFORM_STUB();
}
auto CSoundManager3D::GetEmptyInstanceIndex() -> int
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<int>();
}
auto CSoundManager3D::SetInstance(const char *) -> int
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<int>();
}
auto CSoundManager3D::GetInstance(DWORD) -> ISoundInstance *
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<ISoundInstance *>();
}
auto CSoundManager3D::SetListenerDirection(float, float, float, float, float, float) -> void
{
MT_PLATFORM_STUB();
}
auto CSoundManager3D::SetListenerPosition(float, float, float) -> void
{
MT_PLATFORM_STUB();
}
auto CSoundManager3D::SetListenerVelocity(float, float, float, float) -> void
{
MT_PLATFORM_STUB();
}
auto CSoundManager3D::Lock(int) -> void
{
MT_PLATFORM_STUB();
}
auto CSoundManager3D::Unlock(int) -> void
{
MT_PLATFORM_STUB();
}
auto CSoundManager3D::IsValidInstanceIndex(int) -> bool
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<bool>();
}
@@ -0,0 +1,45 @@
// Platform skeleton for MilesLib/SoundManagerStream.h (40250 MilesLib/SoundManagerStream.cpp), generated by platform_stub.py.
// Every MT_PLATFORM_STUB() body is unimplemented: replace it with the platform implementation.
#include "MilesLib/Stdafx.h"
#include "MilesLib/SoundManagerStream.h"
#include "../PlatformStub.h"
CSoundManagerStream::CSoundManagerStream()
{
MT_PLATFORM_STUB();
}
CSoundManagerStream::~CSoundManagerStream()
{
MT_PLATFORM_STUB();
}
auto CSoundManagerStream::Initialize() -> bool
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<bool>();
}
auto CSoundManagerStream::Destroy() -> void
{
MT_PLATFORM_STUB();
}
auto CSoundManagerStream::SetInstance(DWORD, const char *) -> bool
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<bool>();
}
auto CSoundManagerStream::GetInstance(DWORD) -> CSoundInstanceStream *
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<CSoundInstanceStream *>();
}
auto CSoundManagerStream::CheckInstanceIndex(DWORD) -> bool
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<bool>();
}
+34
View File
@@ -0,0 +1,34 @@
// Platform skeleton for MilesLib/Type.h (40250 MilesLib/Type.cpp), generated by platform_stub.py.
// Every MT_PLATFORM_STUB() body is unimplemented: replace it with the platform implementation.
#include "MilesLib/Stdafx.h"
#include "MilesLib/Type.h"
#include "../PlatformStub.h"
auto NSound::LoadSoundInformationPiece(const char *, TSoundDataVector &, const char *) -> bool
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<bool>();
}
auto NSound::SaveSoundInformationPiece(const char *, TSoundDataVector &) -> bool
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<bool>();
}
auto NSound::DataToInstance(const TSoundDataVector &, TSoundInstanceVector *) -> void
{
MT_PLATFORM_STUB();
}
auto NSound::GetResultString() -> const char *
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<const char *>();
}
auto NSound::SetResultString(const char *) -> void
{
MT_PLATFORM_STUB();
}
+60
View File
@@ -0,0 +1,60 @@
#include "EterBase/StdAfx.h"
#include "EterBase/MappedFile.h"
#include "EterPack/EterPackManager.h"
#include "UserInterface/UserInterface.h"
#include "PackBackend.h"
#include <mutex>
#if defined(_WIN32)
#include <io.h> // _access; elsewhere the <windows.h> shim declares it
#endif
namespace mtpack40250 {
namespace {
std::mutex g_init_mutex;
bool g_initialized = false;
bool g_ready = false;
}
bool initialize(const std::string& client_dir)
{
std::lock_guard<std::mutex> lock(g_init_mutex);
if (g_initialized)
return g_ready;
const std::string folder = client_dir + "/pack";
if (_access((folder + "/Index").c_str(), 0) != 0)
return false; // nothing registered; a later call with the right directory may still succeed
g_initialized = true;
PackSingletons();
g_ready = PackInitialize(folder.c_str());
return g_ready;
}
bool ready()
{
std::lock_guard<std::mutex> lock(g_init_mutex);
return g_ready;
}
bool read(const std::string& name, std::vector<uint8_t>& out)
{
out.clear();
if (!ready())
return false;
CMappedFile file;
LPCVOID data = nullptr;
if (!CEterPackManager::Instance().Get(file, name.c_str(), &data))
return false;
const BYTE* bytes = static_cast<const BYTE*>(data);
out.assign(bytes, bytes + file.Size());
return true;
}
bool exists(const std::string& name)
{
return ready() && CEterPackManager::Instance().isExist(name.c_str());
}
} // namespace mtpack40250
+23
View File
@@ -0,0 +1,23 @@
#pragma once
// PackBackend — the 40250 pack file system for the extension (docs/PORT-PLAN.md 2R item 6). Registers <client>/pack
// through the platform PackInitialize and reads with the ported CEterPackManager (pack first, then the loose file).
// Names are 40250 paths ("d:/ymir work/pc/warrior/...", "locale/en/item_proto"), normalized by ConvertFileName.
// Standard types only, so Godot-side code (asset_io) includes it without the Win32 shims.
#include <cstdint>
#include <string>
#include <vector>
namespace mtpack40250 {
// Registers <client_dir>/pack/Index once per process; false when <client_dir>/pack/Index is missing.
// Later calls return whether the first one succeeded.
bool initialize(const std::string& client_dir);
bool ready();
// CEterPackManager::Get into `out`; false when the name is in no pack, is rejected (CRC) and has no loose file.
bool read(const std::string& name, std::vector<uint8_t>& out);
// CEterPackManager::isExist.
bool exists(const std::string& name);
} // namespace mtpack40250
+12
View File
@@ -0,0 +1,12 @@
#include "PlatformStub.h"
#include <cstdio>
void mt_platform_stub_called(const char* function, bool* reported)
{
static const bool trace = std::getenv("MT_PLATFORM_STUB_TRACE") != nullptr;
if (!trace || *reported)
return;
*reported = true;
std::fprintf(stderr, "platform stub: %s\n", function);
}
+58
View File
@@ -0,0 +1,58 @@
#pragma once
// Support for the generated platform skeleton (platform_stub.py, docs/PORT-PLAN.md 2A). A function whose
// body still starts with MT_PLATFORM_STUB() has no platform implementation yet; it does nothing and
// returns a default value. With MT_PLATFORM_STUB_TRACE set in the environment, the first call of each
// one is reported on stderr.
#include <cstdlib>
#include <type_traits>
void mt_platform_stub_called(const char* function, bool* reported);
#if defined(_MSC_VER)
#define MT_PLATFORM_FUNCTION_SIGNATURE __FUNCSIG__
#else
#define MT_PLATFORM_FUNCTION_SIGNATURE __PRETTY_FUNCTION__
#endif
#define MT_PLATFORM_STUB() \
do \
{ \
static bool mt_platform_stub_reported = false; \
mt_platform_stub_called(MT_PLATFORM_FUNCTION_SIGNATURE, &mt_platform_stub_reported); \
} while (0)
template <class T>
T mt_platform_stub_return()
{
if constexpr (std::is_reference_v<T>)
{
using U = std::remove_cv_t<std::remove_reference_t<T>>;
if constexpr (std::is_default_constructible_v<U> && !std::is_abstract_v<U>)
{
static U value{};
return static_cast<T>(value);
}
else
{
// Never constructed: a caller that uses the referent of an unimplemented platform function
// is a bug the stub cannot hide.
alignas(U) static unsigned char storage[sizeof(U)];
return static_cast<T>(*reinterpret_cast<U*>(storage));
}
}
else if constexpr (std::is_same_v<T, const char*>)
{
// Callers strcmp/strlen/format the names these return (CPythonPlayer::GetName in RecvGuild); a
// null string would crash where the real function never returns one.
return "";
}
else if constexpr (std::is_default_constructible_v<T>)
{
return T{};
}
else
{
std::abort();
}
}
+385
View File
@@ -0,0 +1,385 @@
// The auto hunt window (PORT; 40250 has no counterpart), run by PythonBoot::RunMainScript as module
// mt_autohunt. It hooks game.GameWindow.Open/Close so the window lives exactly as long as the game phase,
// whichever way the host reached it. The logic is CPythonPlayer's (UserInterface/PythonPlayerAutoHunt.cpp);
// this is only the player.AutoHunt* front end. Strings are UTF-8 here and go through
// player.AutoHuntLocalize into the locale's code page, as the packed locale strings are.
static const char c_szAutoHuntScript[] = R"PY(# -*- coding: utf-8 -*-
import app
import chat
import game
import player
import ui
import wndMgr
L = player.AutoHuntLocalize
STATE_OFF, STATE_SEARCH, STATE_ENGAGE, STATE_LOOT, STATE_RETURN, STATE_PAUSED = range(6)
STOP_NONE, STOP_USER, STOP_DEAD, STOP_MAP, STOP_INVENTORY_FULL = range(5)
SKILL_SLOT_NUM = 8
STATE_TEXT = {
STATE_SEARCH: "寻找目标",
STATE_ENGAGE: "战斗中",
STATE_LOOT: "拾取中",
STATE_RETURN: "返回挂机点",
STATE_PAUSED: "手动操作,3秒后继续",
}
STOP_TEXT = {
STOP_USER: "自动狩猎已停止",
STOP_DEAD: "角色死亡,自动狩猎已停止",
STOP_MAP: "切换地图,自动狩猎已停止",
STOP_INVENTORY_FULL: "背包已满,自动狩猎已停止",
}
RANGE_VALUES = (1000, 2000, 3500)
RANGE_TEXTS = ("近", "中", "远")
HP_VALUES = (0, 30, 50, 70)
SP_VALUES = (0, 20, 40, 60)
PICKUP_TEXTS = ("不拾取", "全部", "金币装备")
GATHER_VALUES = (0, 3, 5, 8)
GATHER_TEXTS = ("关", "3只", "5只", "8只")
SMALL_BUTTON = "d:/ymir work/ui/public/small_button_%02d.sub"
MIDDLE_BUTTON = "d:/ymir work/ui/public/middle_button_%02d.sub"
XSMALL_BUTTON = "d:/ymir work/ui/public/xsmall_button_%02d.sub"
COLOR_ON = 0xff7fff7f
COLOR_OFF = 0xffffcf7f
COLOR_SELECTED = 0xffffd24a
COLOR_UNSELECTED = 0xffc8c8c8
def _MarkButton(button, isSelected):
"Down and gold text while selected: the down visual alone is hard to tell apart on a phone."
if isSelected:
button.Down()
else:
button.SetUp()
if button.ButtonText:
button.ButtonText.SetPackedFontColor(isSelected and COLOR_SELECTED or COLOR_UNSELECTED)
def _Nearest(values, value):
best = 0
for i in xrange(len(values)):
if abs(values[i] - value) < abs(values[best] - value):
best = i
return best
class ChoiceRow:
"One setting: a label and a row of buttons of which exactly one stays down."
def __init__(self, parent, y, label, texts, image, step, event):
self.label = ui.TextLine()
self.label.SetParent(parent)
self.label.SetPosition(18, y + 4)
self.label.SetText(L(label))
self.label.Show()
self.buttons = []
self.event = event
self.index = -1
x = 70
for i in xrange(len(texts)):
button = ui.RadioButton()
button.SetParent(parent)
button.SetUpVisual(image % 1)
button.SetOverVisual(image % 2)
button.SetDownVisual(image % 3)
button.SetPosition(x, y)
button.SetText(L(texts[i]))
button.SetEvent(lambda i=i: self.Select(i, True))
button.Show()
self.buttons.append(button)
x += step
def Select(self, index, notify):
self.index = index
for i in xrange(len(self.buttons)):
_MarkButton(self.buttons[i], i == index)
if notify and self.event:
self.event()
def Destroy(self):
self.event = None
self.buttons = []
self.label = None
class FlagButton(ui.ToggleButton):
"A button that stays down while its flag is on."
def __init__(self, parent, x, y, image, text, event):
ui.ToggleButton.__init__(self)
self.SetParent(parent)
self.SetUpVisual(image % 1)
self.SetOverVisual(image % 2)
self.SetDownVisual(image % 3)
self.SetPosition(x, y)
self.SetText(L(text))
self.flag = False
self.flagEvent = event
self.SetToggleDownEvent(lambda: self.__OnToggle(True))
self.SetToggleUpEvent(lambda: self.__OnToggle(False))
self.Show()
def __OnToggle(self, flag):
self.SetFlag(flag)
if self.flagEvent:
self.flagEvent()
def SetFlag(self, flag):
self.flag = flag
_MarkButton(self, flag)
def Destroy(self):
self.flagEvent = None
self.eventUp = None
self.eventDown = None
class SettingDialog(ui.BoardWithTitleBar):
WIDTH = 330
HEIGHT = 300
def __init__(self):
ui.BoardWithTitleBar.__init__(self)
self.AddFlag("movable")
self.AddFlag("float")
self.SetSize(self.WIDTH, self.HEIGHT)
self.SetTitleName(L("自动狩猎"))
self.SetCloseEvent(self.Close)
y = 36
self.rangeRow = ChoiceRow(self, y, "范围", RANGE_TEXTS, SMALL_BUTTON, 48, self.__Save)
y += 28
self.hpRow = ChoiceRow(self, y, "红药", ["关"] + ["%d%%" % v for v in HP_VALUES[1:]], SMALL_BUTTON, 48, self.__Save)
y += 28
self.spRow = ChoiceRow(self, y, "蓝药", ["关"] + ["%d%%" % v for v in SP_VALUES[1:]], SMALL_BUTTON, 48, self.__Save)
y += 28
self.pickupRow = ChoiceRow(self, y, "拾取", PICKUP_TEXTS, MIDDLE_BUTTON, 66, self.__Save)
y += 28
self.gatherRow = ChoiceRow(self, y, "聚怪", GATHER_TEXTS, SMALL_BUTTON, 48, self.__Save)
y += 28
self.skillLabel = ui.TextLine()
self.skillLabel.SetParent(self)
self.skillLabel.SetPosition(18, y + 4)
self.skillLabel.SetText(L("技能栏"))
self.skillLabel.Show()
self.skillButtons = []
for i in xrange(SKILL_SLOT_NUM):
self.skillButtons.append(FlagButton(self, 70 + i * 31, y, XSMALL_BUTTON, str(i + 1), self.__Save))
y += 28
self.targetLabel = ui.TextLine()
self.targetLabel.SetParent(self)
self.targetLabel.SetPosition(18, y + 4)
self.targetLabel.SetText(L("攻击"))
self.targetLabel.Show()
self.stoneButton = FlagButton(self, 70, y, MIDDLE_BUTTON, "石头", self.__Save)
self.bossButton = FlagButton(self, 136, y, MIDDLE_BUTTON, "首领", self.__Save)
y += 30
self.hintLine = ui.TextLine()
self.hintLine.SetParent(self)
self.hintLine.SetPosition(0, y + 2)
self.hintLine.SetWindowHorizontalAlignCenter()
self.hintLine.SetHorizontalAlignCenter()
self.hintLine.SetPackedFontColor(0xffa0a0a0)
self.hintLine.SetText(L("手动操作时暂停,3秒后继续"))
self.hintLine.Show()
y += 26
self.startButton = ui.Button()
self.startButton.SetParent(self)
self.startButton.SetUpVisual("d:/ymir work/ui/public/large_button_01.sub")
self.startButton.SetOverVisual("d:/ymir work/ui/public/large_button_02.sub")
self.startButton.SetDownVisual("d:/ymir work/ui/public/large_button_03.sub")
self.startButton.SetPosition(0, y)
self.startButton.SetWindowHorizontalAlignCenter()
self.startButton.SetEvent(self.__OnClickStart)
self.startButton.Show()
self.SetSize(self.WIDTH, y + 36)
self.SetCenterPosition()
self.isStarted = None
def Destroy(self):
for row in (self.rangeRow, self.hpRow, self.spRow, self.pickupRow, self.gatherRow):
row.Destroy()
for button in self.skillButtons + [self.stoneButton, self.bossButton]:
button.Destroy()
self.skillButtons = []
self.startButton = None
self.Hide()
def Open(self):
(range_, hp, sp, pickup, stone, boss, mask, gather) = player.AutoHuntGetConfig()
self.rangeRow.Select(_Nearest(RANGE_VALUES, range_), False)
self.hpRow.Select(_Nearest(HP_VALUES, hp), False)
self.spRow.Select(_Nearest(SP_VALUES, sp), False)
self.pickupRow.Select(pickup, False)
self.gatherRow.Select(_Nearest(GATHER_VALUES, gather), False)
for i in xrange(SKILL_SLOT_NUM):
self.skillButtons[i].SetFlag(bool(mask & (1 << i)))
self.stoneButton.SetFlag(bool(stone))
self.bossButton.SetFlag(bool(boss))
self.isStarted = None
self.Show()
self.SetTop()
def Close(self):
self.Hide()
def OnPressEscapeKey(self):
self.Close()
return True
def OnUpdate(self):
isStarted = bool(player.AutoHuntIsEnabled())
if isStarted != self.isStarted:
self.isStarted = isStarted
self.startButton.SetText(L(isStarted and "停止狩猎" or "开始狩猎"))
def __Save(self):
mask = 0
for i in xrange(SKILL_SLOT_NUM):
if self.skillButtons[i].flag:
mask |= 1 << i
player.AutoHuntSetConfig(RANGE_VALUES[self.rangeRow.index], HP_VALUES[self.hpRow.index],
SP_VALUES[self.spRow.index], self.pickupRow.index, int(self.stoneButton.flag), int(self.bossButton.flag), mask,
GATHER_VALUES[self.gatherRow.index])
def __OnClickStart(self):
Toggle()
if player.AutoHuntIsEnabled():
self.Close()
class StatusBoard(ui.ThinBoard):
def __init__(self):
ui.ThinBoard.__init__(self)
self.AddFlag("not_pick")
self.SetSize(260, 28)
self.SetWindowHorizontalAlignCenter()
self.SetPosition(0, 64)
self.textLine = ui.TextLine()
self.textLine.SetParent(self)
self.textLine.SetPosition(0, 7)
self.textLine.SetWindowHorizontalAlignCenter()
self.textLine.SetHorizontalAlignCenter()
self.textLine.Show()
def SetStatus(self, text, color):
self.textLine.SetText(text)
self.textLine.SetPackedFontColor(color)
self.Show()
class Ticker(ui.Window):
"Always shown and empty: polls the hunt state for the status board, which is hidden while off."
def __init__(self, status):
ui.Window.__init__(self)
self.AddFlag("not_pick")
self.status = status
self.last = None
self.stopShowTime = 0.0
def OnUpdate(self):
state = player.AutoHuntGetState()
if state != self.last:
(stateIndex, reason, noHP, noSP, gathering, gathered) = state
wasOn = self.last and self.last[0] != STATE_OFF
self.last = state
if stateIndex != STATE_OFF:
text = L("自动狩猎 · ") + L(STATE_TEXT.get(stateIndex, ""))
if gathering:
text = L("自动狩猎 · 聚怪中 %d/%d" % (gathered, player.AutoHuntGetConfig()[7]))
if noHP:
text += L(" · 无红药")
if noSP:
text += L(" · 无蓝药")
self.status.SetStatus(text, COLOR_ON)
elif wasOn and reason in STOP_TEXT:
self.status.SetStatus(L(STOP_TEXT[reason]), COLOR_OFF)
self.stopShowTime = app.GetTime() + 5.0
if reason != STOP_USER:
chat.AppendChat(chat.CHAT_TYPE_INFO, L(STOP_TEXT[reason]))
else:
self.status.Hide()
elif state[0] == STATE_OFF and self.stopShowTime and app.GetTime() > self.stopShowTime:
self.stopShowTime = 0.0
self.status.Hide()
g_status = None
g_ticker = None
g_dialog = None
def Toggle():
if player.AutoHuntIsEnabled():
player.AutoHuntSetEnabled(0)
return
player.AutoHuntSetEnabled(1)
if player.AutoHuntIsEnabled():
chat.AppendChat(chat.CHAT_TYPE_INFO, L("自动狩猎已开启(再次点击AUTO或F9停止)"))
def OpenSettings():
if g_dialog:
if g_dialog.IsShow():
g_dialog.Close()
else:
g_dialog.Open()
def IsSettingsOpen():
return g_dialog and g_dialog.IsShow()
def Attach(gameWindow):
global g_status, g_ticker, g_dialog
Detach()
g_status = StatusBoard()
g_ticker = Ticker(g_status)
g_ticker.Show()
g_dialog = SettingDialog()
if gameWindow.onPressKeyDict is not None:
gameWindow.onPressKeyDict[app.DIK_F9] = Toggle
gameWindow.onPressKeyDict[app.DIK_F8] = OpenSettings
def Detach():
global g_status, g_ticker, g_dialog
player.AutoHuntSetEnabled(0)
if g_dialog:
g_dialog.Destroy()
if g_ticker:
g_ticker.Hide()
g_ticker.status = None
if g_status:
g_status.Hide()
g_status = g_ticker = g_dialog = None
def __Install():
openGame = game.GameWindow.Open
closeGame = game.GameWindow.Close
def Open(self):
openGame(self)
Attach(self)
def Close(self):
Detach()
closeGame(self)
game.GameWindow.Open = Open
game.GameWindow.Close = Close
__Install()
)PY";
@@ -0,0 +1,75 @@
// The frame-rate row of the system option dialog (PORT; 40250 has no counterpart, the PC client ran at
// the monitor's rate), run by PythonBoot::RunMainScript as module mt_framerate. It wraps
// uiSystemOption.OptionDialog's __Load and fills the row the original layout leaves empty at y 210 (its
// shadow slider is commented out), in the style of the fog buttons above it. The value is
// app.Get/SetFrameRateMode (platform/EterBase/FrameRateMode.h); the host paces frames by it and saves it.
// Strings are UTF-8 here and go through player.AutoHuntLocalize into the locale's code page.
static const char c_szFrameRateOptionScript[] = R"PY(# -*- coding: utf-8 -*-
import app
import player
import ui
import uiSystemOption
L = player.AutoHuntLocalize
SMALL_BUTTON = "d:/ymir work/ui/public/small_button_%02d.sub"
ROW_Y = 210
MODE_TEXTS = ("30帧", "60帧", "最高")
def _Refresh(buttons):
mode = app.GetFrameRateMode()
for i in xrange(len(buttons)):
if i == mode:
buttons[i].Down()
else:
buttons[i].SetUp()
def _Select(buttons, mode):
app.SetFrameRateMode(mode)
_Refresh(buttons)
def _Attach(dialog):
board = dialog.GetChild("board")
label = ui.TextLine()
label.SetParent(board)
label.SetPosition(30, ROW_Y + 2)
label.SetText(L("画面帧率"))
label.Show()
buttons = []
for i in xrange(len(MODE_TEXTS)):
button = ui.RadioButton()
button.SetParent(board)
button.SetUpVisual(SMALL_BUTTON % 1)
button.SetOverVisual(SMALL_BUTTON % 2)
button.SetDownVisual(SMALL_BUTTON % 3)
button.SetPosition(110 + 50 * i, ROW_Y)
button.SetText(L(MODE_TEXTS[i]))
button.SetEvent(lambda mode=i: _Select(buttons, mode))
button.Show()
buttons.append(button)
_Refresh(buttons)
dialog.mtFrameRateLabel = label
dialog.mtFrameRateButtons = buttons
def __Install():
load = uiSystemOption.OptionDialog._OptionDialog__Load
def Load(self):
load(self)
try:
_Attach(self)
except:
import dbg
dbg.TraceError("mt_framerate: cannot add the frame-rate row")
uiSystemOption.OptionDialog._OptionDialog__Load = Load
__Install()
)PY";
@@ -0,0 +1,57 @@
// Generated by .agents/skills/metin2-40250-parity-audit/scripts/stub_constants.py; do not edit.
// The module constants of the 2V0 stub modules (GameplayModules.cpp), copied from each 40250
// module's init function with the preprocessor lines around them.
#include "UserInterface/StdAfx.h"
#include "UserInterface/PythonSystem.h"
#include "UserInterface/PythonBackground.h"
#include "EterLib/StateManager.h"
#include "GameLib/MapOutdoor.h"
#include "EffectLib/EffectManager.h"
#include "UserInterface/PythonCharacterManager.h"
#include "UserInterface/PythonEventManager.h"
#include "UserInterface/PythonNetworkStream.h"
#include "GameLib/GameEventManager.h"
#include "UserInterface/PythonExchange.h"
#include "GameLib/FlyingObjectManager.h"
#include "UserInterface/PythonGuild.h"
#include "UserInterface/AbstractPlayer.h"
#include "UserInterface/MarkManager.h"
#include "UserInterface/PythonIME.h"
#include "UserInterface/PythonApplication.h"
#include "UserInterface/PythonItem.h"
#include "GameLib/ItemManager.h"
#include "UserInterface/InstanceBase.h"
#include "UserInterface/AbstractApplication.h"
#include "UserInterface/PythonMessenger.h"
#include "UserInterface/PythonMiniMap.h"
#include "EterLib/Profiler.h"
#include "UserInterface/PythonQuest.h"
#include "UserInterface/PythonSafeBox.h"
#include "UserInterface/PythonShop.h"
#include "UserInterface/PythonSkill.h"
#include "EterBase/Poly/Poly.h"
#include "EterPack/EterPackManager.h"
#include "UserInterface/PythonPlayer.h"
#include "UserInterface/PythonTextTail.h"
// 40250 UserInterface/PythonBackgroundModule.cpp
// 40250 UserInterface/PythonEventManagerMoudle.cpp
// 40250 UserInterface/PythonGameEventManagerModule.cpp
// 40250 UserInterface/PythonProfilerModule.cpp
void AddStubConstants_profiler(PyObject* poModule)
{
(void) poModule;
}
// 40250 UserInterface/PythonQuest.cpp
// 40250 UserInterface/PythonSafeBox.cpp (ported for real, see port/UserInterface/PythonSafeBox.cpp)
// 40250 UserInterface/PythonShop.cpp
// 40250 UserInterface/PythonSkill.cpp
// 40250 UserInterface/PythonSoundManagerModule.cpp (ported for real, see port/UserInterface/PythonSoundManagerModule.cpp)
// 40250 UserInterface/PythonNetworkDatagramModule.cpp
void AddStubConstants_udp(PyObject* poModule)
{
(void) poModule;
}
@@ -0,0 +1,48 @@
// 2V0-e temporary native module surfaces generated from 40250 UserInterface module exports.
// These modules expose names for script loading; calls record that they still need the real 2V1-2V3 implementation.
#include "ScriptLib/StdAfx.h"
#include <cstdio>
#include "../EterLib/UIRenderCommands.h"
// GameplayModuleConstants.cpp: each module's 40250 constants.
void AddStubConstants_profiler(PyObject* poModule);
void AddStubConstants_udp(PyObject* poModule);
namespace {
// Returns `result`, a zero value shaped like the 40250 function's return (stub_constants.py), or 0.
PyObject* stub_call_named(const char* name, PyObject* result = nullptr) {
std::fprintf(stderr, "2V0 native stub called: %s\n", name);
std::fflush(stderr);
return result ? result : Py_BuildValue("i", 0);
}
// 40250 UserInterface/PythonProfilerModule.cpp: profiler export names.
PyObject* stub_profiler_Push(PyObject*, PyObject*) { return stub_call_named("profiler.Push", Py_BuildNone()); }
PyObject* stub_profiler_Pop(PyObject*, PyObject*) { return stub_call_named("profiler.Pop", Py_BuildNone()); }
PyMethodDef methods_profiler[] = {
{ "Push", stub_profiler_Push, METH_VARARGS },
{ "Pop", stub_profiler_Pop, METH_VARARGS },
{ NULL, NULL }
};
// 40250 UserInterface/PythonNetworkDatagramModule.cpp: udp export names.
PyObject* stub_udp_Enable(PyObject*, PyObject*) { return stub_call_named("udp.Enable", Py_BuildNone()); }
PyObject* stub_udp_Disable(PyObject*, PyObject*) { return stub_call_named("udp.Disable", Py_BuildNone()); }
PyMethodDef methods_udp[] = {
{ "Enable", stub_udp_Enable, METH_VARARGS },
{ "Disable", stub_udp_Disable, METH_VARARGS },
{ NULL, NULL }
};
} // namespace
void init_2v0_gameplay_stubs() {
{
PyObject* module = Py_InitModule("profiler", methods_profiler);
PyModule_AddIntConstant(module, "__port_stub__", 1);
AddStubConstants_profiler(module);
}
{
PyObject* module = Py_InitModule("udp", methods_udp);
PyModule_AddIntConstant(module, "__port_stub__", 1);
AddStubConstants_udp(module);
}
}
File diff suppressed because it is too large Load Diff
+128
View File
@@ -0,0 +1,128 @@
#pragma once
// Starting the script layer inside a host process (docs/PORT-PLAN.md 批次 2P step 4).
//
// 40250 runs the interpreter on Main()'s stack (UserInterface/UserInterface.cpp:419-434): construct
// CPythonLauncher, Create(), RunMainScript(), Clear(), all inside one WinMain. Godot owns the process
// here and calls in from GDScript, so the launcher has to outlive the call that starts it — that split
// (Start / RunMainScript / Stop) is the only difference from the original control flow.
//
// It lives under platform/ScriptLib rather than platform/UserInterface because it is only buildable
// with the embedded interpreter, and that is the directory both port_logic and port_platform drop when
// `mtpython` is absent (src/port/CMakeLists.txt).
//
// godot-free, like everything else under platform/: extension/src/python_host_node.cpp is what GDScript
// talks to.
#include <string>
namespace PythonBoot
{
// PythonHost::Configure() -> CPythonLauncher -> Create() -> PythonHost::InstallStdLib(stdlib_path).
// An empty stdlib_path means PythonHost::DefaultStdLibPath(). Starting twice is a no-op that succeeds.
// On failure *error is set and the interpreter is shut down again, so the next attempt starts clean.
// The packs must already be registered (platform/PackBackend.h), as 40250 registers them in Main()
// before the launcher exists.
bool Start(const char* stdlib_path, std::string* error);
bool IsRunning();
// The SDL native client supplies an OS cursor; the Godot host keeps its software cursor.
void SetHostHardwareCursorEnabled(bool enabled);
bool HostHardwareCursorEnabled();
int CursorShape();
bool CursorVisible();
// 40250: RunMainScript(CPythonLauncher&, const char*) — the module initializers, __DEBUG__,
// __COMMAND_LINE__ and RunFile("system.py"). 2V0-e registers temporary observable gameplay modules;
// they are replaced by the real modules in later 2V slices.
// False leaves *error set to what the launcher reported through LogBox (platform/EterBase/LogBox.h).
//
// PORT: system.py runs on a script thread. RunMainScript returns once prototype.RunApp() has reached
// app.Loop() (IsAppLooping) or the script has ended; from then on every AppFrame() runs exactly one
// CPythonApplication::Process() while the host thread waits, so the two never run concurrently.
bool RunMainScript(const char* lpCmdLine, std::string* error);
bool IsAppLooping();
// The script thread's kernel thread id (Linux/Android), 0 before it starts or elsewhere. The host adds
// it to its ADPF performance-hint session.
int ScriptThreadId();
bool AppFrame();
// Native CPythonBackground map selection, in the local coordinate frame of RenderGame.
std::string CurrentMapName();
// Used by the platform CPythonApplication: Loop() calls AppLoopWait() before each Process() and stops
// when it returns false; Exit()/Abort() call AppRequestQuit() (40250: PostQuitMessage).
bool AppLoopWait();
void AppRequestQuit();
// CPythonLauncher::RunLine, with the reported text handed back rather than only shown. The host's own
// check uses it to prove the interpreter and the standard library work in-process on a device that has
// no 40250 packs, which is where RunMainScript cannot run at all.
bool RunLine(const char* source, std::string* error);
// str(expression) evaluated in __main__ (a host/test helper; 40250 has no counterpart).
bool Evaluate(const char* expression, std::string* result, std::string* error);
// Forward physical Godot input to the original 40250 window manager. Coordinates
// are viewport pixels; SetUISize also establishes its logical resolution.
void SetUISize(int width, int height);
// Mobile safe area: the 40250 windows are laid out width - 2 * inset wide and drawn inset pixels
// right of the screen edge (clear of rounded corners and cutouts) while the 3D world keeps the whole
// screen. Input coordinates stay screen pixels. Takes effect at the next SetUISize; 0 = off.
void SetUISafeInset(int inset);
void UIMouseMove(int x, int y);
void UIMouseButton(int button, bool pressed, int x, int y);
void UIMouseWheel(int nLen);
void UIKey(int key, bool pressed);
// Mobile touch & joystick controls
void SetMoveDirection(float angleDeg, bool moving);
void SetAttackKey(bool pressed);
void UseLocalQuickSlot(int localSlotIndex);
bool TryAssignAttachedObjectToLocalQuickSlot(int localSlotIndex);
// PORT: auto hunt (CPythonPlayer::AutoHunt_*, window in AutoHuntScript.inc): start/stop, the settings
// window, and whether it runs / a character is in the world to run it.
void AutoHuntToggle();
void AutoHuntOpenSettings();
bool AutoHuntIsEnabled();
bool AutoHuntAvailable();
// The skill or inventory item in the local quick slot: its UI texture name, the icon's (su, sv, eu, ev)
// inside it and the item count (0 for a skill).
bool LocalQuickSlotIcon(int localSlotIndex, std::string* texture, float uv[4], int* count);
// Touch gestures: a Win32 WM_LBUTTONDBLCLK (40250 CPythonApplication::OnMouseLeftButtonDoubleClick),
// whether an icon hangs on the cursor (CWindowManager::IsAttaching) and mouseController.DeattachObject().
void UIMouseDoubleClick(int x, int y);
bool UIIsAttaching();
void UIDeattachObject();
// Turns the camera around the player immediately, without CCamera::Drag's decaying velocity.
void CameraRotateBy(float rollDeg, float pitchDeg);
bool IsPointInsideActiveUI(int x, int y);
// Touch hosts: hide 40250's on-screen login keypad (the system keyboard types instead).
// Also drops the mouse arrow: touch hosts run 40250's hardware-cursor mode with no OS cursor, so
// mouseModule draws only the attached icon.
void SetTouchInput(bool touch);
bool TouchInput();
// An EditLine has focus (40250 ui.EditLine.OnSetFocus -> ime.EnableCaptureInput).
bool TextInputFocused();
// (x, y) hits the focused window, i.e. the tap landed on the focused EditLine.
bool IsPointInsideFocusedWindow(int x, int y);
struct PlayerStatusInfo {
int level = 1;
int hp = 0;
int max_hp = 0;
int sp = 0;
int max_sp = 0;
int exp = 0;
int max_exp = 0;
std::string name;
};
PlayerStatusInfo GetPlayerStatusInfo();
// WM_CHAR (a Unicode code point) and WM_KEYDOWN (a Win32 VK code) for CPythonIME and OnIMEKeyDown.
void UIChar(unsigned codepoint);
void UIIMEKeyDown(int vkey);
// While IsAppLooping(), UIUpdate is AppFrame() and UIRender keeps the commands that Process() drew.
void UIUpdate();
void UIRender();
// Completed native frame duration, including Vulkan rendering and presentation, for auto sight range.
void SetNativeRenderFrameTime(float milliseconds);
bool IsSoftwareCursorVisible();
// 40250 Main() calls Clear() and lets the launcher leave scope.
void Stop();
}
+117
View File
@@ -0,0 +1,117 @@
// See PythonHost.h: the interpreter setup 40250 got from a real python27 installation.
#include "ScriptLib/StdAfx.h"
#include "PythonHost.h"
#include <cstdio>
#include <cstdlib>
namespace
{
// The pending exception as text, so a failed bootstrap says what went wrong instead of leaving the
// error for the first unrelated script to trip over.
std::string take_error()
{
if (!PyErr_Occurred())
return "no exception";
PyObject *type = NULL, *value = NULL, *tb = NULL;
PyErr_Fetch(&type, &value, &tb);
PyErr_NormalizeException(&type, &value, &tb);
std::string text;
if (PyObject* str = value ? PyObject_Str(value) : NULL)
{
if (PyString_Check(str))
text = PyString_AS_STRING(str);
Py_DECREF(str);
}
if (type && text.empty())
text = ((PyTypeObject*) type)->tp_name;
Py_XDECREF(type);
Py_XDECREF(value);
Py_XDECREF(tb);
return text.empty() ? "unknown error" : text;
}
bool fail(std::string* error, const std::string& text)
{
if (error)
*error = text;
return false;
}
}
namespace PythonHost
{
void Configure(const char* program_name)
{
// site.py lives in a prefix this interpreter does not have, the environment must not be able to
// redirect a game's script layer (PYTHONPATH/PYTHONHOME), the "could not find platform libraries"
// probe has nothing to find, and the pack directories are read-only on the mobile targets.
Py_NoSiteFlag = 1;
Py_IgnoreEnvironmentFlag = 1;
Py_FrozenFlag = 1;
Py_DontWriteBytecodeFlag = 1;
Py_SetProgramName((char*) program_name);
}
bool InstallStdLib(const char* stdlib_path, std::string* error)
{
if (!Py_IsInitialized())
return fail(error, "interpreter is not initialized");
if (!stdlib_path || !*stdlib_path)
return fail(error, "no stdlib path (set MT_PYTHON_STDLIB or pass python27.zip)");
// zipimport and the source importer both go through the C library, so the path has to be a real
// file: a pack entry or an Android asset must be staged out first (step 3c).
if (FILE* fp = fopen(stdlib_path, "rb"))
fclose(fp);
else if (FILE* dir = fopen((std::string(stdlib_path) + "/os.py").c_str(), "rb"))
fclose(dir);
else
return fail(error, std::string("cannot open ") + stdlib_path);
PySys_SetPath((char*) stdlib_path);
// Py_Initialize ran _PyCodecRegistry_Init against the then-empty path and 2.7 never retries it
// ("no codec search functions registered" for the rest of the process), so the search function is
// registered again now that encodings is importable.
PyObject* encodings = PyImport_ImportModule("encodings");
if (!encodings)
return fail(error, "import encodings: " + take_error());
PyObject* search = PyObject_GetAttrString(encodings, (char*) "search_function");
Py_DECREF(encodings);
if (!search)
return fail(error, "encodings.search_function: " + take_error());
PyObject* codecs = PyImport_ImportModule("codecs");
PyObject* registered = codecs ? PyObject_CallMethod(codecs, (char*) "register", (char*) "O", search) : NULL;
Py_DECREF(search);
Py_XDECREF(codecs);
if (!registered)
return fail(error, "codecs.register: " + take_error());
Py_DECREF(registered);
return true;
}
namespace
{
std::string g_staged_path;
}
void SetDefaultStdLibPath(const char* stdlib_path)
{
g_staged_path = stdlib_path ? stdlib_path : "";
}
std::string DefaultStdLibPath()
{
// The environment still wins, so a developer can point a build at another stdlib without rebuilding.
if (const char* env = getenv("MT_PYTHON_STDLIB"))
return env;
// Whatever staged the zip for this platform (extension/src/python_stdlib.cpp inside Godot; nothing
// in the native tests, which pass the build tree's copy on the command line).
return g_staged_path;
}
}
+28
View File
@@ -0,0 +1,28 @@
#pragma once
// The interpreter setup 40250 got for free from a real python27 installation.
//
// 40250's Main() only constructs CPythonLauncher: python27.dll found its own prefix, so `import site`,
// the codec registry and every stdlib import worked before a single script ran. The embedded
// interpreter has no prefix and no filesystem to probe, so the host does that part itself —
// the flags before Py_Initialize, and the stdlib (python27.zip) on sys.path afterwards.
// See docs/PORT-PLAN.md 批次 2P step 3.
#include <string>
namespace PythonHost
{
// Before the interpreter starts, i.e. before CPythonLauncher's constructor.
// `program_name` is what CPythonLauncher::Create defaults to; it only names the interpreter.
void Configure(const char* program_name = "eter.python");
// After Py_Initialize: replaces sys.path with `stdlib_path` (a python27.zip or a stdlib directory
// on a real filesystem — zipimport and the .py importer both need a path the C library can open)
// and re-registers the codec search function. False leaves *error set.
bool InstallStdLib(const char* stdlib_path, std::string* error);
// Where the host put the stdlib: $MT_PYTHON_STDLIB when set, else whatever SetDefaultStdLibPath was
// given, else "". Inside Godot that is the staged python27.zip (extension/src/python_stdlib.h), which
// on Android/iOS is the sandbox copy of the one in the read-only bundle.
std::string DefaultStdLibPath();
void SetDefaultStdLibPath(const char* stdlib_path);
}
+328
View File
@@ -0,0 +1,328 @@
// The account registration window (PORT; 40250 has no counterpart, its accounts were made on the web),
// run by PythonBoot::RunMainScript as module mt_register. It hooks introLogin.LoginWindow.Open/Close and
// puts a register button under the login board; the dialog posts to the server's registration service
// (tools/server/register_server.py) through net.RegisterAccount. Strings are UTF-8 here and go through
// player.AutoHuntLocalize into the locale's code page.
static const char c_szRegisterScript[] = R"PY(# -*- coding: utf-8 -*-
import introLogin
import net
import player
import ui
import wndMgr
L = player.AutoHuntLocalize
REGISTER_PORT = 11080
LOGIN_MIN, LOGIN_MAX = 4, 16
PASSWORD_MIN, PASSWORD_MAX = 4, 16
SOCIAL_ID_LEN = 7
LARGE_BUTTON = "d:/ymir work/ui/public/large_button_%02d.sub"
MIDDLE_BUTTON = "d:/ymir work/ui/public/middle_button_%02d.sub"
COLOR_ERROR = 0xffff7f7f
COLOR_INFO = 0xffc8c8c8
ERROR_TEXT = {
"BAD_LOGIN": "账号需为4-16位英文字母或数字",
"BAD_PASSWORD": "密码需为4-16位字母、数字或符号",
"BAD_SOCIAL_ID": "删除码需为7位数字",
"EXISTS": "该账号已存在",
"RATE_LIMIT": "注册过于频繁,请稍后再试",
"CONNECT": "无法连接注册服务器",
"TIMEOUT": "注册服务器无响应",
"SERVER": "注册服务器出错,请稍后再试",
}
def _IsAlnum(text):
for c in text:
if not (("a" <= c <= "z") or ("A" <= c <= "Z") or ("0" <= c <= "9")):
return False
return True
def _IsPrintable(text):
for c in text:
if not ("!" <= c <= "~"):
return False
return True
def _Validate(login, password, confirm, socialID):
if not (LOGIN_MIN <= len(login) <= LOGIN_MAX) or not _IsAlnum(login):
return ERROR_TEXT["BAD_LOGIN"]
if not (PASSWORD_MIN <= len(password) <= PASSWORD_MAX) or not _IsPrintable(password):
return ERROR_TEXT["BAD_PASSWORD"]
if password != confirm:
return "两次输入的密码不一致"
if len(socialID) != SOCIAL_ID_LEN or not socialID.isdigit():
return ERROR_TEXT["BAD_SOCIAL_ID"]
return None
def _MakeButton(parent, x, y, image, text, event):
button = ui.Button()
button.SetParent(parent)
button.SetPosition(x, y)
button.SetUpVisual(image % 1)
button.SetOverVisual(image % 2)
button.SetDownVisual(image % 3)
button.SetText(L(text))
button.SetEvent(event)
button.Show()
return button
class InputRow:
LABEL_X = 18
SLOT_X = 96
SLOT_WIDTH = 160
def __init__(self, parent, y, label, maxLen):
self.label = ui.TextLine()
self.label.SetParent(parent)
self.label.SetPosition(self.LABEL_X, y + 2)
self.label.SetText(L(label))
self.label.Show()
self.slot = ui.SlotBar()
self.slot.SetParent(parent)
self.slot.SetPosition(self.SLOT_X, y)
self.slot.SetSize(self.SLOT_WIDTH, 18)
self.slot.Show()
self.edit = ui.EditLine()
self.edit.SetParent(self.slot)
self.edit.SetPosition(4, 2)
self.edit.SetSize(self.SLOT_WIDTH - 8, 16)
self.edit.SetMax(maxLen)
self.edit.SetIMEFlag(0)
self.edit.Show()
def GetText(self):
return self.edit.GetText()
def Destroy(self):
self.edit.SetReturnEvent(0)
self.edit.SetTabEvent(0)
self.edit = None
self.slot = None
self.label = None
class RegisterDialog(ui.BoardWithTitleBar):
WIDTH = 280
HEIGHT = 222
def __init__(self, loginWindow):
ui.BoardWithTitleBar.__init__(self)
self.loginWindow = loginWindow
self.pending = False
self.pendingLogin = ""
self.pendingPassword = ""
self.AddFlag("movable")
self.AddFlag("float")
self.SetSize(self.WIDTH, self.HEIGHT)
self.SetTitleName(L("注册账号"))
self.SetCloseEvent(ui.__mem_func__(self.Close))
self.loginRow = InputRow(self, 38, "账号", LOGIN_MAX)
self.passwordRow = InputRow(self, 66, "密码", PASSWORD_MAX)
self.passwordRow.edit.SetSecret(True)
self.confirmRow = InputRow(self, 94, "确认密码", PASSWORD_MAX)
self.confirmRow.edit.SetSecret(True)
self.socialRow = InputRow(self, 122, "删除码", SOCIAL_ID_LEN)
self.socialRow.edit.SetNumberMode()
rows = (self.loginRow, self.passwordRow, self.confirmRow, self.socialRow)
for i in xrange(len(rows)):
nextEdit = rows[(i + 1) % len(rows)].edit
rows[i].edit.SetTabEvent(ui.__mem_func__(nextEdit.SetFocus))
if i + 1 < len(rows):
rows[i].edit.SetReturnEvent(ui.__mem_func__(nextEdit.SetFocus))
self.socialRow.edit.SetReturnEvent(ui.__mem_func__(self.__OnClickRegister))
for row in rows:
row.edit.SetEscapeEvent(ui.__mem_func__(self.Close))
self.hintLine = ui.TextLine()
self.hintLine.SetParent(self)
self.hintLine.SetPosition(0, 150)
self.hintLine.SetWindowHorizontalAlignCenter()
self.hintLine.SetHorizontalAlignCenter()
self.hintLine.Show()
self.registerButton = _MakeButton(self, self.WIDTH / 2 - 66, 180, MIDDLE_BUTTON, "注册",
ui.__mem_func__(self.__OnClickRegister))
self.cancelButton = _MakeButton(self, self.WIDTH / 2 + 5, 180, MIDDLE_BUTTON, "取消",
ui.__mem_func__(self.Close))
def Destroy(self):
self.Hide()
for row in (self.loginRow, self.passwordRow, self.confirmRow, self.socialRow):
row.Destroy()
self.loginRow = self.passwordRow = self.confirmRow = self.socialRow = None
self.registerButton = None
self.cancelButton = None
self.hintLine = None
self.loginWindow = None
def Open(self):
for row in (self.loginRow, self.passwordRow, self.confirmRow, self.socialRow):
row.edit.SetText("")
self.__SetHint("账号仅限英文字母和数字,删除码用于删除角色", COLOR_INFO)
self.SetPosition((wndMgr.GetScreenWidth() - self.WIDTH) / 2, (wndMgr.GetScreenHeight() - self.HEIGHT) / 2)
self.Show()
self.SetTop()
self.loginRow.edit.SetFocus()
def Close(self):
for row in (self.loginRow, self.passwordRow, self.confirmRow, self.socialRow):
row.edit.KillFocus()
self.Hide()
if self.loginWindow and self.loginWindow.idEditLine:
self.loginWindow.idEditLine.SetFocus()
return True
def OnPressEscapeKey(self):
return self.Close()
def __SetHint(self, text, color):
self.hintLine.SetText(L(text))
self.hintLine.SetPackedFontColor(color)
def __GetHost(self):
stream = self.loginWindow.stream
if stream.account_addr:
return stream.account_addr
return stream.addr
def __OnClickRegister(self):
if self.pending:
return
login = self.loginRow.GetText()
password = self.passwordRow.GetText()
error = _Validate(login, password, self.confirmRow.GetText(), self.socialRow.GetText())
if error:
self.__SetHint(error, COLOR_ERROR)
return
host = self.__GetHost()
if not host:
self.__SetHint("请先选择服务器", COLOR_ERROR)
return
if not net.RegisterAccount(host, REGISTER_PORT, login, password, self.socialRow.GetText()):
return
self.pending = True
self.pendingLogin = login.lower()
self.pendingPassword = password
self.registerButton.Disable()
self.__SetHint("正在注册...", COLOR_INFO)
def OnUpdate(self):
if not self.pending:
return
result = net.GetRegisterAccountResult()
if not result:
return
self.pending = False
self.registerButton.Enable()
if result == "OK":
self.__OnRegistered()
return
code = result[4:] if result.startswith("ERR ") else "SERVER"
self.__SetHint(ERROR_TEXT.get(code, ERROR_TEXT["SERVER"]), COLOR_ERROR)
def __OnRegistered(self):
loginWindow = self.loginWindow
login, password = self.pendingLogin, self.pendingPassword
self.pendingPassword = ""
self.Close()
if loginWindow.idEditLine:
loginWindow.idEditLine.SetText(login)
if loginWindow.pwdEditLine:
loginWindow.pwdEditLine.SetText(password)
loginWindow.PopupNotifyMessage(L("账号 %s 注册成功,请点击登录") % login)
class RegisterEntry(ui.Window):
"The button under the login board; it follows the board's position and visibility every frame."
def __init__(self, loginWindow):
ui.Window.__init__(self)
self.loginWindow = loginWindow
self.dialog = RegisterDialog(loginWindow)
self.button = ui.Button()
self.button.SetUpVisual(LARGE_BUTTON % 1)
self.button.SetOverVisual(LARGE_BUTTON % 2)
self.button.SetDownVisual(LARGE_BUTTON % 3)
self.button.SetText(L("注册账号"))
self.button.SetEvent(ui.__mem_func__(self.dialog.Open))
self.SetSize(0, 0)
self.Show()
def Destroy(self):
self.Hide()
self.button.Hide()
self.button = None
self.dialog.Destroy()
self.dialog = None
self.loginWindow = None
def OnUpdate(self):
board = self.loginWindow.loginBoard if self.loginWindow else None
if not board or not self.loginWindow.IsShow() or not board.IsShow() or self.dialog.IsShow():
if self.button.IsShow():
self.button.Hide()
return
x, y = board.GetGlobalPosition()
self.button.SetPosition(x + (board.GetWidth() - self.button.GetWidth()) / 2, y + board.GetHeight() + 6)
if not self.button.IsShow():
self.button.Show()
self.button.SetTop()
_entries = {}
def Attach(loginWindow):
key = id(loginWindow)
if key not in _entries:
_entries[key] = RegisterEntry(loginWindow)
def Detach(loginWindow):
entry = _entries.pop(id(loginWindow), None)
if entry:
entry.Destroy()
def __Install():
openLogin = introLogin.LoginWindow.Open
closeLogin = introLogin.LoginWindow.Close
def Open(self):
result = openLogin(self)
try:
Attach(self)
except:
import dbg
dbg.TraceError("mt_register: attach failed")
return result
def Close(self):
Detach(self)
return closeLogin(self)
introLogin.LoginWindow.Open = Open
introLogin.LoginWindow.Close = Close
# system.py reaches app.Loop() before this runs, so a login window may already be open.
import gc
for obj in gc.get_objects():
if isinstance(obj, introLogin.LoginWindow) and getattr(obj, "loginBoard", None):
Attach(obj)
__Install()
)PY";
+31
View File
@@ -0,0 +1,31 @@
#include "ScriptLib/StdAfx.h"
#include "ScriptLib/Resource.h"
#include "EterLib/GrpImage.h"
#include "EterLib/GrpSubImage.h"
#include "EterLib/GrpText.h"
#include "EterLib/AttributeData.h"
#include "EterGrnLib/Thing.h"
#include "EffectLib/EffectMesh.h"
namespace {
CResource* NewUIImage(const char* name) { return new CGraphicImage(name); }
CResource* NewUISubImage(const char* name) { return new CGraphicSubImage(name); }
// 40250 UserInterface/PythonApplication.cpp NewText: a "<face>:<size>[i].fnt" name is a CGraphicText.
CResource* NewText(const char* name) { return new CGraphicText(name); }
CResource* NewThing(const char* name) { return new CGraphicThing(name); }
CResource* NewEffectMesh(const char* name) { return new CEffectMesh(name); }
CResource* NewAttributeData(const char* name) { return new CAttributeData(name); }
}
CPythonResource::CPythonResource() {
for (const char* ext : {"tga", "dds", "png", "jpg", "bmp"})
m_resManager.RegisterResourceNewFunctionPointer(ext, NewUIImage);
m_resManager.RegisterResourceNewFunctionPointer("sub", NewUISubImage);
m_resManager.RegisterResourceNewFunctionPointer("fnt", NewText);
m_resManager.RegisterResourceNewFunctionPointer("gr2", NewThing);
m_resManager.RegisterResourceNewFunctionPointer("mde", NewEffectMesh);
m_resManager.RegisterResourceNewFunctionPointer("mdatr", NewAttributeData);
}
CPythonResource::~CPythonResource() { m_resManager.DestroyDeletingList(); }
void CPythonResource::Destroy() { m_resManager.DestroyDeletingList(); m_resManager.Destroy(); }
void CPythonResource::DumpFileList(const char* name) { m_resManager.DumpFileListToTextFile(name); }
+863
View File
@@ -0,0 +1,863 @@
// PORT: stand-in for the closed IDV SpeedTreeRT 1.6.0 library (40250 extern/library/SpeedTreeRT.lib,
// Windows COFF). The class interface is the SDK header (port/common/shim/sdk/SpeedTreeRT.h) and the
// 40250 SpeedTreeLib wrapper/forest call it unchanged; this file implements the members they call.
//
// What is the SDK's contract and kept here:
// - GetGeometry fills SGeometry the way SpeedTreeWrapper reads it: one contiguous branch strip per
// LOD, static-lit m_pColors (LIGHT_STATIC; light 0 from SetLightAttributes, the tree material),
// m_pTexCoords1 self-shadow coordinates, camera-facing leaf clusters (m_pCenterCoords +
// m_pLeafMapCoords rebuilt from SetCamera) with m_pLeafMapTexCoords, alpha test values of 84
// (SetLeafTargetAlphaMask default 0x54 == c_nDefaultAlphaTestValue).
// - SetLodLevel(1.0f), which the wrapper always applies, selects discrete LOD 0 with billboards
// inactive; there is only that LOD.
// - GetTextures returns bare file names: the wrapper prefixes the .spt directory.
// - GetTreeSize reads the Size / SizeVariance header tokens (2001 / 2002) of the .spt.
// What is not the SDK (DIVERGENT; the notes are on the wrapper in audit/port-map/SpeedTreeLib/):
// - Branch and leaf geometry cannot be generated from the .spt parameters without the closed
// engine; it is the previous procedural proxy (species hints from the file name, 1000-unit
// height, crossed-branch trunk, hand-picked composite atlas rects), no fronds.
// - Collision objects are one trunk cylinder; the .spt collision block is not parsed.
// - Materials are the SDK defaults (white); the .spt material block is not parsed.
#include "SpeedTreeLib/StdAfx.h"
#include <SpeedTreeRT.h>
#include "spt.h"
#include "../EterLib/RenderCommands3D.h"
#include <algorithm>
#include <cctype>
#include <cmath>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <memory>
#include <string>
#include <vector>
namespace
{
constexpr float kPI = 3.14159265358979323846f;
constexpr float kTAU = 2.0f * kPI;
constexpr float kAlphaTestValue = 84.0f; // SetLeafTargetAlphaMask(0x54) default
constexpr float kProxyHeight = 1000.0f;
struct Vec3
{
float x = 0.0f, y = 0.0f, z = 0.0f;
Vec3() = default;
Vec3(float a, float b, float c) : x(a), y(b), z(c) {}
Vec3 operator+(const Vec3 & o) const { return { x + o.x, y + o.y, z + o.z }; }
Vec3 operator-(const Vec3 & o) const { return { x - o.x, y - o.y, z - o.z }; }
Vec3 operator*(float s) const { return { x * s, y * s, z * s }; }
};
float dot(const Vec3 & a, const Vec3 & b) { return a.x * b.x + a.y * b.y + a.z * b.z; }
Vec3 cross(const Vec3 & a, const Vec3 & b) { return { a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x }; }
Vec3 normalize(const Vec3 & v)
{
const float l = std::sqrt(dot(v, v));
return l > 1e-6f ? v * (1.0f / l) : Vec3(0.0f, 0.0f, 1.0f);
}
std::string to_lower_str(std::string s)
{
std::transform(s.begin(), s.end(), s.begin(), [](unsigned char c) { return static_cast<char>(std::tolower(c)); });
return s;
}
std::string basename_only(std::string path)
{
std::replace(path.begin(), path.end(), '\\', '/');
const size_t slash = path.find_last_of('/');
return slash == std::string::npos ? path : path.substr(slash + 1);
}
bool has_any(const std::string & hint, std::initializer_list<const char *> keys)
{
const std::string h = to_lower_str(hint);
for (const char * k : keys)
if (h.find(k) != std::string::npos)
return true;
return false;
}
bool is_conifer_species(const std::string & hint)
{
return has_any(hint, { "cedar", "cypress", "pine", "fir", "spruce", "conifer", "juniper", "christmastree" });
}
bool is_palm_species(const std::string & hint)
{
return has_any(hint, { "palm", "banana", "aloe", "fern", "joshua" });
}
uint32_t hash32(uint32_t s)
{
s ^= s >> 16;
s *= 0x7feb352dU;
s ^= s >> 15;
s *= 0x846ca68bU;
s ^= s >> 16;
return s;
}
float hash01(uint32_t s) { return float(hash32(s) & 0x00FFFFFFU) / float(0x01000000U); }
uint32_t species_seed(const std::string & s)
{
uint32_t h = 2166136261U;
for (unsigned char c : s)
{
h ^= c;
h *= 16777619U;
}
return h;
}
// Composite-atlas leaf rects, D3D image space (v down).
struct UVRect
{
float u0 = 0.0f, v0 = 0.0f, u1 = 1.0f, v1 = 1.0f;
};
std::vector<UVRect> foliage_rects(const std::string & species, const std::string & composite)
{
if (composite.empty())
return { { 0.0f, 0.0f, 1.0f, 1.0f } };
const std::string s = to_lower_str(species);
const std::string c = to_lower_str(composite);
const bool fall = s.find("fall") != std::string::npos;
const bool winter = s.find("winter") != std::string::npos;
if (c.find("b1") != std::string::npos)
{
if (fall)
return { { 0.00f, 0.05f, 0.25f, 0.25f }, { 0.25f, 0.25f, 0.50f, 0.50f } };
return { { 0.25f, 0.02f, 0.50f, 0.23f }, { 0.25f, 0.18f, 0.50f, 0.36f }, { 0.00f, 0.27f, 0.27f, 0.49f } };
}
if (c.find("b2") != std::string::npos)
{
if (fall)
return { { 0.00f, 0.00f, 0.25f, 0.25f }, { 0.25f, 0.25f, 0.50f, 0.50f } };
return { { 0.50f, 0.38f, 0.75f, 0.63f }, { 0.50f, 0.63f, 0.75f, 0.88f }, { 0.00f, 0.38f, 0.25f, 0.62f } };
}
if (c.find("b3") != std::string::npos)
{
if (fall)
return { { 0.25f, 0.25f, 0.50f, 0.50f } };
return { { 0.00f, 0.25f, 0.25f, 0.50f }, { 0.00f, 0.50f, 0.25f, 0.75f }, { 0.25f, 0.50f, 0.50f, 0.75f } };
}
if (c.find("n1") != std::string::npos)
{
if (winter)
return { { 0.00f, 0.36f, 0.50f, 0.58f }, { 0.25f, 0.55f, 0.52f, 0.75f } };
return { { 0.00f, 0.72f, 0.28f, 0.96f }, { 0.25f, 0.74f, 0.53f, 0.97f } };
}
if (c.find("n2") != std::string::npos)
return { { 0.00f, 0.48f, 0.27f, 0.75f }, { 0.26f, 0.73f, 0.58f, 1.00f }, { 0.75f, 0.48f, 1.00f, 0.80f } };
return { { 0.0f, 0.0f, 1.0f, 1.0f } };
}
// .spt header: 1000 <len> "__IdvSpt_02_", 1002, 2000 <len> <branch texture>, 2001 <float size>,
// 2002 <float variance>.
bool read_spt_size(const unsigned char * p, size_t n, float & size, float & variance)
{
size_t o = 0;
auto i32 = [&](int32_t & v) {
if (o + 4 > n)
return false;
std::memcpy(&v, p + o, 4);
o += 4;
return true;
};
int32_t t = 0, len = 0;
if (!i32(t) || t != 1000 || !i32(len) || len < 0 || (o += size_t(len)) > n)
return false;
if (!i32(t) || t != 1002 || !i32(t) || t != 2000 || !i32(len) || len < 0 || (o += size_t(len)) > n)
return false;
int32_t bits = 0;
if (!i32(t) || t != 2001 || !i32(bits))
return false;
std::memcpy(&size, &bits, 4);
if (!i32(t) || t != 2002 || !i32(bits))
return false;
std::memcpy(&variance, &bits, 4);
return true;
}
struct SStaticLight
{
float afAttributes[16] = {
-0.707f, 0.0f, 0.707f, 1.0f, 1.0f, 1.0f, 0.5f, 0.5f, 0.5f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f
};
bool bOn = false;
};
SStaticLight g_aLights[8];
float g_afCameraPos[3] = { 0.0f, 0.0f, 0.0f };
float g_afCameraDir[3] = { 0.0f, 1.0f, 0.0f };
bool g_bTextureFlip = false;
bool g_bDropToBillboard = false;
std::string g_strError;
void SetError(const char * pError) { g_strError = pError ? pError : ""; }
const float c_afDefaultMaterial[13] = { 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 5.0f };
// Static lighting (SLS_BASIC): material ambient x light ambient + material diffuse x light diffuse x N.L
// for every light switched on, clamped per channel.
unsigned long static_color(const Vec3 & n, const float * mat)
{
float rgb[3] = { 0.0f, 0.0f, 0.0f };
bool any = false;
for (const SStaticLight & light : g_aLights)
{
if (!light.bOn)
continue;
any = true;
const float * a = light.afAttributes;
const float ndotl = std::max(0.0f, dot(n, normalize(Vec3(a[0], a[1], a[2]))));
for (int c = 0; c < 3; ++c)
rgb[c] += mat[3 + c] * a[6 + c] + mat[c] * a[3 + c] * ndotl;
}
if (!any)
rgb[0] = rgb[1] = rgb[2] = 1.0f;
auto channel = [](float v) { return static_cast<unsigned long>(std::clamp(v, 0.0f, 1.0f) * 255.0f + 0.5f); };
return 0xFF000000UL | (channel(rgb[0]) << 16) | (channel(rgb[1]) << 8) | channel(rgb[2]);
}
// Geometry shared by a tree and its instances (the SDK shares it through m_pRefCount).
struct STreeData
{
std::string strName;
float fFileSize = -1.0f, fFileVariance = 0.0f;
float fSize = -1.0f, fVariance = 0.0f;
std::string strBranchTexture, strCompositeTexture, strSelfShadowTexture;
// branches
std::vector<float> vBranchCoords, vBranchNormals, vBranchTex0, vBranchTex1;
std::vector<unsigned long> vBranchColors;
std::vector<unsigned short> vBranchStrip;
unsigned short usBranchStripLength = 0;
const unsigned short * pBranchStrip = nullptr;
// leaves
struct SCluster
{
Vec3 vCenter, vNormal;
float fWidth = 0.0f, fHeight = 0.0f;
UVRect rect;
bool bFlip = false;
};
std::vector<SCluster> vClusters;
std::vector<float> vLeafCenters, vLeafNormals, vLeafTexCoords, vLeafCoords;
std::vector<unsigned long> vLeafColors;
std::vector<unsigned char> vLeafMapIndices;
std::vector<const float *> vLeafTexPtrs, vLeafCoordPtrs;
float afBoundingBox[6] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f };
float fTrunkRadius = 35.0f, fTrunkHeight = 600.0f;
float afBranchMaterial[13], afFrondMaterial[13], afLeafMaterial[13];
float fLeafLightingAdjustment = 0.75f;
bool bComputed = false;
STreeData()
{
std::memcpy(afBranchMaterial, c_afDefaultMaterial, sizeof(afBranchMaterial));
std::memcpy(afFrondMaterial, c_afDefaultMaterial, sizeof(afFrondMaterial));
std::memcpy(afLeafMaterial, c_afDefaultMaterial, sizeof(afLeafMaterial));
}
void Parse(const unsigned char * p, size_t n)
{
fmt::SptInfo info;
fmt::sniff_spt(std::string(reinterpret_cast<const char *>(p), n), info);
for (const std::string & ref : info.texture_refs)
if (to_lower_str(ref).find("bark") != std::string::npos)
{
strBranchTexture = basename_only(ref);
break;
}
if (strBranchTexture.empty() && !info.texture_refs.empty())
strBranchTexture = basename_only(info.texture_refs.front());
strCompositeTexture = basename_only(info.composite_texture);
strSelfShadowTexture = basename_only(info.self_shadow_texture);
read_spt_size(p, n, fFileSize, fFileVariance);
fSize = fFileSize;
fVariance = fFileVariance;
}
void AppendStrip(const std::vector<unsigned short> & sub)
{
if (sub.empty())
return;
if (!vBranchStrip.empty())
{
// degenerate join; keep the next strip on an even triangle so its winding is unchanged
vBranchStrip.push_back(vBranchStrip.back());
vBranchStrip.push_back(sub.front());
if (vBranchStrip.size() & 1)
vBranchStrip.push_back(sub.front());
}
vBranchStrip.insert(vBranchStrip.end(), sub.begin(), sub.end());
}
void AddTube(const Vec3 & from, const Vec3 & to, float r0, float r1, int seg, float bark_repeat)
{
Vec3 axis = to - from;
if (dot(axis, axis) < 1e-6f)
return;
axis = normalize(axis);
const Vec3 helper = std::fabs(axis.z) > 0.9f ? Vec3(1.0f, 0.0f, 0.0f) : Vec3(0.0f, 0.0f, 1.0f);
const Vec3 u = normalize(cross(axis, helper));
const Vec3 w = normalize(cross(axis, u));
std::vector<unsigned short> strip;
for (int i = 0; i <= seg; ++i)
{
if (vBranchCoords.size() / 3 + 2 > 65530)
break;
const float a = float(i) / float(seg) * kTAU;
const Vec3 n = u * std::cos(a) + w * std::sin(a);
const float s = float(i) / float(seg);
for (int end = 0; end < 2; ++end)
{
const Vec3 p = end ? to + n * r1 : from + n * r0;
strip.push_back(static_cast<unsigned short>(vBranchCoords.size() / 3));
vBranchCoords.insert(vBranchCoords.end(), { p.x, p.y, p.z });
vBranchNormals.insert(vBranchNormals.end(), { n.x, n.y, n.z });
vBranchTex0.insert(vBranchTex0.end(), { s, end ? 0.0f : bark_repeat });
}
}
AppendStrip(strip);
}
void BuildBranches(float H, bool conifer, bool palm)
{
const float trunk_top = H * (palm ? 0.82f : (conifer ? 0.90f : 0.76f));
const float trunk_r = H * (palm ? 0.028f : 0.035f);
const float H_m = H * 0.01f;
AddTube(Vec3(0.0f, 0.0f, 0.0f), Vec3(0.0f, 0.0f, trunk_top), trunk_r * 1.35f, trunk_r * 0.42f, 9, H_m * 0.22f);
if (palm)
return;
const int count = conifer ? 9 : 8;
const uint32_t seed = species_seed(strName);
for (int i = 0; i < count; ++i)
{
const float f = (i + 1.0f) / (count + 1.0f);
const float z = H * (conifer ? (0.28f + f * 0.52f) : (0.32f + f * 0.34f));
const float angle = kTAU * (f * 1.6180339f + hash01(seed + i * 17U));
const float len = H * (conifer ? (0.24f * (1.0f - f * 0.55f)) : (0.18f + 0.08f * hash01(seed + i * 29U)));
const Vec3 from(0.0f, 0.0f, z);
const Vec3 to(std::cos(angle) * len, std::sin(angle) * len,
z + H * (conifer ? 0.06f : (0.10f + 0.06f * hash01(seed + i * 31U))));
AddTube(from, to, trunk_r * (0.55f - 0.20f * f), trunk_r * 0.12f, 6, H_m * 0.08f);
if (!conifer && (i % 2 == 0))
{
const float side = angle + (hash01(seed + i * 37U) > 0.5f ? 0.65f : -0.65f);
const Vec3 tip = to + Vec3(std::cos(side), std::sin(side), 0.65f) * (len * 0.42f);
AddTube(to, tip, trunk_r * 0.16f, trunk_r * 0.05f, 5, H_m * 0.04f);
}
}
}
void BuildLeaves(float H, bool conifer, bool palm)
{
const std::vector<UVRect> rects = foliage_rects(strName, strCompositeTexture);
const uint32_t seed = species_seed(strName);
const int count = palm ? 16 : 24;
for (int i = 0; i < count; ++i)
{
const float a = kTAU * (float(i) * 0.6180339f + hash01(seed + i * 101U) * 0.15f);
SCluster c;
if (palm)
{
const float radial = H * (0.10f + 0.18f * hash01(seed + i * 103U));
c.vCenter = Vec3(std::cos(a) * radial, std::sin(a) * radial, H * (0.78f + 0.12f * hash01(seed + i * 107U)));
c.fWidth = H * 0.32f;
c.fHeight = H * 0.18f;
}
else if (conifer)
{
const float zf = 0.30f + 0.62f * (float(i) + 0.5f) / float(count);
const float radial = H * 0.23f * (1.0f - zf * 0.70f) * (0.35f + 0.65f * hash01(seed + i * 109U));
c.vCenter = Vec3(std::cos(a) * radial, std::sin(a) * radial, H * zf);
c.fWidth = H * (0.18f + 0.10f * (1.0f - zf));
c.fHeight = H * 0.18f;
}
else
{
const float zf = hash01(seed + i * 109U);
const float zn = zf * 2.0f - 1.0f;
const float radial = H * 0.34f * std::sqrt(std::max(0.05f, 1.0f - zn * zn)) *
(0.25f + 0.75f * std::sqrt(hash01(seed + i * 113U)));
c.vCenter = Vec3(std::cos(a) * radial, std::sin(a) * radial, H * (0.58f + zf * 0.34f));
c.fWidth = H * (0.23f + 0.10f * hash01(seed + i * 127U));
c.fHeight = H * (0.15f + 0.08f * hash01(seed + i * 131U));
}
// cluster normal: away from the crown centre, biased up
const Vec3 out = normalize(c.vCenter - Vec3(0.0f, 0.0f, H * 0.6f));
c.vNormal = normalize(Vec3(out.x, out.y, std::fabs(out.z) * 0.5f + 0.5f));
c.rect = rects[size_t(i) % rects.size()];
c.bFlip = (i & 1) != 0;
vClusters.push_back(c);
}
}
void Compute()
{
const bool enabled = IsNativeTerrainRenderEnabled();
const float H = kProxyHeight;
const float R = H * 0.35f;
afBoundingBox[0] = -R;
afBoundingBox[1] = -R;
afBoundingBox[2] = 0.0f;
afBoundingBox[3] = R;
afBoundingBox[4] = R;
afBoundingBox[5] = H;
fTrunkRadius = H * 0.035f;
fTrunkHeight = H * 0.75f;
// PORT: the Godot host draws its own trees unless the native terrain renderer is on; the tree
// then has no geometry so the forest submits nothing.
if (enabled)
{
const bool conifer = is_conifer_species(strName);
const bool palm = is_palm_species(strName);
BuildBranches(H, conifer, palm);
BuildLeaves(H, conifer, palm);
}
const size_t nBranchVerts = vBranchCoords.size() / 3;
vBranchColors.resize(nBranchVerts);
vBranchTex1.resize(nBranchVerts * 2);
for (size_t i = 0; i < nBranchVerts; ++i)
{
const Vec3 n(vBranchNormals[i * 3], vBranchNormals[i * 3 + 1], vBranchNormals[i * 3 + 2]);
vBranchColors[i] = static_color(n, afBranchMaterial);
// self-shadow map projected straight down over the bounding box
vBranchTex1[i * 2] = (vBranchCoords[i * 3] - afBoundingBox[0]) / (afBoundingBox[3] - afBoundingBox[0]);
vBranchTex1[i * 2 + 1] = (vBranchCoords[i * 3 + 1] - afBoundingBox[1]) / (afBoundingBox[4] - afBoundingBox[1]);
}
if (g_bTextureFlip)
for (size_t i = 0; i < nBranchVerts; ++i)
{
vBranchTex0[i * 2 + 1] = 1.0f - vBranchTex0[i * 2 + 1];
vBranchTex1[i * 2 + 1] = 1.0f - vBranchTex1[i * 2 + 1];
}
usBranchStripLength = static_cast<unsigned short>(vBranchStrip.size());
pBranchStrip = vBranchStrip.empty() ? nullptr : vBranchStrip.data();
const size_t nLeaves = vClusters.size();
vLeafCenters.resize(nLeaves * 3);
vLeafNormals.resize(nLeaves * 3);
vLeafColors.resize(nLeaves);
vLeafMapIndices.assign(nLeaves, 0);
vLeafTexCoords.resize(nLeaves * 8);
vLeafCoords.assign(nLeaves * 16, 0.0f);
vLeafTexPtrs.resize(nLeaves);
vLeafCoordPtrs.resize(nLeaves);
for (size_t i = 0; i < nLeaves; ++i)
{
const SCluster & c = vClusters[i];
std::memcpy(&vLeafCenters[i * 3], &c.vCenter, 12);
std::memcpy(&vLeafNormals[i * 3], &c.vNormal, 12);
vLeafColors[i] = static_color(c.vNormal, afLeafMaterial);
// corners 0..3: (+r,+u) (-r,+u) (-r,-u) (+r,-u); drawn as 0,1,2 / 0,2,3
const float uR = c.bFlip ? c.rect.u0 : c.rect.u1, uL = c.bFlip ? c.rect.u1 : c.rect.u0;
float * t = &vLeafTexCoords[i * 8];
const float vTop = g_bTextureFlip ? c.rect.v0 : 1.0f - c.rect.v0;
const float vBottom = g_bTextureFlip ? c.rect.v1 : 1.0f - c.rect.v1;
t[0] = uR; t[1] = vTop;
t[2] = uL; t[3] = vTop;
t[4] = uL; t[5] = vBottom;
t[6] = uR; t[7] = vBottom;
vLeafTexPtrs[i] = t;
vLeafCoordPtrs[i] = &vLeafCoords[i * 16];
}
bComputed = true;
}
// SDK leaf clusters face the camera given to SetCamera.
void UpdateLeafCoords()
{
const Vec3 dir = normalize(Vec3(g_afCameraDir[0], g_afCameraDir[1], g_afCameraDir[2]));
Vec3 right = cross(dir, Vec3(0.0f, 0.0f, 1.0f));
right = dot(right, right) < 1e-6f ? Vec3(1.0f, 0.0f, 0.0f) : normalize(right);
const Vec3 up = normalize(cross(right, dir));
for (size_t i = 0; i < vClusters.size(); ++i)
{
const SCluster & c = vClusters[i];
const Vec3 r = right * (c.fWidth * 0.5f), u = up * (c.fHeight * 0.5f);
const Vec3 corners[4] = { r + u, u - r, Vec3() - r - u, r - u };
float * p = &vLeafCoords[i * 16];
for (int k = 0; k < 4; ++k)
{
p[k * 4 + 0] = corners[k].x;
p[k * 4 + 1] = corners[k].y;
p[k * 4 + 2] = corners[k].z;
p[k * 4 + 3] = 0.0f;
}
}
}
};
} // namespace
struct CSpeedTreeRT::SImpl
{
std::shared_ptr<STreeData> pTree = std::make_shared<STreeData>();
const CSpeedTreeRT * pInstanceOf = nullptr;
float afPosition[3] = { 0.0f, 0.0f, 0.0f };
float fLodLevel = 1.0f;
float fLodNear = 100.0f, fLodFar = 1000.0f;
float fWindStrength = 0.0f;
unsigned int uiLocalStart = 0, uiLocalSpan = 0;
unsigned int uiSeed = 1;
bool bLeafRocking = false;
unsigned int uiRockingGroups = 1;
ELightingMethod eBranchLighting = LIGHT_STATIC, eLeafLighting = LIGHT_STATIC, eFrondLighting = LIGHT_STATIC;
EWindMethod eBranchWind = WIND_NONE, eLeafWind = WIND_NONE, eFrondWind = WIND_NONE;
float afLeafLodSizes[1] = { 1.0f };
};
CSpeedTreeRT::SGeometry::SIndexed::SIndexed()
: m_nDiscreteLodLevel(-1), m_usNumStrips(0), m_pStripLengths(nullptr), m_pStrips(nullptr), m_usVertexCount(0),
m_pColors(nullptr), m_pNormals(nullptr), m_pBinormals(nullptr), m_pTangents(nullptr), m_pCoords(nullptr),
m_pTexCoords0(nullptr), m_pTexCoords1(nullptr), m_pWindWeights(nullptr), m_pWindMatrixIndices(nullptr)
{
}
CSpeedTreeRT::SGeometry::SIndexed::~SIndexed() {}
CSpeedTreeRT::SGeometry::SLeaf::SLeaf()
: m_bIsActive(false), m_fAlphaTestValue(0.0f), m_nDiscreteLodLevel(-1), m_usLeafCount(0), m_pLeafMapIndices(nullptr),
m_pLeafClusterIndices(nullptr), m_pCenterCoords(nullptr), m_pLeafMapTexCoords(nullptr), m_pLeafMapCoords(nullptr),
m_pColors(nullptr), m_pNormals(nullptr), m_pBinormals(nullptr), m_pTangents(nullptr), m_pWindWeights(nullptr),
m_pWindMatrixIndices(nullptr)
{
}
CSpeedTreeRT::SGeometry::SLeaf::~SLeaf() {}
CSpeedTreeRT::SGeometry::SBillboard::SBillboard()
: m_bIsActive(false), m_pTexCoords(nullptr), m_pCoords(nullptr), m_fAlphaTestValue(0.0f)
{
}
CSpeedTreeRT::SGeometry::SBillboard::~SBillboard() {}
CSpeedTreeRT::SGeometry::SGeometry() : m_fBranchAlphaTestValue(0.0f), m_fFrondAlphaTestValue(0.0f) {}
CSpeedTreeRT::SGeometry::~SGeometry() {}
CSpeedTreeRT::STextures::STextures()
: m_pBranchTextureFilename(nullptr), m_uiLeafTextureCount(0), m_pLeafTextureFilenames(nullptr),
m_uiFrondTextureCount(0), m_pFrondTextureFilenames(nullptr), m_pCompositeFilename(nullptr),
m_pSelfShadowFilename(nullptr)
{
}
CSpeedTreeRT::STextures::~STextures() {}
CSpeedTreeRT::CSpeedTreeRT() : m_pImpl(new SImpl) {}
CSpeedTreeRT::~CSpeedTreeRT() { delete m_pImpl; }
void * CSpeedTreeRT::operator new(size_t nSize) { return ::operator new(nSize); }
void * CSpeedTreeRT::operator new[](size_t nSize) { return ::operator new[](nSize); }
void CSpeedTreeRT::operator delete(void * pRawMemory) { ::operator delete(pRawMemory); }
void CSpeedTreeRT::operator delete[](void * pRawMemory) { ::operator delete[](pRawMemory); }
bool CSpeedTreeRT::LoadTree(const char * pFilename)
{
SetError(pFilename ? "SpeedTreeRT: file loading is not supported, pass the pack block" : "SpeedTreeRT: no file name");
return false;
}
bool CSpeedTreeRT::LoadTree(const unsigned char * pBlock, unsigned int nNumBytes)
{
if (!pBlock || nNumBytes < 16)
{
SetError("SpeedTreeRT: empty tree block");
return false;
}
m_pImpl->pTree = std::make_shared<STreeData>();
m_pImpl->pTree->Parse(pBlock, nNumBytes);
return true;
}
void CSpeedTreeRT::SetSourceName(const char * pFilename)
{
m_pImpl->pTree->strName = pFilename ? pFilename : "";
}
bool CSpeedTreeRT::Compute(const float * /*pTransform*/, unsigned int nSeed, bool /*bCompositeStrips*/)
{
STreeData & tree = *m_pImpl->pTree;
if (tree.bComputed)
{
SetError("SpeedTreeRT: tree already computed");
return false;
}
m_pImpl->uiSeed = nSeed;
tree.Compute();
return true;
}
CSpeedTreeRT * CSpeedTreeRT::MakeInstance(void)
{
CSpeedTreeRT * pInstance = new CSpeedTreeRT;
*pInstance->m_pImpl = *m_pImpl;
pInstance->m_pImpl->pInstanceOf = this;
return pInstance;
}
const CSpeedTreeRT * CSpeedTreeRT::InstanceOf(void) const { return m_pImpl->pInstanceOf; }
void CSpeedTreeRT::DeleteTransientData(void) {}
void CSpeedTreeRT::GetTreeSize(float & fSize, float & fVariance) const
{
fSize = m_pImpl->pTree->fSize;
fVariance = m_pImpl->pTree->fVariance;
}
void CSpeedTreeRT::SetTreeSize(float fNewSize, float fNewVariance)
{
m_pImpl->pTree->fSize = fNewSize;
m_pImpl->pTree->fVariance = fNewVariance;
}
unsigned int CSpeedTreeRT::GetSeed() const { return m_pImpl->uiSeed; }
const float * CSpeedTreeRT::GetTreePosition(void) const { return m_pImpl->afPosition; }
void CSpeedTreeRT::SetTreePosition(float x, float y, float z)
{
m_pImpl->afPosition[0] = x;
m_pImpl->afPosition[1] = y;
m_pImpl->afPosition[2] = z;
}
CSpeedTreeRT::ELightingMethod CSpeedTreeRT::GetBranchLightingMethod(void) const { return m_pImpl->eBranchLighting; }
void CSpeedTreeRT::SetBranchLightingMethod(ELightingMethod eMethod) { m_pImpl->eBranchLighting = eMethod; }
CSpeedTreeRT::ELightingMethod CSpeedTreeRT::GetLeafLightingMethod(void) const { return m_pImpl->eLeafLighting; }
void CSpeedTreeRT::SetLeafLightingMethod(ELightingMethod eMethod) { m_pImpl->eLeafLighting = eMethod; }
CSpeedTreeRT::ELightingMethod CSpeedTreeRT::GetFrondLightingMethod(void) const { return m_pImpl->eFrondLighting; }
void CSpeedTreeRT::SetFrondLightingMethod(ELightingMethod eMethod) { m_pImpl->eFrondLighting = eMethod; }
float CSpeedTreeRT::GetLeafLightingAdjustment() const { return m_pImpl->pTree->fLeafLightingAdjustment; }
void CSpeedTreeRT::SetLeafLightingAdjustment(float fScalar) { m_pImpl->pTree->fLeafLightingAdjustment = fScalar; }
bool CSpeedTreeRT::GetLightState(unsigned int nLightIndex) { return nLightIndex < 8 && g_aLights[nLightIndex].bOn; }
void CSpeedTreeRT::SetLightState(unsigned int nLightIndex, bool bLightOn)
{
if (nLightIndex < 8)
g_aLights[nLightIndex].bOn = bLightOn;
}
const float * CSpeedTreeRT::GetLightAttributes(unsigned int nLightIndex)
{
return nLightIndex < 8 ? g_aLights[nLightIndex].afAttributes : nullptr;
}
void CSpeedTreeRT::SetLightAttributes(unsigned int nLightIndex, const float * pLightAttributes)
{
if (nLightIndex < 8 && pLightAttributes)
std::memcpy(g_aLights[nLightIndex].afAttributes, pLightAttributes, sizeof(g_aLights[nLightIndex].afAttributes));
}
const float * CSpeedTreeRT::GetBranchMaterial(void) const { return m_pImpl->pTree->afBranchMaterial; }
void CSpeedTreeRT::SetBranchMaterial(const float * pMaterial) { std::memcpy(m_pImpl->pTree->afBranchMaterial, pMaterial, 13 * sizeof(float)); }
const float * CSpeedTreeRT::GetLeafMaterial(void) const { return m_pImpl->pTree->afLeafMaterial; }
void CSpeedTreeRT::SetLeafMaterial(const float * pMaterial) { std::memcpy(m_pImpl->pTree->afLeafMaterial, pMaterial, 13 * sizeof(float)); }
const float * CSpeedTreeRT::GetFrondMaterial(void) const { return m_pImpl->pTree->afFrondMaterial; }
void CSpeedTreeRT::SetFrondMaterial(const float * pMaterial) { std::memcpy(m_pImpl->pTree->afFrondMaterial, pMaterial, 13 * sizeof(float)); }
void CSpeedTreeRT::GetCamera(float * pPosition, float * pDirection)
{
if (pPosition)
std::memcpy(pPosition, g_afCameraPos, sizeof(g_afCameraPos));
if (pDirection)
std::memcpy(pDirection, g_afCameraDir, sizeof(g_afCameraDir));
}
void CSpeedTreeRT::SetCamera(const float * pPosition, const float * pDirection)
{
if (pPosition)
std::memcpy(g_afCameraPos, pPosition, sizeof(g_afCameraPos));
if (pDirection)
std::memcpy(g_afCameraDir, pDirection, sizeof(g_afCameraDir));
}
// WRAPPER_USE_NO_WIND: the wind entry points only keep their state.
void CSpeedTreeRT::SetTime(float /*fTime*/) {}
void CSpeedTreeRT::ComputeWindEffects(bool /*bBranches*/, bool /*bLeaves*/, bool /*bFronds*/) {}
void CSpeedTreeRT::ResetLeafWindState(void) {}
bool CSpeedTreeRT::GetLeafRockingState(void) const { return m_pImpl->bLeafRocking; }
void CSpeedTreeRT::SetLeafRockingState(bool bFlag) { m_pImpl->bLeafRocking = bFlag; }
void CSpeedTreeRT::SetNumLeafRockingGroups(unsigned int nRockingGroups) { m_pImpl->uiRockingGroups = nRockingGroups; }
CSpeedTreeRT::EWindMethod CSpeedTreeRT::GetLeafWindMethod(void) const { return m_pImpl->eLeafWind; }
void CSpeedTreeRT::SetLeafWindMethod(EWindMethod eMethod) { m_pImpl->eLeafWind = eMethod; }
CSpeedTreeRT::EWindMethod CSpeedTreeRT::GetBranchWindMethod(void) const { return m_pImpl->eBranchWind; }
void CSpeedTreeRT::SetBranchWindMethod(EWindMethod eMethod) { m_pImpl->eBranchWind = eMethod; }
CSpeedTreeRT::EWindMethod CSpeedTreeRT::GetFrondWindMethod(void) const { return m_pImpl->eFrondWind; }
void CSpeedTreeRT::SetFrondWindMethod(EWindMethod eMethod) { m_pImpl->eFrondWind = eMethod; }
float CSpeedTreeRT::GetWindStrength(void) const { return m_pImpl->fWindStrength; }
float CSpeedTreeRT::SetWindStrength(float fNewStrength, float /*fOldStrength*/, float /*fFrequencyTimeOffset*/)
{
const float fOld = m_pImpl->fWindStrength;
m_pImpl->fWindStrength = fNewStrength;
return fOld;
}
void CSpeedTreeRT::SetNumWindMatrices(unsigned int /*nNumMatrices*/) {}
void CSpeedTreeRT::SetWindMatrix(unsigned int /*nMatrixIndex*/, const float * /*pMatrix*/) {}
void CSpeedTreeRT::GetLocalMatrices(unsigned int & nStartingIndex, unsigned int & nMatrixSpan)
{
nStartingIndex = m_pImpl->uiLocalStart;
nMatrixSpan = m_pImpl->uiLocalSpan;
}
void CSpeedTreeRT::SetLocalMatrices(unsigned int nStartingMatrix, unsigned int nMatrixSpan)
{
m_pImpl->uiLocalStart = nStartingMatrix;
m_pImpl->uiLocalSpan = nMatrixSpan;
}
void CSpeedTreeRT::ComputeLodLevel(void)
{
const float dx = m_pImpl->afPosition[0] - g_afCameraPos[0];
const float dy = m_pImpl->afPosition[1] - g_afCameraPos[1];
const float dz = m_pImpl->afPosition[2] - g_afCameraPos[2];
const float fDistance = std::sqrt(dx * dx + dy * dy + dz * dz);
const float fRange = std::max(1e-3f, m_pImpl->fLodFar - m_pImpl->fLodNear);
m_pImpl->fLodLevel = 1.0f - std::clamp((fDistance - m_pImpl->fLodNear) / fRange, 0.0f, 1.0f);
}
float CSpeedTreeRT::GetLodLevel(void) const { return m_pImpl->fLodLevel; }
void CSpeedTreeRT::SetLodLevel(float fLodLevel) { m_pImpl->fLodLevel = std::clamp(fLodLevel, 0.0f, 1.0f); }
void CSpeedTreeRT::SetDropToBillboard(bool bFlag) { g_bDropToBillboard = bFlag; }
void CSpeedTreeRT::GetLodLimits(float & fNear, float & fFar) const
{
fNear = m_pImpl->fLodNear;
fFar = m_pImpl->fLodFar;
}
void CSpeedTreeRT::SetLodLimits(float fNear, float fFar)
{
m_pImpl->fLodNear = fNear;
m_pImpl->fLodFar = fFar;
}
short CSpeedTreeRT::GetDiscreteBranchLodLevel(float /*fLodLevel*/) const { return 0; }
unsigned short CSpeedTreeRT::GetDiscreteLeafLodLevel(float /*fLodLevel*/) const { return 0; }
short CSpeedTreeRT::GetDiscreteFrondLodLevel(float /*fLodLevel*/) const { return 0; }
unsigned short CSpeedTreeRT::GetNumBranchLodLevels(void) const { return 1; }
unsigned short CSpeedTreeRT::GetNumLeafLodLevels(void) const { return 1; }
unsigned short CSpeedTreeRT::GetNumFrondLodLevels(void) const { return 1; }
const float * CSpeedTreeRT::GetLeafBillboardTable(unsigned int & nEntryCount) const
{
nEntryCount = 0;
return nullptr;
}
const float * CSpeedTreeRT::GetLeafLodSizeAdjustments(void) { return m_pImpl->afLeafLodSizes; }
void CSpeedTreeRT::GetGeometry(SGeometry & sGeometry, unsigned long ulBitVector, short /*sOverrideBranchLodValue*/,
short /*sOverrideFrondLodValue*/, short /*sOverrideLeafLodValue*/)
{
STreeData & tree = *m_pImpl->pTree;
if (ulBitVector & SpeedTree_BranchGeometry)
{
SGeometry::SIndexed & b = sGeometry.m_sBranches;
b = SGeometry::SIndexed();
b.m_nDiscreteLodLevel = 0;
b.m_usVertexCount = static_cast<unsigned short>(tree.vBranchCoords.size() / 3);
b.m_usNumStrips = tree.usBranchStripLength ? 1 : 0;
b.m_pStripLengths = &tree.usBranchStripLength;
b.m_pStrips = &tree.pBranchStrip;
b.m_pColors = tree.vBranchColors.data();
b.m_pNormals = tree.vBranchNormals.data();
b.m_pCoords = tree.vBranchCoords.data();
b.m_pTexCoords0 = tree.vBranchTex0.data();
b.m_pTexCoords1 = tree.vBranchTex1.data();
sGeometry.m_fBranchAlphaTestValue = kAlphaTestValue;
}
if (ulBitVector & SpeedTree_FrondGeometry)
{
sGeometry.m_sFronds = SGeometry::SIndexed();
sGeometry.m_sFronds.m_nDiscreteLodLevel = 0;
sGeometry.m_fFrondAlphaTestValue = kAlphaTestValue;
}
if (ulBitVector & SpeedTree_LeafGeometry)
{
tree.UpdateLeafCoords();
SGeometry::SLeaf & l = sGeometry.m_sLeaves0;
l = SGeometry::SLeaf();
l.m_bIsActive = !tree.vClusters.empty();
l.m_fAlphaTestValue = kAlphaTestValue;
l.m_nDiscreteLodLevel = 0;
l.m_usLeafCount = static_cast<unsigned short>(tree.vClusters.size());
l.m_pLeafMapIndices = tree.vLeafMapIndices.data();
l.m_pCenterCoords = tree.vLeafCenters.data();
l.m_pLeafMapTexCoords = tree.vLeafTexPtrs.data();
l.m_pLeafMapCoords = tree.vLeafCoordPtrs.data();
l.m_pColors = tree.vLeafColors.data();
l.m_pNormals = tree.vLeafNormals.data();
sGeometry.m_sLeaves1 = SGeometry::SLeaf();
}
if (ulBitVector & SpeedTree_BillboardGeometry)
{
sGeometry.m_sBillboard0 = SGeometry::SBillboard();
sGeometry.m_sBillboard1 = SGeometry::SBillboard();
sGeometry.m_sHorizontalBillboard = SGeometry::SBillboard();
}
}
void CSpeedTreeRT::GetTextures(STextures & sTextures) const
{
const STreeData & tree = *m_pImpl->pTree;
sTextures = STextures();
sTextures.m_pBranchTextureFilename = tree.strBranchTexture.c_str();
sTextures.m_pCompositeFilename = tree.strCompositeTexture.empty() ? nullptr : tree.strCompositeTexture.c_str();
sTextures.m_pSelfShadowFilename = tree.strSelfShadowTexture.empty() ? nullptr : tree.strSelfShadowTexture.c_str();
}
bool CSpeedTreeRT::GetTextureFlip(void) { return g_bTextureFlip; }
void CSpeedTreeRT::SetTextureFlip(bool bFlag) { g_bTextureFlip = bFlag; }
const char * CSpeedTreeRT::GetCurrentError(void) { return g_strError.c_str(); }
void CSpeedTreeRT::ResetError(void) { g_strError.clear(); }
void CSpeedTreeRT::GetBoundingBox(float * pBounds) const
{
std::memcpy(pBounds, m_pImpl->pTree->afBoundingBox, 6 * sizeof(float));
}
unsigned int CSpeedTreeRT::GetCollisionObjectCount(void) { return 1; }
void CSpeedTreeRT::GetCollisionObject(unsigned int /*nIndex*/, ECollisionObjectType & eType, float * pPosition, float * pDimensions)
{
const STreeData & tree = *m_pImpl->pTree;
eType = CO_CYLINDER;
if (pPosition)
pPosition[0] = pPosition[1] = pPosition[2] = 0.0f;
if (pDimensions)
{
pDimensions[0] = tree.fTrunkRadius;
pDimensions[1] = tree.fTrunkHeight;
pDimensions[2] = 0.0f;
}
}
+93
View File
@@ -0,0 +1,93 @@
#include "spt.h"
#include <cctype>
#include <cstdint>
#include <cstring>
namespace fmt {
namespace {
bool ends_with_ci(const std::string& s, const char* suf) {
size_t n = std::strlen(suf);
if (s.size() < n) return false;
for (size_t i = 0; i < n; ++i)
if (std::tolower((unsigned char)s[s.size() - n + i]) != std::tolower((unsigned char)suf[i]))
return false;
return true;
}
std::string token_ci(const std::string& bytes, const char* needle) {
const size_t n = std::strlen(needle);
if (n == 0 || bytes.size() < n) return "";
for (size_t i = 0; i + n <= bytes.size(); ++i) {
bool match = true;
for (size_t j = 0; j < n; ++j) {
if (std::tolower((unsigned char)bytes[i + j]) !=
std::tolower((unsigned char)needle[j])) {
match = false;
break;
}
}
if (!match) continue;
size_t e = i + n;
while (e < bytes.size()) {
const unsigned char c = (unsigned char)bytes[e];
if (!(std::isalnum(c) || c == '_' || c == '-')) break;
++e;
}
return bytes.substr(i, e - i);
}
return "";
}
std::string as_dds(std::string s) {
if (s.empty()) return s;
const size_t dot = s.find_last_of('.');
if (dot != std::string::npos) s.resize(dot);
return s + ".dds";
}
} // namespace
bool sniff_spt(const std::string& b, SptInfo& out) {
out = SptInfo{};
if (b.size() < 20) return false;
std::memcpy(&out.header_dword, b.data(), 4);
uint32_t maglen = 0;
std::memcpy(&maglen, b.data() + 4, 4);
if (maglen >= 4 && maglen <= 32 && 8 + maglen <= b.size()) {
out.magic.assign(b.data() + 8, b.data() + 8 + maglen);
// 去掉可能的尾随 NUL
while (!out.magic.empty() && out.magic.back() == '\0') out.magic.pop_back();
}
out.ok = out.magic.rfind("__IdvSpt", 0) == 0;
// 扫描可打印 ASCII 段,收 .tga / .dds 结尾的
std::string cur;
auto flush = [&] {
if (cur.size() >= 5 && (ends_with_ci(cur, ".tga") || ends_with_ci(cur, ".dds"))) {
// 只留文件名基础部分之后的路径(原样)
out.texture_refs.push_back(cur);
}
cur.clear();
};
for (unsigned char c : b) {
if (c >= 0x20 && c < 0x7F) {
cur += (char)c;
} else {
flush();
}
}
flush();
// 这两个名字在真实 v2 .spt 中常紧跟二进制标记,不会由上面的
// "字符串必须正好以扩展名结尾" 规则捕获。
out.composite_texture = as_dds(token_ci(b, "CompositeMap"));
out.self_shadow_texture = as_dds(token_ci(b, "CompositeShadowMap"));
return out.ok;
}
} // namespace fmt
+34
View File
@@ -0,0 +1,34 @@
// .spt —— SpeedTree RT 私有格式(IDV Inc.)。
//
// W4 调研结论(2026-08-29):**几何无法读**。`.spt` 的解析在闭源 `CSpeedTreeRT::LoadTree()`
// 里(`m2dev-client-src-main/extern/library/SpeedTree/speedtree_static.lib`,实测 COFF x86-64,
// IDV 专有,不能链进 macOS/移动端、不可随意分发);`SpeedTreeLib/` 是渲染 wrapper,不含 parser。
// → 运行时使用读取真实 bark/composite atlas 的 proxy;真几何走经授权的 Windows x64 离线 exporter。
// 2026-09-11: hash-matched native exports for 87 local species are now staged in
// assets/TreeGeometry and loaded preferentially by the runtime. This sniffer
// remains only the fallback texture reader, not a geometry decoder.
//
// 这里只做「嗅探」:读文件头 magic + version,抽取内嵌贴图和 composite atlas token。
// 不解析枝干/叶片几何。无 godot 依赖。
#pragma once
#include <cstdint>
#include <string>
#include <vector>
namespace fmt {
struct SptInfo {
bool ok = false;
std::string magic; // "__IdvSpt_02_" 等
uint32_t header_dword = 0; // magic 前的第一个 u32(版本/大小,未定)
std::vector<std::string> texture_refs; // 内嵌的 *.tga / *.dds 路径(原样)
// SpeedTree 2 把这两个 atlas 名写成不一定以 NUL 结尾的 token(例如
// "CompositeMapB1#N"),普通 printable-string 扫描会漏掉。统一转成 .dds,
// 供无几何 reader 的 proxy 渲染使用。
std::string composite_texture;
std::string self_shadow_texture;
};
bool sniff_spt(const std::string& bytes, SptInfo& out);
} // namespace fmt
+23
View File
@@ -0,0 +1,23 @@
// Platform skeleton for UserInterface/ProcessCRC.h (40250 UserInterface/ProcessCRC.cpp), generated by platform_stub.py.
// Every MT_PLATFORM_STUB() body is unimplemented: replace it with the platform implementation.
#include "UserInterface/StdAfx.h"
#include "UserInterface/ProcessCRC.h"
#include "../PlatformStub.h"
auto GetExeCRC(DWORD &, DWORD &) -> bool
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<bool>();
}
auto BuildProcessCRC() -> void
{
MT_PLATFORM_STUB();
}
auto GetProcessCRCMagicCubePiece() -> BYTE
{
MT_PLATFORM_STUB();
return mt_platform_stub_return<BYTE>();
}
@@ -0,0 +1,777 @@
#include "UserInterface/StdAfx.h"
#include "UserInterface/PythonApplication.h"
#include "UserInterface/MarkManager.h"
#include "GameLib/GameUtil.h"
#include "EterLib/Camera.h"
#include "EterBase/Timer.h"
#include "EterLib/ResourceManager.h"
#include "UserInterface/PythonNetworkStream.h"
#include "UserInterface/AccountConnector.h"
#include "UserInterface/PythonItem.h"
#include "UserInterface/PythonTextTail.h"
#include "UserInterface/PythonSkill.h"
#include "UserInterface/PythonNonPlayer.h"
#include "GameLib/ItemManager.h"
#include "EterLib/NetDevice.h"
#include "../PlatformStub.h"
#include "../EterLib/UIRenderCommands.h"
#include "../EterLib/RenderCommands3D.h"
#include "EterLib/GrpDevice.h"
#include "EterGrnLib/LODController.h"
#include "UserInterface/PythonBackground.h"
#include "UserInterface/PythonSystem.h"
#include "../ScriptLib/PythonBoot.h"
#include "ServerClock.h"
#include "../EterBase/PerfCounters.h"
#if defined(__linux__) || defined(__ANDROID__)
#include <sched.h>
#endif
// 2V0-d link surface; 2V0-f adds the application lifecycle (Create/Loop/Process/Exit) that
// prototype.RunApp() drives. The rest of the members still wait for the game slices (2V1-2V3).
//
// PORT: there is no CPythonApplication object yet (its members are the whole game: background,
// network stream, player, ...), so these functions only use the singletons PythonBoot owns
alignas(alignof(CPythonApplication)) static char s_app_storage[sizeof(CPythonApplication)] = {};
CPythonApplication* CPythonApplication::ms_pInstance = reinterpret_cast<CPythonApplication*>(s_app_storage);
extern double g_specularSpd;
void CPythonApplication::ShowWebPage(const char*, const RECT&) { MT_PLATFORM_STUB(); }
void CPythonApplication::MoveWebPage(const RECT&) { MT_PLATFORM_STUB(); }
void CPythonApplication::HideWebPage() { MT_PLATFORM_STUB(); }
bool CPythonApplication::IsWebPageMode() { MT_PLATFORM_STUB(); return false; }
void CPythonApplication::GetInfo(UINT, std::string* out) { MT_PLATFORM_STUB(); if (out) out->clear(); }
// In 40250, Loop() is: while (1) { if (IsMessage()) { if (!MessageProcess()) break; } else { if (!Process()) break; } }
// PORT: Godot owns the message pump and forwards input to the window manager between frames
// (PythonBoot::UIMouseMove & co.), so the loop here only waits for the host's next frame. It runs
// on PythonBoot's script thread; WM_QUIT is PythonBoot::AppRequestQuit.
void CPythonApplication::Loop()
{
while (PythonBoot::AppLoopWait())
{
if (!Process())
break;
}
}
// In 40250 this is PostQuitMessage(0).
void CPythonApplication::Exit() { PythonBoot::AppRequestQuit(); }
// 40250 also writes a TraceError banner first; the caller (system.py) has already logged the reason.
void CPythonApplication::Abort()
{
TraceError("============================================================================================================");
TraceError("Abort!!!!\n\n");
PythonBoot::AppRequestQuit();
}
static float MIN_FOG = 2400.0f;
void CPythonApplication::SetMinFog(float fMinFog) { MIN_FOG = fMinFog; }
// In 40250 Process() copies CTimer::GetCurrentSecond() into m_fGlobalTime right after Advance() and
// this returns it. PORT: no member to hold it; the timer only advances in Process(), so reading it
// here gives the same value.
float CPythonApplication::GetGlobalTime() { return CTimer::Instance().GetCurrentSecond(); }
// In 40250 Process() also copies CTimer::GetElapsedSecond() into m_fGlobalElapsedTime (PythonApplication.cpp:448).
// PORT: read straight from the timer, as GetGlobalTime above.
float CPythonApplication::GetGlobalElapsedTime() { return CTimer::Instance().GetElapsedSecond(); }
static bool s_isFrameSkipDisable = false;
// m_iForceSightRange (the 40250 constructor sets -1: automatic sight range).
static int s_iForceSightRange = -1;
static float s_nativeRenderFrameTime = 0.0f;
void PythonBoot::SetNativeRenderFrameTime(float milliseconds) { s_nativeRenderFrameTime = milliseconds; }
void CPythonApplication::SetFrameSkip(bool isEnable) { s_isFrameSkipDisable = !isEnable; }
// PORT: 40250 creates the Win32 window, the D3D8 device, cursors, sound, keyboard, the net device,
// fonts and the IME here. The Godot window and its canvas already exist when the host starts the
// script, so the window size is the canvas size (PythonBoot::SetUISize) rather than the width/height
// passed from metin2.cfg, and the graphic device is the recording device (RecordingDevice.h) at that
// size. Cursors, sound, keyboard and fonts are not created here yet.
bool CPythonApplication::Create(PyObject*, const char*, int, int, int)
{
unsigned width = 0, height = 0;
UIRenderGetSize(&width, &height);
if (!width || !height)
{
// appCreate returns NULL on failure; RunApp turns this into the original LogBox.
TraceError("CreateDevice: GraphicDevice create failed");
PyErr_SetString(PyExc_RuntimeError, "CREATE_DEVICE");
return false;
}
// 40250 PythonApplication.cpp:1196-1199.
extern bool GRAPHICS_CAPS_SOFTWARE_TILING;
if (!CPythonSystem::Instance().IsAutoTiling())
GRAPHICS_CAPS_SOFTWARE_TILING = CPythonSystem::Instance().IsSoftwareTiling();
// In 40250 m_grpDevice is a member created here (PythonApplication.cpp:909).
static CGraphicDevice s_grpDevice;
int iRet = s_grpDevice.Create(NULL, width, height, true, 32, 0);
switch (iRet)
{
case CGraphicDevice::CREATE_OK:
break;
case CGraphicDevice::CREATE_REFRESHRATE:
break;
case CGraphicDevice::CREATE_GET_DEVICE_CAPS:
PyErr_SetString(PyExc_RuntimeError, "GetDevCaps failed");
TraceError("CreateDevice: GetDevCaps failed");
return false;
case CGraphicDevice::CREATE_GET_DEVICE_CAPS2:
PyErr_SetString(PyExc_RuntimeError, "GetDevCaps2 failed");
TraceError("CreateDevice: GetDevCaps2 failed");
return false;
default:
// PORT: the recording device returns only the cases above; the rest is 40250's fallback.
if (iRet & CGraphicDevice::CREATE_OK)
break;
TraceError("CreateDevice: Unknown Error!");
PyErr_SetString(PyExc_RuntimeError, "UNKNOWN_ERROR");
return false;
}
// 40250 PythonApplication.cpp:1206-1220.
if (CPythonSystem::Instance().IsAutoTiling())
{
if (s_grpDevice.IsFastTNL())
{
CPythonBackground::Instance().ReserveSoftwareTilingEnable(false);
}
else
{
CPythonBackground::Instance().ReserveSoftwareTilingEnable(true);
}
}
else
{
CPythonBackground::Instance().ReserveSoftwareTilingEnable(CPythonSystem::Instance().IsSoftwareTiling());
}
// In 40250 m_netDevice is a member created here (PythonApplication.cpp:1242).
static CNetworkDevice s_netDevice;
if (!s_netDevice.Create())
{
TraceError("NetDevice::Create failed");
PyErr_SetString(PyExc_RuntimeError, "CREATE_NETWORK");
return false;
}
// 40250 PythonApplication.cpp:1250-1251.
if (!s_grpDevice.IsFastTNL())
CGrannyLODController::SetMinLODMode(true);
// 40250 m_pyItem.Create() (PythonApplication.cpp:1253): registers dropitem.mse with CEffectManager.
CPythonItem::Instance().Create();
// 40250 PythonApplication.cpp:1258-1259 (after DefaultFont_Startup).
CPythonIME::Instance().Create(GetWindowHandle());
CPythonIME::Instance().SetText("", 0);
// 40250 PythonApplication.cpp:1260.
CPythonTextTail::Instance().Initialize();
// 40250 PythonApplication.cpp:1262-1263.
// Light Manager
m_LightManager.Initialize();
if (IsNativeTerrainRenderEnabled())
{
const bool use_hardware_cursor = PythonBoot::HostHardwareCursorEnabled() || PythonBoot::TouchInput();
if (CPythonSystem::InstancePtr() && CPythonSystem::Instance().GetConfig())
CPythonSystem::Instance().GetConfig()->is_software_cursor = !use_hardware_cursor;
SetCursorMode(use_hardware_cursor ? CURSOR_MODE_HARDWARE : CURSOR_MODE_SOFTWARE);
CGrannyMaterial::CreateSphereMap(0, "d:/ymir work/special/spheremap.jpg");
CGrannyMaterial::CreateSphereMap(1, "d:/ymir work/special/spheremap01.jpg");
}
return true;
}
// 40250 PythonApplication.cpp:105
void CPythonApplication::GetMousePosition(POINT* ppt)
{
CMSApplication::GetMousePosition(ppt);
}
// 40250 PythonApplication.cpp:168, the !PERF_CHECKER_RENDER_GAME branch (the profiling copy below it
// only adds timers). game.GameWindow.OnRender calls it every frame.
// PORT: the members are reached through their singletons (see the note at the top of the file).
void CPythonApplication::RenderGame()
{
MtPerf::CScope kPerf(MtPerf::SECTION_RENDER_GAME);
float fAspect=UI::CWindowManager::Instance().GetAspect();
float fFarClip=CPythonBackground::Instance().GetFarClip();
CPythonGraphic::Instance().SetPerspective(30.0f, fAspect, 100.0, fFarClip);
CCullingManager::Instance().Process();
CPythonCharacterManager::Instance().Deform();
CEffectManager::Instance().Update();
CPythonBackground::Instance().RenderCharacterShadowToTexture();
CPythonGraphic::Instance().SetGameRenderState();
CPythonGraphic::Instance().PushState();
{
long lx, ly;
UI::CWindowManager::Instance().GetMousePosition(lx, ly);
// PORT: window coordinates -> the screen coordinates of the full-width 3D view.
lx += UI::CWindowManager::Instance().GetScreenOffsetX();
CPythonGraphic::Instance().SetCursorPosition(lx, ly);
}
CPythonBackground::Instance().RenderSky();
CPythonBackground::Instance().RenderBeforeLensFlare();
CPythonBackground::Instance().RenderCloud();
CPythonBackground::Instance().BeginEnvironment();
CPythonBackground::Instance().Render();
CPythonBackground::Instance().SetCharacterDirLight();
CPythonCharacterManager::Instance().Render();
CPythonBackground::Instance().SetBackgroundDirLight();
CPythonBackground::Instance().RenderWater();
CPythonBackground::Instance().RenderSnow();
CPythonBackground::Instance().RenderEffect();
CPythonBackground::Instance().EndEnvironment();
CEffectManager::Instance().Render();
CPythonItem::Instance().Render();
CFlyingManager::Instance().Render();
CPythonBackground::Instance().BeginEnvironment();
CPythonBackground::Instance().RenderPCBlocker();
CPythonBackground::Instance().EndEnvironment();
CPythonBackground::Instance().RenderAfterLensFlare();
}
// 40250 PythonApplication.cpp:321 without the PERF_CHECKER_RENDER_GAME timers. game.GameWindow.OnUpdate
// calls it every frame. PORT: members through their singletons, as in RenderGame.
void CPythonApplication::UpdateGame()
{
MtPerf::CScope kPerf(MtPerf::SECTION_UPDATE_GAME);
POINT ptMouse;
GetMousePosition(&ptMouse);
CGraphicTextInstance::Hyperlink_UpdateMousePos(ptMouse.x, ptMouse.y);
//!@# Alt+Tab 중 SetTransfor 에서 튕김 현상 해결을 위해 - [levites]
//if (m_isActivateWnd)
{
CScreen s;
float fAspect = UI::CWindowManager::Instance().GetAspect();
float fFarClip = CPythonBackground::Instance().GetFarClip();
s.SetPerspective(30.0f,fAspect, 100.0f, fFarClip);
s.BuildViewFrustum();
}
TPixelPosition kPPosMainActor;
CPythonPlayer::Instance().NEW_GetMainActorPosition(&kPPosMainActor);
CPythonBackground::Instance().Update(kPPosMainActor.x, kPPosMainActor.y, kPPosMainActor.z);
CGameEventManager::Instance().SetCenterPosition(kPPosMainActor.x, kPPosMainActor.y, kPPosMainActor.z);
CGameEventManager::Instance().Update();
CPythonCharacterManager::Instance().Update();
CEffectManager::Instance().UpdateSound();
CFlyingManager::Instance().Update();
CPythonItem::Instance().Update(ptMouse);
CPythonPlayer::Instance().Update();
// NOTE : Update 에서 위치 값이 바뀌므로 다시 얻어 옵니다 - [levites]
// 이 부분 때문에 메인 케릭터의 Sound가 이전 위치에서 플레이 되는 현상이 있었음.
CPythonPlayer::Instance().NEW_GetMainActorPosition(&kPPosMainActor);
SetCenterPosition(kPPosMainActor.x, kPPosMainActor.y, kPPosMainActor.z);
}
// 40250 PythonApplication.cpp:399. Kept in order: timer, network (2V1), input polling (Godot pushes
// input instead), camera (2V3), resource GC, mouse/UI update, then the render block's interface pass.
// PORT: the frame-skip bookkeeping and the game render pass are left out; the Godot frame clock
// decides when this runs, and RenderGame belongs to 2V3.
// PORT: telemetry for --perf-log (platform/EterBase/PerfCounters.h); 40250 has no counterpart.
static void __PerfSampleWorld()
{
if (!MtPerf::Enabled())
return;
MtPerf::SCounters& rkCounters = MtPerf::Counters();
CPythonCharacterManager& rkChrMgr = CPythonCharacterManager::Instance();
int iActors = 0;
for (CPythonCharacterManager::CharacterIterator i = rkChrMgr.CharacterInstanceBegin(); i != rkChrMgr.CharacterInstanceEnd(); ++i)
++iActors;
rkCounters.actorCount = iActors;
#if defined(__linux__) || defined(__ANDROID__)
rkCounters.scriptCpu = sched_getcpu();
#endif
}
bool CPythonApplication::Process()
{
MtPerf::CScope kPerfProcess(MtPerf::SECTION_PROCESS);
__PerfSampleWorld();
ELTimer_SetFrameMSec();
CTimer& rkTimer=CTimer::Instance();
rkTimer.Advance();
// Network I/O
{
MtPerf::CScope kPerf(MtPerf::SECTION_NETWORK);
CPythonNetworkStream::Instance().Process();
// PORT: m_kGuildMarkUploader/m_kGuildMarkDownloader.Process() follow here in 40250; the guild mark
// transfer is not ported yet (GuildMarkDownloader.cpp/GuildMarkUploader.cpp).
CAccountConnector::Instance().Process();
}
{
MtPerf::CScope kPerf(MtPerf::SECTION_CAMERA);
//!@# Alt+Tab 중 SetTransfor 에서 튕김 현상 해결을 위해 - [levites]
//if (m_isActivateWnd)
__UpdateCamera();
CResourceManager::Instance().Update();
OnCameraUpdate();
if (IsNativeTerrainRenderEnabled())
OnMouseUpdate();
}
{
MtPerf::CScope kPerf(MtPerf::SECTION_UI_UPDATE);
OnUIUpdate();
}
if (IsNativeTerrainRenderEnabled())
CGrannyMaterial::TranslateSpecularMatrix(g_specularSpd, g_specularSpd, 0.0f);
// PORT: the render block without the lost-device restore, ClearDepthBuffer and Show (Godot clears
// and presents the frame), and without the !IsActive() SkipRenderBuffering(3000): the host has no
// Win32 activation (CMSWindow::IsActive is a stub). The frame's UI and 3D command lists restart here.
// 40250 PythonApplication.cpp:681.
DWORD dwRenderStartTime = ELTimer_GetMSec();
{
MtPerf::CScope kPerf(MtPerf::SECTION_RENDER_BEGIN);
CCullingManager::Instance().Update();
UIRenderBeginFrame();
Render3DBeginFrame();
}
CPythonGraphic& rkGraphic = CPythonGraphic::Instance();
if (rkGraphic.Begin())
{
rkGraphic.SetInterfaceRenderState();
{
MtPerf::CScope kPerf(MtPerf::SECTION_UI_RENDER);
OnUIRender();
if (IsNativeTerrainRenderEnabled())
{
rkGraphic.SetInterfaceRenderState();
unsigned cw = 0, ch = 0;
UIRenderGetSize(&cw, &ch);
UIRenderSetClip(0.0f, 0.0f, float(cw), float(ch));
OnMouseRender();
}
}
rkGraphic.End();
// 40250 PythonApplication.cpp:741-842 (render time, face count, automatic sight range), minus the
// per-second FPS/face counters and the windowed dwBufRenderTime rounding, whose result 40250 never
// uses (its Sleep is commented out).
DWORD dwRenderEndTime = ELTimer_GetMSec();
static DWORD s_dwRenderCheckTime = dwRenderEndTime;
static DWORD s_dwRenderRangeTime = 0;
static DWORD s_dwRenderRangeFrame = 0;
// The native host completes Vulkan work after this command-recording pass.
// Use its last completed frame, including presentation, for automatic sight range.
m_dwCurRenderTime = s_nativeRenderFrameTime > 0.0f
? static_cast<DWORD>(s_nativeRenderFrameTime + 0.5f)
: dwRenderEndTime - dwRenderStartTime;
s_dwRenderRangeTime += m_dwCurRenderTime;
++s_dwRenderRangeFrame;
if (dwRenderEndTime-s_dwRenderCheckTime>1000)
{
m_fAveRenderTime=float(double(s_dwRenderRangeTime)/double(s_dwRenderRangeFrame));
s_dwRenderCheckTime=ELTimer_GetMSec();
s_dwRenderRangeTime=0;
s_dwRenderRangeFrame=0;
}
DWORD dwCurFaceCount=rkGraphic.GetFaceCount();
rkGraphic.ResetFaceCount();
if (dwCurFaceCount > 5000)
{
// 프레임 완충 처리
if (dwRenderEndTime > m_dwBufSleepSkipTime)
{
static float s_fBufRenderTime = 0.0f;
float fCurRenderTime = m_dwCurRenderTime;
if (fCurRenderTime > s_fBufRenderTime)
{
float fRatio = fMAX(0.5f, (fCurRenderTime - s_fBufRenderTime) / 30.0f);
s_fBufRenderTime = (s_fBufRenderTime * (100.0f - fRatio) + (fCurRenderTime + 5) * fRatio) / 100.0f;
}
else
{
float fRatio = 0.5f;
s_fBufRenderTime = (s_fBufRenderTime * (100.0f - fRatio) + fCurRenderTime * fRatio) / 100.0f;
}
// 한계치를 정한다
if (s_fBufRenderTime > 100.0f)
s_fBufRenderTime = 100.0f;
m_fAveRenderTime=s_fBufRenderTime;
}
m_dwFaceAccCount += dwCurFaceCount;
m_dwFaceAccTime += m_dwCurRenderTime;
// PORT: recording a frame can take under 1 ms, so the integer division is guarded (40250's
// D3D frame never took 0 ms).
if (m_dwFaceAccTime)
m_fFaceSpd=(m_dwFaceAccCount/m_dwFaceAccTime);
// 거리 자동 조절
if (-1 == s_iForceSightRange)
{
static float s_fAveRenderTime = 16.0f;
float fRatio=0.3f;
s_fAveRenderTime=(s_fAveRenderTime*(100.0f-fRatio)+max(16.0f, m_dwCurRenderTime)*fRatio)/100.0f;
float fFar=25600.0f;
float fNear=MIN_FOG;
double dbAvePow=double(1000.0f/s_fAveRenderTime);
double dbMaxPow=60.0;
float fDistance=max(fNear+(fFar-fNear)*(dbAvePow)/dbMaxPow, fNear);
CPythonBackground::Instance().SetViewDistanceSet(0, fDistance);
}
// 거리 강제 설정시
else
{
CPythonBackground::Instance().SetViewDistanceSet(0, float(s_iForceSightRange));
}
}
else
{
// 10000 폴리곤 보다 적을때는 가장 멀리 보이게 한다
CPythonBackground::Instance().SetViewDistanceSet(0, 25600.0f);
}
}
return true;
}
// 40250 PythonApplicationCursor.cpp. PORT: the members live here until the application object exists
// (initial values from the constructor and CreateCursors); the host draws no hardware cursor, so every
// shape in [0, CURSOR_COUNT) counts as loaded in place of m_CursorHandleMap.
PyObject* s_poMouseHandler = NULL; // m_poMouseHandler
namespace
{
int s_iCursorNum = CPythonApplication::CURSOR_SHAPE_NORMAL; // m_iCursorNum
int s_iContinuousCursorNum = CPythonApplication::CURSOR_SHAPE_NORMAL; // m_iContinuousCursorNum
BOOL s_bCursorVisible = TRUE; // m_bCursorVisible
bool s_bLiarCursorOn = false; // m_bLiarCursorOn
int s_iCursorMode = CPythonApplication::CURSOR_MODE_HARDWARE; // m_iCursorMode
}
void CPythonApplication::SetCursorVisible(BOOL bFlag, bool bLiarCursorOn)
{
s_bCursorVisible = bFlag;
// PORT: a touch screen has no cursor, not even the stand-in 40250 draws while the real one is hidden.
s_bLiarCursorOn = bLiarCursorOn && !PythonBoot::TouchInput();
// PORT: 40250 also counts ShowCursor up or down in hardware mode; the host has no OS cursor to hide.
}
BOOL CPythonApplication::GetCursorVisible()
{
return s_bCursorVisible;
}
bool CPythonApplication::GetLiarCursorOn()
{
return s_bLiarCursorOn;
}
int CPythonApplication::GetCursorMode()
{
return s_iCursorMode;
}
int CPythonApplication::GetCursorNum()
{
return s_iCursorNum;
}
BOOL CPythonApplication::__IsContinuousChangeTypeCursor(int iCursorNum)
{
switch (iCursorNum)
{
case CURSOR_SHAPE_NORMAL:
case CURSOR_SHAPE_ATTACK:
case CURSOR_SHAPE_TARGET:
case CURSOR_SHAPE_MAGIC:
case CURSOR_SHAPE_BUY:
case CURSOR_SHAPE_SELL:
return TRUE;
break;
}
return FALSE;
}
BOOL CPythonApplication::SetCursorNum(int iCursorNum)
{
if (CURSOR_SHAPE_NORMAL == iCursorNum)
{
if (!__IsContinuousChangeTypeCursor(s_iCursorNum))
{
iCursorNum = s_iContinuousCursorNum;
}
}
else
{
if (__IsContinuousChangeTypeCursor(s_iCursorNum))
{
s_iContinuousCursorNum = s_iCursorNum;
}
}
if (CURSOR_MODE_HARDWARE == s_iCursorMode)
{
// PORT: m_CursorHandleMap.find(iCursorNum) and SetCursor(hCursor).
if (iCursorNum < 0 || iCursorNum >= CURSOR_COUNT)
return FALSE;
}
s_iCursorNum = iCursorNum;
PyCallClassMemberFunc(s_poMouseHandler, "ChangeCursor", Py_BuildValue("(i)", s_iCursorNum));
return TRUE;
}
void CPythonApplication::SetCursorMode(int iMode)
{
switch (iMode)
{
case CURSOR_MODE_HARDWARE:
s_iCursorMode = CURSOR_MODE_HARDWARE;
break;
case CURSOR_MODE_SOFTWARE:
s_iCursorMode = CURSOR_MODE_SOFTWARE;
break;
}
}
// 40250 PythonApplication.cpp:871.
void CPythonApplication::SetMouseHandler(PyObject* poMouseHandler)
{
s_poMouseHandler = poMouseHandler;
}
void CPythonApplication::SetGlobalCenterPosition(LONG x, LONG y)
{
// 40250 PythonApplication.cpp:1284: the background owns the global-to-local map offset.
CPythonBackground& background = CPythonBackground::Instance();
background.GlobalPositionToLocalPosition(x, y);
SetCenterPosition(x, y, background.GetHeight(x, y));
}
void CPythonApplication::SetFPS(int) {}
namespace {
DWORD s_server_start_msec = 0;
time_t s_server_time = 0;
time_t s_local_start_time = 0;
}
void SetPlatformServerTime(time_t server_time)
{
s_server_start_msec = ELTimer_GetMSec();
s_server_time = server_time;
s_local_start_time = time(nullptr);
}
time_t GetPlatformServerTime()
{
return static_cast<time_t>(ELTimer_GetMSec() - s_server_start_msec) + s_server_time;
}
time_t GetPlatformServerTimeStamp()
{
return (time(nullptr) - s_local_start_time) + s_server_time;
}
void CPythonApplication::SetServerTime(time_t server_time) { SetPlatformServerTime(server_time); }
time_t CPythonApplication::GetServerTime() { return GetPlatformServerTime(); }
time_t CPythonApplication::GetServerTimeStamp() { return GetPlatformServerTimeStamp(); }
void CPythonApplication::SetConnectData(const char*, int) { MT_PLATFORM_STUB(); }
void CPythonApplication::GetConnectData(std::string& ip, int& port) { MT_PLATFORM_STUB(); ip.clear(); port = 0; }
// 40250 PythonApplication.cpp:1377.
void CPythonApplication::SetForceSightRange(int iRange)
{
s_iForceSightRange = iRange;
}
int CPythonApplication::CheckDeviceState()
{
return DEVICE_STATE_OK;
}
bool CPythonApplication::CreateDevice(int width, int height, int Windowed, int bit, int frequency)
{
static CGraphicDevice s_grpDevice;
return s_grpDevice.Create(NULL, width, height, Windowed ? true : false, bit, frequency) == CGraphicDevice::CREATE_OK;
}
void CPythonApplication::NotifyHack(const char* c_szFormat, ...)
{
char szBuf[1024];
va_list args;
va_start(args, c_szFormat);
vsnprintf(szBuf, sizeof(szBuf), c_szFormat, args);
va_end(args);
CPythonNetworkStream::Instance().NotifyHack(szBuf);
}
// 40250 PythonApplication.cpp:394
void CPythonApplication::SkipRenderBuffering(DWORD dwSleepMSec)
{
m_dwBufSleepSkipTime=ELTimer_GetMSec()+dwSleepMSec;
}
void CPythonApplication::UpdateClientRect()
{
unsigned w = 0, h = 0;
UIRenderGetSize(&w, &h);
UI::CWindowManager::Instance().SetResolution(w, h);
}
int CPythonApplication::GetWidth()
{
unsigned w = 0, h = 0;
UIRenderGetSize(&w, &h);
return (int)w;
}
int CPythonApplication::GetHeight()
{
unsigned w = 0, h = 0;
UIRenderGetSize(&w, &h);
return (int)h;
}
void CPythonApplication::Clear()
{
CPythonSystem::Instance().Clear();
}
void CPythonApplication::Destroy()
{
}
void CMovieMan::PlayLogo(const char*) { MT_PLATFORM_STUB(); }
BOOL PERF_CHECKER_RENDER_GAME = FALSE;
double g_specularSpd = 0;
// 40250 UserInterface/PythonApplication.cpp, verbatim.
// SUPPORT_NEW_KOREA_SERVER
bool LoadLocaleData(const char* localePath)
{
NANOBEGIN
CPythonNonPlayer& rkNPCMgr = CPythonNonPlayer::Instance();
CItemManager& rkItemMgr = CItemManager::Instance();
CPythonSkill& rkSkillMgr = CPythonSkill::Instance();
CPythonNetworkStream& rkNetStream = CPythonNetworkStream::Instance();
char szItemList[256];
char szItemProto[256];
char szItemDesc[256];
char szMobProto[256];
char szSkillDescFileName[256];
char szSkillTableFileName[256];
char szInsultList[256];
snprintf(szItemList, sizeof(szItemList) , "%s/item_list.txt", localePath);
snprintf(szItemProto, sizeof(szItemProto), "%s/item_proto", localePath);
snprintf(szItemDesc, sizeof(szItemDesc), "%s/itemdesc.txt", localePath);
snprintf(szMobProto, sizeof(szMobProto), "%s/mob_proto", localePath);
snprintf(szSkillDescFileName, sizeof(szSkillDescFileName), "%s/SkillDesc.txt", localePath);
snprintf(szSkillTableFileName, sizeof(szSkillTableFileName), "%s/SkillTable.txt", localePath);
snprintf(szInsultList, sizeof(szInsultList), "%s/insult.txt", localePath);
rkNPCMgr.Destroy();
rkItemMgr.Destroy();
rkSkillMgr.Destroy();
if (!rkItemMgr.LoadItemList(szItemList))
{
TraceError("LoadLocaleData - LoadItemList(%s) Error", szItemList);
}
if (!rkItemMgr.LoadItemTable(szItemProto))
{
TraceError("LoadLocaleData - LoadItemProto(%s) Error", szItemProto);
return false;
}
if (!rkItemMgr.LoadItemDesc(szItemDesc))
{
Tracenf("LoadLocaleData - LoadItemDesc(%s) Error", szItemDesc);
}
if (!rkNPCMgr.LoadNonPlayerData(szMobProto))
{
TraceError("LoadLocaleData - LoadMobProto(%s) Error", szMobProto);
return false;
}
if (!rkSkillMgr.RegisterSkillDesc(szSkillDescFileName))
{
TraceError("LoadLocaleData - RegisterSkillDesc(%s) Error", szMobProto);
return false;
}
if (!rkSkillMgr.RegisterSkillTable(szSkillTableFileName))
{
TraceError("LoadLocaleData - RegisterSkillTable(%s) Error", szMobProto);
return false;
}
if (!rkNetStream.LoadInsultList(szInsultList))
{
Tracenf("CPythonApplication - CPythonNetworkStream::LoadInsultList(%s)", szInsultList);
}
if (LocaleService_IsYMIR())
{
char szEmpireTextConvFile[256];
for (DWORD dwEmpireID=1; dwEmpireID<=3; ++dwEmpireID)
{
sprintf(szEmpireTextConvFile, "%s/lang%d.cvt", localePath, dwEmpireID);
if (!rkNetStream.LoadConvertTable(dwEmpireID, szEmpireTextConvFile))
{
TraceError("LoadLocaleData - CPythonNetworkStream::LoadConvertTable(%d, %s) FAILURE", dwEmpireID, szEmpireTextConvFile);
}
}
}
NANOEND
return true;
}
@@ -0,0 +1,478 @@
// 40250 UserInterface/PythonApplicationCamera.cpp plus the camera members' other functions in
// PythonApplication.cpp (SetCenterPosition, EnableSpecialCameraMode, SetCameraSpeed).
// PORT: there is no CPythonApplication object (see PythonApplication.cpp), so the camera members live
// in s_app below with 40250's names and constructor values, and m_pyGraphic is CPythonGraphic::Instance().
#include "UserInterface/StdAfx.h"
#include "UserInterface/PythonApplication.h"
#include "EterBase/Timer.h"
#include "EterLib/Camera.h"
#include "EterLib/Util.h"
#include "EterLib/TextFileLoader.h"
// 40250 PythonApplication.cpp:28-30
float c_fDefaultCameraRotateSpeed = 1.5f;
float c_fDefaultCameraPitchSpeed = 1.5f;
float c_fDefaultCameraZoomSpeed = 0.05f;
namespace
{
struct ApplicationCamera
{
D3DXVECTOR3 m_v3CenterPosition{0.0f, 0.0f, 0.0f};
CPythonApplication::SCameraSetting m_DefaultCameraSetting;
CPythonApplication::SCameraSetting m_kEventCameraSetting;
int m_iCameraMode = CPythonApplication::CAMERA_MODE_NORMAL;
float m_fBlendCameraStartTime = 0.0f;
float m_fBlendCameraBlendTime = 0.0f;
CPythonApplication::SCameraSetting m_kEndBlendCameraSetting;
float m_fRotationSpeed = 0.0f;
float m_fPitchSpeed = 0.0f;
float m_fZoomSpeed = 0.0f;
float m_fCameraRotateSpeed = c_fDefaultCameraRotateSpeed;
float m_fCameraPitchSpeed = c_fDefaultCameraPitchSpeed;
float m_fCameraZoomSpeed = c_fDefaultCameraZoomSpeed;
CPythonApplication::SCameraPos m_kCmrPos;
CPythonApplication::SCameraSpeed m_kCmrSpd;
BOOL m_isSpecialCameraMode = FALSE;
// The constructor's CCameraManager::Instance().AddCamera(EVENT_CAMERA_NUMBER), on first use.
ApplicationCamera() { CCameraManager::Instance().AddCamera(CPythonApplication::EVENT_CAMERA_NUMBER); }
};
ApplicationCamera& app()
{
static ApplicationCamera s_app;
return s_app;
}
}
float BlendValueByLinear(float fElapsedTime, float fDuration, float fBeginValue, float fEndValue)
{
if (fElapsedTime >= fDuration)
return fEndValue;
return (fEndValue - fBeginValue) * (fElapsedTime / fDuration) + fBeginValue;
}
void CPythonApplication::__UpdateCamera()
{
ApplicationCamera& s_app = app();
//////////////////////
// Camera Setting
CCamera * pMainCamera = CCameraManager::Instance().GetCurrentCamera();
if (!pMainCamera)
return;
if (CAMERA_MODE_BLEND == s_app.m_iCameraMode)
{
float fcurTime = CTimer::Instance().GetCurrentSecond();
float fElapsedTime = fcurTime - s_app.m_fBlendCameraStartTime;
float fxCenter = BlendValueByLinear(fElapsedTime, s_app.m_fBlendCameraBlendTime, s_app.m_kEventCameraSetting.v3CenterPosition.x, s_app.m_kEndBlendCameraSetting.v3CenterPosition.x);
float fyCenter = BlendValueByLinear(fElapsedTime, s_app.m_fBlendCameraBlendTime, s_app.m_kEventCameraSetting.v3CenterPosition.y, s_app.m_kEndBlendCameraSetting.v3CenterPosition.y);
float fzCenter = BlendValueByLinear(fElapsedTime, s_app.m_fBlendCameraBlendTime, s_app.m_kEventCameraSetting.v3CenterPosition.z, s_app.m_kEndBlendCameraSetting.v3CenterPosition.z);
float fDistance = BlendValueByLinear(fElapsedTime, s_app.m_fBlendCameraBlendTime, s_app.m_kEventCameraSetting.fZoom, s_app.m_kEndBlendCameraSetting.fZoom);
float fPitch = BlendValueByLinear(fElapsedTime, s_app.m_fBlendCameraBlendTime, s_app.m_kEventCameraSetting.fPitch, s_app.m_kEndBlendCameraSetting.fPitch);
float fRotation = BlendValueByLinear(fElapsedTime, s_app.m_fBlendCameraBlendTime, s_app.m_kEventCameraSetting.fRotation, s_app.m_kEndBlendCameraSetting.fRotation);
float fUpDir = BlendValueByLinear(fElapsedTime, s_app.m_fBlendCameraBlendTime, s_app.m_kEventCameraSetting.kCmrPos.m_fUpDir, s_app.m_kEndBlendCameraSetting.kCmrPos.m_fUpDir);
float fViewDir = BlendValueByLinear(fElapsedTime, s_app.m_fBlendCameraBlendTime, s_app.m_kEventCameraSetting.kCmrPos.m_fViewDir, s_app.m_kEndBlendCameraSetting.kCmrPos.m_fViewDir);
float fCrossDir = BlendValueByLinear(fElapsedTime, s_app.m_fBlendCameraBlendTime, s_app.m_kEventCameraSetting.kCmrPos.m_fCrossDir, s_app.m_kEndBlendCameraSetting.kCmrPos.m_fCrossDir);
// Temporary. Have to fix that this work in camera class. - [levites]
pMainCamera->Unlock();
CPythonGraphic::Instance().SetPositionCamera(fxCenter, fyCenter, fzCenter, fDistance, fPitch, fRotation);
pMainCamera->MoveVertical(fUpDir);
pMainCamera->MoveFront(fViewDir);
pMainCamera->MoveAlongCross(fCrossDir);
pMainCamera->Lock();
}
else if (CAMERA_MODE_STAND == s_app.m_iCameraMode)
{
float fDistance, fPitch, fRotation, fHeight;
GetCamera(&fDistance, &fPitch, &fRotation, &fHeight);
CPythonGraphic::Instance().SetPositionCamera(s_app.m_kEventCameraSetting.v3CenterPosition.x,
s_app.m_kEventCameraSetting.v3CenterPosition.y,
s_app.m_kEventCameraSetting.v3CenterPosition.z + pMainCamera->GetTargetHeight(),
fDistance, fPitch, fRotation);
}
else if (CAMERA_MODE_NORMAL == s_app.m_iCameraMode)
{
float fDistance, fPitch, fRotation, fHeight;
GetCamera(&fDistance, &fPitch, &fRotation, &fHeight);
CPythonGraphic::Instance().SetPositionCamera(s_app.m_v3CenterPosition.x, s_app.m_v3CenterPosition.y, s_app.m_v3CenterPosition.z + pMainCamera->GetTargetHeight(), fDistance, fPitch, fRotation);
}
if (0.0f != s_app.m_fRotationSpeed)
pMainCamera->Roll(s_app.m_fRotationSpeed);
if (0.0f != s_app.m_fPitchSpeed)
pMainCamera->Pitch(s_app.m_fPitchSpeed);
if (0.0f != s_app.m_fZoomSpeed)
pMainCamera->Zoom(s_app.m_fZoomSpeed);
if (0.0f !=s_app.m_kCmrSpd.m_fViewDir)
s_app.m_kCmrPos.m_fViewDir+=s_app.m_kCmrSpd.m_fViewDir;
if (0.0f !=s_app.m_kCmrSpd.m_fCrossDir)
s_app.m_kCmrPos.m_fCrossDir+=s_app.m_kCmrSpd.m_fCrossDir;
if (0.0f !=s_app.m_kCmrSpd.m_fUpDir)
s_app.m_kCmrPos.m_fUpDir+=s_app.m_kCmrSpd.m_fUpDir;
if (0.0f != s_app.m_kCmrPos.m_fViewDir)
pMainCamera->MoveFront(s_app.m_kCmrPos.m_fViewDir);
if (0.0f != s_app.m_kCmrPos.m_fCrossDir)
pMainCamera->MoveAlongCross(s_app.m_kCmrPos.m_fCrossDir);
if (0.0f != s_app.m_kCmrPos.m_fUpDir)
pMainCamera->MoveVertical(s_app.m_kCmrPos.m_fUpDir);
// PORT: SkipRenderBuffering while dragging and the listener update of m_SoundManager follow here in
// 40250; there is no render buffering and sound is not ported (2V4).
}
void CPythonApplication::SetViewDirCameraSpeed(float fSpeed)
{
if (IsLockCurrentCamera())
return;
app().m_kCmrSpd.m_fViewDir=fSpeed;
}
void CPythonApplication::SetCrossDirCameraSpeed(float fSpeed)
{
if (IsLockCurrentCamera())
return;
app().m_kCmrSpd.m_fCrossDir=fSpeed;
}
void CPythonApplication::SetUpDirCameraSpeed(float fSpeed)
{
if (IsLockCurrentCamera())
return;
app().m_kCmrSpd.m_fUpDir=fSpeed;
}
void CPythonApplication::SetCamera(float Distance, float Pitch, float Rotation, float fDestinationHeight)
{
if (IsLockCurrentCamera())
return;
CCamera * pCurrentCamera = CCameraManager::Instance().GetCurrentCamera();
if (!pCurrentCamera)
return;
D3DXVECTOR3 v3Target = pCurrentCamera->GetTarget();
CPythonGraphic::Instance().SetPositionCamera(v3Target.x, v3Target.y, v3Target.z, Distance, Pitch, Rotation);
CCamera * pMainCamera = CCameraManager::Instance().GetCurrentCamera();
if (pMainCamera)
pMainCamera->SetTargetHeight(fDestinationHeight);
}
void CPythonApplication::GetCamera(float * Distance, float * Pitch, float * Rotation, float * DestinationHeight)
{
CCamera * pCurrentCamera = CCameraManager::Instance().GetCurrentCamera();
*Distance = pCurrentCamera->GetDistance();
*Pitch = pCurrentCamera->GetPitch();
*Rotation = pCurrentCamera->GetRoll();
*DestinationHeight = pCurrentCamera->GetTarget().z;
}
void CPythonApplication::RotateCamera(int iDirection)
{
if (IsLockCurrentCamera())
return;
float fDegree = app().m_fCameraRotateSpeed * float(iDirection);
app().m_fRotationSpeed = fDegree;
}
void CPythonApplication::PitchCamera(int iDirection)
{
if (IsLockCurrentCamera())
return;
float fDegree = app().m_fCameraPitchSpeed * float(iDirection);
app().m_fPitchSpeed = fDegree;
}
void CPythonApplication::ZoomCamera(int iDirection)
{
if (IsLockCurrentCamera())
return;
float fRatio = 1.0f + app().m_fCameraZoomSpeed * float(iDirection);
app().m_fZoomSpeed = fRatio;
}
// PORT: in special camera mode 40250 checks GetKeyState(VK_SCROLL) & 1 (Scroll Lock on) to move the
// camera instead; the platform has no Scroll Lock state, so it is always off.
void CPythonApplication::MovieRotateCamera(int iDirection)
{
if (IsLockCurrentCamera())
return;
float fDegree = app().m_fCameraRotateSpeed * float(iDirection);
app().m_fRotationSpeed = fDegree;
}
void CPythonApplication::MoviePitchCamera(int iDirection)
{
if (IsLockCurrentCamera())
return;
float fDegree = app().m_fCameraPitchSpeed * float(iDirection);
app().m_fPitchSpeed = fDegree;
}
void CPythonApplication::MovieZoomCamera(int iDirection)
{
if (IsLockCurrentCamera())
return;
float fRatio = 1.0f + app().m_fCameraZoomSpeed * float(iDirection);
app().m_fZoomSpeed = fRatio;
}
void CPythonApplication::MovieResetCamera()
{
if (IsLockCurrentCamera())
return;
ApplicationCamera& s_app = app();
if (s_app.m_isSpecialCameraMode)
{
SetCrossDirCameraSpeed(0.0f);
SetViewDirCameraSpeed(0.0f);
SetUpDirCameraSpeed(0.0f);
s_app.m_kCmrPos.m_fViewDir = 0;
s_app.m_kCmrPos.m_fCrossDir = 0;
s_app.m_kCmrPos.m_fUpDir = 0;
}
}
float CPythonApplication::GetRotation()
{
return CCameraManager::Instance().GetCurrentCamera()->GetRoll();
}
float CPythonApplication::GetPitch()
{
return CCameraManager::Instance().GetCurrentCamera()->GetPitch();
}
bool CPythonApplication::IsLockCurrentCamera()
{
CCamera * pCamera = CCameraManager::Instance().GetCurrentCamera();
if (!pCamera)
return false;
return pCamera->IsLock();
}
void CPythonApplication::SetEventCamera(const SCameraSetting & c_rCameraSetting)
{
ApplicationCamera& s_app = app();
if (CCameraManager::DEFAULT_PERSPECTIVE_CAMERA == CCameraManager::Instance().GetCurrentCameraNum())
{
GetCameraSetting(&s_app.m_DefaultCameraSetting);
}
/////
CCameraManager::Instance().SetCurrentCamera(EVENT_CAMERA_NUMBER);
CCamera * pCamera = CCameraManager::Instance().GetCurrentCamera();
if (!pCamera)
return;
SetCameraSetting(c_rCameraSetting);
s_app.m_kEventCameraSetting = c_rCameraSetting;
s_app.m_iCameraMode = CAMERA_MODE_STAND;
}
void CPythonApplication::BlendEventCamera(const SCameraSetting & c_rCameraSetting, float fBlendTime)
{
ApplicationCamera& s_app = app();
s_app.m_iCameraMode = CAMERA_MODE_BLEND;
s_app.m_fBlendCameraStartTime = CTimer::Instance().GetCurrentSecond();
s_app.m_fBlendCameraBlendTime = fBlendTime;
s_app.m_kEndBlendCameraSetting = c_rCameraSetting;
CCamera * pCamera = CCameraManager::Instance().GetCurrentCamera();
if (pCamera)
pCamera->Lock();
}
void CPythonApplication::SetDefaultCamera()
{
ApplicationCamera& s_app = app();
s_app.m_iCameraMode = CAMERA_MODE_NORMAL;
s_app.m_fBlendCameraStartTime = 0.0f;
s_app.m_fBlendCameraBlendTime = 0.0f;
/////
CCamera * pCamera = CCameraManager::Instance().GetCurrentCamera();
if (pCamera)
pCamera->Unlock();
if (CCameraManager::DEFAULT_PERSPECTIVE_CAMERA != CCameraManager::Instance().GetCurrentCameraNum())
{
CCameraManager::Instance().SetCurrentCamera(CCameraManager::DEFAULT_PERSPECTIVE_CAMERA);
SetCameraSetting(s_app.m_DefaultCameraSetting);
}
}
void CPythonApplication::SetCameraSetting(const SCameraSetting & c_rCameraSetting)
{
CCamera * pCamera = CCameraManager::Instance().GetCurrentCamera();
if (!pCamera)
return;
CPythonGraphic::Instance().SetPositionCamera( c_rCameraSetting.v3CenterPosition.x,
c_rCameraSetting.v3CenterPosition.y,
c_rCameraSetting.v3CenterPosition.z,
c_rCameraSetting.fZoom,
c_rCameraSetting.fPitch,
c_rCameraSetting.fRotation);
if (0.0f != c_rCameraSetting.kCmrPos.m_fViewDir)
pCamera->MoveFront(c_rCameraSetting.kCmrPos.m_fViewDir);
if (0.0f != c_rCameraSetting.kCmrPos.m_fCrossDir)
pCamera->MoveAlongCross(c_rCameraSetting.kCmrPos.m_fCrossDir);
if (0.0f != c_rCameraSetting.kCmrPos.m_fUpDir)
pCamera->MoveVertical(c_rCameraSetting.kCmrPos.m_fUpDir);
ApplicationCamera& s_app = app();
s_app.m_kCmrPos.m_fUpDir = 0.0f;
s_app.m_kCmrPos.m_fViewDir = 0.0f;
s_app.m_kCmrPos.m_fCrossDir = 0.0f;
s_app.m_kCmrSpd.m_fUpDir = 0.0f;
s_app.m_kCmrSpd.m_fViewDir = 0.0f;
s_app.m_kCmrSpd.m_fCrossDir = 0.0f;
s_app.m_fZoomSpeed = 0.0f;
s_app.m_fPitchSpeed = 0.0f;
s_app.m_fRotationSpeed = 0.0f;
}
void CPythonApplication::GetCameraSetting(SCameraSetting * pCameraSetting)
{
ApplicationCamera& s_app = app();
pCameraSetting->v3CenterPosition = s_app.m_v3CenterPosition;
pCameraSetting->kCmrPos = s_app.m_kCmrPos;
if (CCameraManager::Instance().GetCurrentCamera())
pCameraSetting->v3CenterPosition.z += CCameraManager::Instance().GetCurrentCamera()->GetTargetHeight();
float fHeight;
GetCamera(&pCameraSetting->fZoom, &pCameraSetting->fPitch, &pCameraSetting->fRotation, &fHeight);
}
// 40250 PythonApplication.cpp:1294
void CPythonApplication::SetCenterPosition(float fx, float fy, float fz)
{
ApplicationCamera& s_app = app();
s_app.m_v3CenterPosition.x = +fx;
s_app.m_v3CenterPosition.y = -fy;
s_app.m_v3CenterPosition.z = +fz;
}
// 40250 PythonApplication.cpp:1301
void CPythonApplication::GetCenterPosition(TPixelPosition * pPixelPosition)
{
ApplicationCamera& s_app = app();
pPixelPosition->x = +s_app.m_v3CenterPosition.x;
pPixelPosition->y = -s_app.m_v3CenterPosition.y;
pPixelPosition->z = +s_app.m_v3CenterPosition.z;
}
// 40250 PythonApplication.cpp:1365
void CPythonApplication::EnableSpecialCameraMode()
{
app().m_isSpecialCameraMode = TRUE;
}
void CPythonApplication::SetCameraSpeed(int iPercentage)
{
ApplicationCamera& s_app = app();
s_app.m_fCameraRotateSpeed = c_fDefaultCameraRotateSpeed * float(iPercentage) / 100.0f;
s_app.m_fCameraPitchSpeed = c_fDefaultCameraPitchSpeed * float(iPercentage) / 100.0f;
s_app.m_fCameraZoomSpeed = c_fDefaultCameraZoomSpeed * float(iPercentage) / 100.0f;
}
void CPythonApplication::SaveCameraSetting(const char * c_szFileName)
{
SCameraSetting CameraSetting;
GetCameraSetting(&CameraSetting);
FILE * File = fopen(c_szFileName, "w");
if (!File)
return;
PrintfTabs(File, 0, "CenterPos %f %f %f\n", CameraSetting.v3CenterPosition.x, CameraSetting.v3CenterPosition.y, CameraSetting.v3CenterPosition.z);
PrintfTabs(File, 0, "CameraSetting %f %f %f\n", CameraSetting.fZoom, CameraSetting.fPitch, CameraSetting.fRotation);
PrintfTabs(File, 0, "CmrPos %f %f %f\n", CameraSetting.kCmrPos.m_fUpDir, CameraSetting.kCmrPos.m_fViewDir, CameraSetting.kCmrPos.m_fCrossDir);
Tracef("SaveCameraSetting(%s) - (CenterPos %d %d %d) (Distance %d, Pitch %d, Rotation %d) (UpDir %d, ViewDir %d, CrossDir %d)\n",
c_szFileName,
int(CameraSetting.v3CenterPosition.x),
int(CameraSetting.v3CenterPosition.y),
int(CameraSetting.v3CenterPosition.z),
int(CameraSetting.fZoom),
int(CameraSetting.fPitch),
int(CameraSetting.fRotation),
int(CameraSetting.kCmrPos.m_fUpDir),
int(CameraSetting.kCmrPos.m_fViewDir),
int(CameraSetting.kCmrPos.m_fCrossDir));
fclose(File);
}
bool CPythonApplication::LoadCameraSetting(const char * c_szFileName)
{
CTextFileLoader TextFileLoader;
if (!TextFileLoader.Load(c_szFileName))
return false;
D3DXVECTOR3 v3CenterPosition;
CTokenVector * pCenterPos;
if (TextFileLoader.GetTokenVector("centerpos", &pCenterPos))
if (3 == pCenterPos->size())
{
v3CenterPosition.x = atof(pCenterPos->at(0).c_str());
v3CenterPosition.y = atof(pCenterPos->at(1).c_str());
v3CenterPosition.z = atof(pCenterPos->at(2).c_str());
}
CTokenVector * pCameraSetting;
CTokenVector * pCmrPos;
if (TextFileLoader.GetTokenVector("camerasetting", &pCameraSetting))
if (TextFileLoader.GetTokenVector("cmrpos", &pCmrPos))
if (3 == pCameraSetting->size())
if (3 == pCmrPos->size())
{
SCameraSetting CameraSetting;
CameraSetting.v3CenterPosition = v3CenterPosition;
CameraSetting.fZoom = atof(pCameraSetting->at(0).c_str());
CameraSetting.fPitch = atof(pCameraSetting->at(1).c_str());
CameraSetting.fRotation = atof(pCameraSetting->at(2).c_str());
CameraSetting.kCmrPos.m_fUpDir = atof(pCmrPos->at(0).c_str());
CameraSetting.kCmrPos.m_fViewDir = atof(pCmrPos->at(1).c_str());
CameraSetting.kCmrPos.m_fCrossDir = atof(pCmrPos->at(2).c_str());
SetEventCamera(CameraSetting);
return true;
}
return false;
}
@@ -0,0 +1,220 @@
#include "UserInterface/StdAfx.h"
#include "UserInterface/PythonApplication.h"
#include "UserInterface/PythonBackground.h"
#include "EterLib/Camera.h"
extern PyObject* s_poMouseHandler;
void CPythonApplication::OnCameraUpdate()
{
if ( CPythonBackground::Instance().IsMapReady() )
{
CCamera* pkCameraMgr = CCameraManager::Instance().GetCurrentCamera();
if (pkCameraMgr)
{
pkCameraMgr->Update();
CPythonGraphic::Instance().UpdateViewMatrix();
}
}
}
void CPythonApplication::OnUIUpdate()
{
UI::CWindowManager& rkUIMgr = UI::CWindowManager::Instance();
rkUIMgr.Update();
}
void CPythonApplication::OnUIRender()
{
UI::CWindowManager& rkUIMgr = UI::CWindowManager::Instance();
rkUIMgr.Render();
}
void CPythonApplication::OnSizeChange(int width, int height)
{
}
void CPythonApplication::OnMouseMiddleButtonDown(int x, int y)
{
CCameraManager& rkCmrMgr = CCameraManager::Instance();
CCamera* pkCmrCur = rkCmrMgr.GetCurrentCamera();
if (pkCmrCur)
pkCmrCur->BeginDrag(x, y);
if ( !CPythonBackground::Instance().IsMapReady() )
return;
SetCursorNum(CAMERA_ROTATE);
if ( CURSOR_MODE_HARDWARE == GetCursorMode())
SetCursorVisible(FALSE, true);
}
void CPythonApplication::OnMouseMiddleButtonUp(int x, int y)
{
CCameraManager& rkCmrMgr = CCameraManager::Instance();
CCamera* pkCmrCur = rkCmrMgr.GetCurrentCamera();
if (pkCmrCur)
pkCmrCur->EndDrag();
if ( !CPythonBackground::Instance().IsMapReady() )
return;
SetCursorNum(NORMAL);
if ( CURSOR_MODE_HARDWARE == GetCursorMode())
SetCursorVisible(TRUE);
}
void CPythonApplication::OnMouseWheel(int nLen)
{
CCameraManager& rkCmrMgr = CCameraManager::Instance();
CCamera* pkCmrCur = rkCmrMgr.GetCurrentCamera();
if (pkCmrCur)
pkCmrCur->Wheel(nLen);
}
void CPythonApplication::OnMouseMove(int x, int y)
{
CCameraManager& rkCmrMgr = CCameraManager::Instance();
CCamera* pkCmrCur = rkCmrMgr.GetCurrentCamera();
POINT Point;
if (pkCmrCur)
{
if ( CPythonBackground::Instance().IsMapReady() && pkCmrCur->Drag(x, y, &Point) )
{
x = Point.x;
y = Point.y;
}
}
UI::CWindowManager& rkWndMgr = UI::CWindowManager::Instance();
rkWndMgr.RunMouseMove(x, y);
}
void CPythonApplication::OnMouseLeftButtonDown(int x, int y)
{
UI::CWindowManager& rkWndMgr = UI::CWindowManager::Instance();
rkWndMgr.RunMouseLeftButtonDown(x, y);
}
void CPythonApplication::OnMouseLeftButtonUp(int x, int y)
{
UI::CWindowManager& rkWndMgr = UI::CWindowManager::Instance();
rkWndMgr.RunMouseLeftButtonUp(x, y);
}
void CPythonApplication::OnMouseLeftButtonDoubleClick(int x, int y)
{
UI::CWindowManager& rkWndMgr = UI::CWindowManager::Instance();
rkWndMgr.RunMouseLeftButtonDown(x, y);
rkWndMgr.RunMouseLeftButtonDoubleClick(x, y);
}
void CPythonApplication::OnMouseRightButtonDown(int x, int y)
{
UI::CWindowManager& rkWndMgr = UI::CWindowManager::Instance();
rkWndMgr.RunMouseRightButtonDown(x, y);
}
void CPythonApplication::OnMouseRightButtonUp(int x, int y)
{
UI::CWindowManager& rkWndMgr = UI::CWindowManager::Instance();
rkWndMgr.RunMouseRightButtonUp(x, y);
}
void CPythonApplication::OnKeyDown(int iIndex)
{
UI::CWindowManager& rkWndMgr = UI::CWindowManager::Instance();
if (DIK_ESCAPE == iIndex)
{
rkWndMgr.RunPressEscapeKey();
}
rkWndMgr.RunKeyDown(iIndex);
}
void CPythonApplication::OnKeyUp(int iIndex)
{
UI::CWindowManager& rkWndMgr = UI::CWindowManager::Instance();
rkWndMgr.RunKeyUp(iIndex);
}
void CPythonApplication::RunIMEUpdate()
{
UI::CWindowManager& rkWndMgr = UI::CWindowManager::Instance();
rkWndMgr.RunIMEUpdate();
}
void CPythonApplication::RunIMETabEvent()
{
UI::CWindowManager& rkWndMgr = UI::CWindowManager::Instance();
rkWndMgr.RunIMETabEvent();
}
void CPythonApplication::RunIMEReturnEvent()
{
UI::CWindowManager& rkWndMgr = UI::CWindowManager::Instance();
rkWndMgr.RunIMEReturnEvent();
}
void CPythonApplication::OnIMEKeyDown(int iIndex)
{
UI::CWindowManager& rkWndMgr = UI::CWindowManager::Instance();
rkWndMgr.RunIMEKeyDown(iIndex);
}
void CPythonApplication::RunIMEChangeCodePage()
{
UI::CWindowManager& rkWndMgr = UI::CWindowManager::Instance();
rkWndMgr.RunChangeCodePage();
}
void CPythonApplication::RunIMEOpenCandidateListEvent()
{
UI::CWindowManager& rkWndMgr = UI::CWindowManager::Instance();
rkWndMgr.RunOpenCandidate();
}
void CPythonApplication::RunIMECloseCandidateListEvent()
{
UI::CWindowManager& rkWndMgr = UI::CWindowManager::Instance();
rkWndMgr.RunCloseCandidate();
}
void CPythonApplication::RunIMEOpenReadingWndEvent()
{
UI::CWindowManager& rkWndMgr = UI::CWindowManager::Instance();
rkWndMgr.RunOpenReading();
}
void CPythonApplication::RunIMECloseReadingWndEvent()
{
UI::CWindowManager& rkWndMgr = UI::CWindowManager::Instance();
rkWndMgr.RunCloseReading();
}
void CPythonApplication::RunPressExitKey()
{
UI::CWindowManager& rkWndMgr = UI::CWindowManager::Instance();
rkWndMgr.RunPressExitKey();
}
void CPythonApplication::OnMouseUpdate()
{
if (!s_poMouseHandler)
return;
UI::CWindowManager& rkWndMgr = UI::CWindowManager::Instance();
long lx, ly;
rkWndMgr.GetMousePosition(lx, ly);
PyCallClassMemberFunc(s_poMouseHandler, "Update", Py_BuildValue("(ii)", lx, ly));
}
void CPythonApplication::OnMouseRender()
{
if (!s_poMouseHandler)
return;
PyCallClassMemberFunc(s_poMouseHandler, "Render", Py_BuildValue("()"));
}
+9
View File
@@ -0,0 +1,9 @@
#pragma once
#include <ctime>
// CPythonApplication is not constructed by the Godot host. Keep the three values that its
// 40250 SetServerTime/GetServerTime/GetServerTimeStamp methods use in the platform adapter.
void SetPlatformServerTime(time_t server_time);
time_t GetPlatformServerTime();
time_t GetPlatformServerTimeStamp();
@@ -0,0 +1,170 @@
// Platform implementation of the pack bootstrap from 40250 UserInterface/UserInterface.cpp. PackInitialize is the 40250
// function with three platform differences:
// - pack names in Index are matched to the on-disk .eix/.epk case-insensitively ("Etc" is ETC.eix on NTFS, and
// CEterPack::CreateIndexFile fopens the name as given), so the registered dbname carries the on-disk spelling;
// - no LogBoxf (a Win32 message box), only the TraceError next to it;
// - CTextFileLoader::SetCacheMode and CSoundData::SetPackMode are not called: EterLib/TextFileLoader and MilesLib
// are not ported yet, and neither affects which files the pack manager registers or returns.
// Built as in the Distribute configuration (_DISTRIBUTE): pack first.
#include "EterBase/StdAfx.h"
#include "EterBase/FileLoader.h"
#include "EterBase/MappedFile.h"
#include "EterBase/Debug.h"
#include "EterBase/lzo.h"
#include "EterPack/EterPackManager.h"
#include "UserInterface.h"
#include <map>
#include <string>
#if defined(_WIN32)
#include <io.h>
#else
#include <dirent.h>
#endif
// 40250 UserInterface.cpp:49.
bool __IS_TEST_SERVER_MODE__=false;
// 40250 UserInterface.cpp:98. PORT: LoadString reads the executable's STRINGTABLE; the one the supplied English
// client resolves is UserInterface.rc's LANG_ENGLISH, SUBLANG_ENGLISH_US section (ids from resource.h).
namespace
{
const char* LoadAppString(DWORD dwID)
{
switch (dwID)
{
case 1: return "Metin 2"; // IDS_APP_NAME
case 2: return "'s"; // IDS_POSSESSIVE_MORPHENE
case 3: return "IDS_WARN_BAD_DRIVER"; // IDS_WARN_BAD_DRIVER
case 4: return "IDS_WARN_NO_TNL"; // IDS_WARN_NO_TNL
case 5: return "Cannot read %s file"; // IDS_ERR_CANNOT_READ_FILE
case 6: return "File '%s' is not latest version. Please launch patcher."; // IDS_ERR_NOT_LATEST_FILE
case 7: return "Please run patcher."; // IDS_ERR_MUST_LAUNCH_FROM_PATCHER
}
return "";
}
std::map<DWORD, std::string> gs_kMap_dwID_stLocale;
} // namespace
const std::string& ApplicationStringTable_GetString(DWORD dwID)
{
std::string& rstLocale=gs_kMap_dwID_stLocale[dwID];
rstLocale=LoadAppString(dwID);
return rstLocale;
}
const char* ApplicationStringTable_GetStringz(DWORD dwID)
{
return ApplicationStringTable_GetString(dwID).c_str();
}
namespace
{
// Lowercased file name -> on-disk spelling, for the files directly in `folder`.
std::map<std::string, std::string> list_folder(const std::string& folder)
{
std::map<std::string, std::string> names;
auto add = [&](const std::string& name) {
std::string lower = name;
for (char& c : lower)
c = (char) tolower((unsigned char) c);
names.emplace(lower, name);
};
#if defined(_WIN32)
_finddata_t fd;
intptr_t h = _findfirst((folder + "*").c_str(), &fd);
if (h != -1)
{
do
add(fd.name);
while (_findnext(h, &fd) == 0);
_findclose(h);
}
#else
if (DIR* d = opendir(folder.c_str()))
{
while (dirent* e = readdir(d))
add(e->d_name);
closedir(d);
}
#endif
return names;
}
// <folder><name> with `name` in the spelling of the on-disk <name>.eix, or unchanged when there is none.
std::string on_disk(const std::map<std::string, std::string>& names, const std::string& folder, const std::string& name)
{
std::string lower = name + ".eix";
for (char& c : lower)
c = (char) tolower((unsigned char) c);
auto it = names.find(lower);
if (it == names.end())
return folder + name;
return folder + it->second.substr(0, it->second.size() - 4);
}
}
void PackSingletons()
{
static CLZO lzo;
static CEterPackManager EterPackManager;
}
// 40250: PackInitialize
bool PackInitialize(const char * c_pszFolder)
{
if (_access(c_pszFolder, 0) != 0)
return true;
std::string stFolder(c_pszFolder);
stFolder += "/";
std::string stFileName(stFolder);
stFileName += "Index";
CMappedFile file;
LPCVOID pvData;
if (!file.Create(stFileName.c_str(), &pvData, 0, 0))
{
TraceError("FATAL ERROR! File not exist: %s", stFileName.c_str());
return true;
}
CMemoryTextFileLoader TextLoader;
TextLoader.Bind(file.Size(), pvData);
bool bPackFirst = TRUE;
const std::string& strPackType = TextLoader.GetLineString(0);
if (strPackType.compare("FILE") && strPackType.compare("PACK"))
{
TraceError("Pack/Index has invalid syntax. First line must be 'PACK' or 'FILE'");
return false;
}
CEterPackManager::Instance().SetCacheMode();
CEterPackManager::Instance().SetSearchMode(bPackFirst);
const std::map<std::string, std::string> names = list_folder(stFolder);
std::string strPackName, strTexCachePackName;
for (DWORD i = 1; i < TextLoader.GetLineCount() - 1; i += 2)
{
const std::string & c_rstFolder = TextLoader.GetLineString(i);
const std::string & c_rstName = TextLoader.GetLineString(i + 1);
strPackName = on_disk(names, stFolder, c_rstName);
strTexCachePackName = on_disk(names, stFolder, c_rstName + "_texcache");
CEterPackManager::Instance().RegisterPack(strPackName.c_str(), c_rstFolder.c_str());
CEterPackManager::Instance().RegisterPack(strTexCachePackName.c_str(), c_rstFolder.c_str());
}
CEterPackManager::Instance().RegisterRootPack(on_disk(names, stFolder, "root").c_str());
return true;
}
@@ -0,0 +1,12 @@
#pragma once
// Platform-layer pieces of 40250 UserInterface/UserInterface.cpp (the WinMain unit). 40250 declares these nowhere:
// Main() in the same file calls them. The extension's pack bootstrap calls them instead.
// 40250: PackInitialize
// Registers <folder>/Index the way the 40250 client does at startup. The CLZO and CEterPackManager singletons
// it needs must already exist (see PackSingletons).
bool PackInitialize(const char * c_pszFolder);
// The two function-static singletons 40250 Main() creates before PackInitialize("pack")
// (`static CLZO lzo; static CEterPackManager EterPackManager;`), created on first use and alive until exit.
void PackSingletons();
@@ -0,0 +1,29 @@
// 40250 UserInterface/WiseLogicXTrap.cpp: the build without XTRAP_CLIENT_ENABLE (the XTrap anti-cheat SDK is
// Win32-only and not shipped), verbatim.
#include "UserInterface/StdAfx.h"
#include "UserInterface/Locale.h"
#include "UserInterface/WiseLogicXTrap.h"
bool XTrap_Init()
{
return true;
}
bool XTrap_CheckInit()
{
return true;
}
void XTrap_PollEvent()
{
}
void XTrap_SetUserInfo(LPCSTR szUserID, LPCSTR szServerName, LPCSTR szCharacterName, LPCSTR szCharacterClass, SOCKET hSocket)
{
}
void XTrap_ValidateCheckStream( LPVOID PacketBufferIn, LPVOID PacketBufferOut )
{
}
+457
View File
@@ -0,0 +1,457 @@
// The <wingdi.h> subset the 40250 font path calls (common/shim/win32/wingdi.h), over FreeType.
// CGraphicDib / CGraphicFontTexture run unchanged on top of it: a memory DC owns a 32-bit DIB,
// CreateFontIndirect maps the LOGFONT onto a TrueType face the way GDI sizes it, and TextOutW
// rasterises into the DIB with the DC's text/background colours.
//
// GDI sizing that the glyph atlas depends on:
// - lfHeight > 0 is the cell height (ascent + descent), lfHeight < 0 the em height; the em is
// lfHeight * unitsPerEm / (usWinAscent + usWinDescent), rounded to whole pixels.
// - tmAscent / tmDescent are usWinAscent / usWinDescent scaled to that em and rounded;
// GetTextExtentPoint32W reports tmHeight = tmAscent + tmDescent as the height.
// - ANTIALIASED_QUALITY follows the face's gasp table: grayscale only in the ppem ranges it
// flags GASP_DO_GRAY, otherwise bilevel (Tahoma at 10/12 ppem is bilevel).
// - The glyph origin is (x + A, y + tmAscent - top); advance = A + B + C.
// Missing glyphs fall back to the first installed face that has them, like GDI font linking.
#include "EterLib/StdAfx.h"
#include <ft2build.h>
#include FT_FREETYPE_H
#include FT_TRUETYPE_TABLES_H
#include FT_GASP_H
#include FT_SYNTHESIS_H
#include FT_DRIVER_H
#include FT_MODULE_H
#include <algorithm>
#include <cctype>
#include <cmath>
#include <cstdint>
#include <cstring>
#include <mutex>
#include <string>
#include <unordered_map>
#include <vector>
#include <dirent.h>
namespace {
enum class GdiKind { Bitmap, Font };
struct GdiObject
{
GdiKind kind;
};
} // namespace
struct HBITMAP__ : GdiObject
{
int width = 0;
int height = 0;
bool top_down = true;
std::vector<uint32_t> bits;
};
struct HFONT__ : GdiObject
{
FT_Face face = nullptr;
std::vector<FT_Face> fallbacks;
int ppem = 0;
int ascent = 0;
int descent = 0;
bool italic = false;
bool antialiased = false;
};
struct HDC__
{
HBITMAP bitmap = nullptr;
HFONT font = nullptr;
COLORREF text = 0;
COLORREF bk = 0x00FFFFFF;
int bk_mode = OPAQUE;
};
namespace {
std::mutex g_mutex;
FT_Library g_library = nullptr;
std::unordered_map<std::string, FT_Face> g_faces; // loaded face per file path
FT_Library library()
{
if (!g_library) {
FT_Init_FreeType(&g_library);
// GDI runs the full TrueType bytecode, which is FreeType's v35 interpreter; v40 drops the
// horizontal hints and gives different advances at small sizes.
FT_UInt version = TT_INTERPRETER_VERSION_35;
FT_Property_Set(g_library, "truetype", "interpreter-version", &version);
}
return g_library;
}
std::string lower(std::string s)
{
for (char& c : s) c = char(std::tolower(static_cast<unsigned char>(c)));
return s;
}
const std::vector<std::string>& font_dirs()
{
static const std::vector<std::string> dirs = {
#if defined(__ANDROID__)
"/system/fonts",
#else
"/System/Library/Fonts/Supplemental",
"/System/Library/Fonts",
"/Library/Fonts",
#endif
};
return dirs;
}
// Face name -> font file: the file stem matched case-insensitively ("Tahoma" -> Tahoma.ttf).
std::string find_font_file(const std::string& face)
{
const std::string want = lower(face);
for (const std::string& dir : font_dirs()) {
DIR* d = opendir(dir.c_str());
if (!d) continue;
std::string hit;
while (dirent* e = readdir(d)) {
std::string name = e->d_name;
const size_t dot = name.rfind('.');
if (dot == std::string::npos) continue;
const std::string ext = lower(name.substr(dot + 1));
if (ext != "ttf" && ext != "ttc" && ext != "otf") continue;
if (lower(name.substr(0, dot)) == want) { hit = dir + "/" + name; break; }
}
closedir(d);
if (!hit.empty()) return hit;
}
return {};
}
FT_Face open_face(const std::string& path)
{
auto it = g_faces.find(path);
if (it != g_faces.end()) return it->second;
FT_Face face = nullptr;
if (FT_New_Face(library(), path.c_str(), 0, &face) != 0) face = nullptr;
if (face) FT_Select_Charmap(face, FT_ENCODING_UNICODE);
g_faces[path] = face;
return face;
}
FT_Face open_named(const char* name)
{
const std::string path = find_font_file(name);
return path.empty() ? nullptr : open_face(path);
}
// PORT: the faces GDI would substitute when the requested one is not installed (the 40250 locale
// asks for Tahoma / Arial on code page 1252), then the font-linking faces for CJK/Hangul glyphs.
const char* const kSubstitutes[] = {"Arial", "Helvetica", "Roboto-Regular", "DroidSans", "NotoSans-Regular"};
const char* const kLinked[] = {"Arial Unicode", "AppleSDGothicNeo", "NotoSansCJK-Regular", "NotoSansCJKkr-Regular",
"DroidSansFallback"};
bool gray_at(FT_Face face, int ppem)
{
const FT_Int flags = FT_Get_Gasp(face, FT_UInt(ppem));
if (flags == FT_GASP_NO_TABLE) return true;
return (flags & FT_GASP_DO_GRAY) != 0;
}
void set_size(FT_Face face, int ppem)
{
FT_Set_Pixel_Sizes(face, 0, FT_UInt(ppem));
}
struct Glyph
{
int left = 0; // A
int top = 0; // rows above the baseline
int advance = 0; // A + B + C
int width = 0; // B
int rows = 0;
int pitch = 0;
bool mono = true;
std::vector<unsigned char> bitmap;
};
bool load_glyph(HFONT font, wchar_t ch, bool render, Glyph* out)
{
FT_Face face = font->face;
FT_UInt index = FT_Get_Char_Index(face, FT_ULong(ch));
if (index == 0) {
for (FT_Face fallback : font->fallbacks) {
FT_UInt i = FT_Get_Char_Index(fallback, FT_ULong(ch));
if (i) { face = fallback; index = i; break; }
}
}
set_size(face, font->ppem);
const bool gray = font->antialiased && gray_at(face, font->ppem);
const FT_Int32 target = gray ? FT_LOAD_TARGET_NORMAL : FT_LOAD_TARGET_MONO;
if (FT_Load_Glyph(face, index, FT_LOAD_DEFAULT | target) != 0) return false;
FT_GlyphSlot slot = face->glyph;
if (font->italic) FT_GlyphSlot_Oblique(slot);
out->advance = int((slot->advance.x + 32) >> 6);
if (slot->format == FT_GLYPH_FORMAT_OUTLINE) {
if (FT_Render_Glyph(slot, gray ? FT_RENDER_MODE_NORMAL : FT_RENDER_MODE_MONO) != 0) return false;
}
const FT_Bitmap& bm = slot->bitmap;
out->left = slot->bitmap_left;
out->top = slot->bitmap_top;
out->width = int(bm.width);
out->rows = int(bm.rows);
out->mono = bm.pixel_mode == FT_PIXEL_MODE_MONO;
if (render && bm.buffer && bm.rows) {
out->pitch = std::abs(bm.pitch);
out->bitmap.assign(bm.buffer, bm.buffer + size_t(out->pitch) * bm.rows);
}
return true;
}
HFONT default_font()
{
static HFONT font = [] {
LOGFONT lf{};
lf.lfHeight = 12;
std::strcpy(lf.lfFaceName, "Arial");
return CreateFontIndirect(&lf);
}();
return font;
}
HFONT dc_font(HDC hdc)
{
return hdc->font ? hdc->font : default_font();
}
// COLORREF is 0x00BBGGRR; a 32-bit DIB pixel is 0x00RRGGBB.
uint32_t dib_pixel(COLORREF c)
{
return ((c & 0xFF) << 16) | (c & 0xFF00) | ((c >> 16) & 0xFF);
}
uint32_t* dib_row(HBITMAP bmp, int y)
{
const int row = bmp->top_down ? y : bmp->height - 1 - y;
return bmp->bits.data() + size_t(row) * size_t(bmp->width);
}
} // namespace
HDC CreateCompatibleDC(HDC)
{
return new HDC__();
}
BOOL DeleteDC(HDC hdc)
{
delete hdc;
return TRUE;
}
HBITMAP CreateDIBSection(HDC, const BITMAPINFO* pbmi, UINT, void** ppvBits, HANDLE, DWORD)
{
if (!pbmi || pbmi->bmiHeader.biBitCount != 32 || pbmi->bmiHeader.biCompression != BI_RGB) return nullptr;
const LONG w = pbmi->bmiHeader.biWidth;
const LONG h = pbmi->bmiHeader.biHeight;
if (w <= 0 || h == 0) return nullptr;
auto* bmp = new HBITMAP__();
bmp->kind = GdiKind::Bitmap;
bmp->width = int(w);
bmp->height = int(h < 0 ? -h : h);
bmp->top_down = h < 0;
bmp->bits.assign(size_t(bmp->width) * size_t(bmp->height), 0);
if (ppvBits) *ppvBits = bmp->bits.data();
return bmp;
}
// The only caller is CGraphicDib::Put onto a window DC, which this platform does not have.
int SetDIBitsToDevice(HDC, int, int, DWORD, DWORD h, int, int, UINT, UINT, const void*, const BITMAPINFO*, UINT)
{
return int(h);
}
HFONT CreateFontIndirect(const LOGFONT* lplf)
{
if (!lplf) return nullptr;
std::lock_guard<std::mutex> lock(g_mutex);
FT_Face face = open_named(lplf->lfFaceName);
for (const char* name : kSubstitutes) {
if (face) break;
face = open_named(name);
}
if (!face) return nullptr;
auto* font = new HFONT__();
font->kind = GdiKind::Font;
font->face = face;
for (const char* name : kLinked)
if (FT_Face linked = open_named(name); linked && linked != face) font->fallbacks.push_back(linked);
font->italic = lplf->lfItalic != 0;
font->antialiased = lplf->lfQuality == ANTIALIASED_QUALITY;
const TT_OS2* os2 = static_cast<const TT_OS2*>(FT_Get_Sfnt_Table(face, FT_SFNT_OS2));
const double upem = face->units_per_EM ? face->units_per_EM : 2048;
const double win_ascent = os2 && os2->usWinAscent ? os2->usWinAscent : face->ascender;
const double win_descent = os2 && os2->usWinAscent ? os2->usWinDescent : -face->descender;
LONG height = lplf->lfHeight ? lplf->lfHeight : 12;
int ppem = height > 0 ? int(std::lround(height * upem / (win_ascent + win_descent))) : int(-height);
font->ppem = std::max(ppem, 1);
font->ascent = int(std::lround(win_ascent * font->ppem / upem));
font->descent = int(std::lround(win_descent * font->ppem / upem));
return font;
}
BOOL DeleteObject(HGDIOBJ ho)
{
if (!ho) return FALSE;
auto* object = static_cast<GdiObject*>(ho);
if (object->kind == GdiKind::Bitmap) delete static_cast<HBITMAP__*>(object);
else delete static_cast<HFONT__*>(object); // faces stay cached for the process
return TRUE;
}
HGDIOBJ SelectObject(HDC hdc, HGDIOBJ h)
{
if (!hdc || !h) return nullptr;
auto* object = static_cast<GdiObject*>(h);
if (object->kind == GdiKind::Bitmap) {
HGDIOBJ old = hdc->bitmap;
hdc->bitmap = static_cast<HBITMAP__*>(object);
return old;
}
HGDIOBJ old = hdc->font;
hdc->font = static_cast<HFONT__*>(object);
return old;
}
COLORREF SetTextColor(HDC hdc, COLORREF color)
{
const COLORREF old = hdc->text;
hdc->text = color;
return old;
}
COLORREF SetBkColor(HDC hdc, COLORREF color)
{
const COLORREF old = hdc->bk;
hdc->bk = color;
return old;
}
int SetBkMode(HDC hdc, int mode)
{
const int old = hdc->bk_mode;
hdc->bk_mode = mode;
return old;
}
BOOL GetTextExtentPoint32W(HDC hdc, LPCWSTR lpString, int c, LPSIZE psizl)
{
if (!hdc || !psizl) return FALSE;
std::lock_guard<std::mutex> lock(g_mutex);
HFONT font = dc_font(hdc);
if (!font) return FALSE;
LONG cx = 0;
for (int i = 0; i < c; ++i) {
Glyph glyph;
if (load_glyph(font, lpString[i], false, &glyph)) cx += glyph.advance;
}
psizl->cx = cx;
psizl->cy = font->ascent + font->descent;
return TRUE;
}
BOOL GetCharABCWidthsFloatW(HDC hdc, UINT iFirst, UINT iLast, LPABCFLOAT lpABC)
{
if (!hdc || !lpABC || iLast < iFirst) return FALSE;
std::lock_guard<std::mutex> lock(g_mutex);
HFONT font = dc_font(hdc);
if (!font) return FALSE;
for (UINT ch = iFirst; ch <= iLast; ++ch) {
Glyph glyph;
if (!load_glyph(font, wchar_t(ch), false, &glyph)) return FALSE;
ABCFLOAT& abc = lpABC[ch - iFirst];
if (glyph.width == 0) {
// A blank glyph (space) is all advance, like GDI reports it.
abc.abcfA = 0;
abc.abcfB = float(glyph.advance);
abc.abcfC = 0;
} else {
abc.abcfA = float(glyph.left);
abc.abcfB = float(glyph.width);
abc.abcfC = float(glyph.advance - glyph.left - glyph.width);
}
}
return TRUE;
}
BOOL TextOutW(HDC hdc, int x, int y, LPCWSTR lpString, int c)
{
if (!hdc || !hdc->bitmap) return FALSE;
std::lock_guard<std::mutex> lock(g_mutex);
HFONT font = dc_font(hdc);
if (!font) return FALSE;
HBITMAP bmp = hdc->bitmap;
const int height = font->ascent + font->descent;
std::vector<Glyph> glyphs(size_t(std::max(c, 0)));
int extent = 0;
for (int i = 0; i < c; ++i) {
load_glyph(font, lpString[i], true, &glyphs[size_t(i)]);
extent += glyphs[size_t(i)].advance;
}
if (hdc->bk_mode == OPAQUE) {
const uint32_t bk = dib_pixel(hdc->bk);
for (int py = std::max(y, 0); py < std::min(y + height, bmp->height); ++py) {
uint32_t* row = dib_row(bmp, py);
for (int px = std::max(x, 0); px < std::min(x + extent, bmp->width); ++px) row[px] = bk;
}
}
const uint32_t fg = dib_pixel(hdc->text);
const uint32_t bg = dib_pixel(hdc->bk);
int pen = x;
for (const Glyph& glyph : glyphs) {
const int ox = pen + glyph.left;
const int oy = y + font->ascent - glyph.top;
for (int gy = 0; gy < glyph.rows && !glyph.bitmap.empty(); ++gy) {
const int py = oy + gy;
if (py < 0 || py >= bmp->height) continue;
uint32_t* row = dib_row(bmp, py);
const unsigned char* src = glyph.bitmap.data() + size_t(gy) * size_t(glyph.pitch);
for (int gx = 0; gx < glyph.width; ++gx) {
const int px = ox + gx;
if (px < 0 || px >= bmp->width) continue;
unsigned coverage = glyph.mono ? ((src[gx >> 3] >> (7 - (gx & 7))) & 1) * 255 : src[gx];
if (!coverage) continue;
if (coverage == 255) { row[px] = fg; continue; }
// Grayscale GDI text blends the text colour over the background colour.
const uint32_t under = hdc->bk_mode == OPAQUE ? bg : row[px];
uint32_t out = 0;
for (int shift = 0; shift < 24; shift += 8) {
const unsigned a = (fg >> shift) & 0xFF, b = (under >> shift) & 0xFF;
out |= ((a * coverage + b * (255 - coverage) + 127) / 255) << shift;
}
row[px] = out;
}
}
pen += glyph.advance;
}
return TRUE;
}
BOOL TextOutA(HDC hdc, int x, int y, LPCSTR lpString, int c)
{
const int n = MultiByteToWideChar(CP_ACP, 0, lpString, c, nullptr, 0);
if (n <= 0) return c == 0;
std::vector<WCHAR> wide(static_cast<size_t>(n));
MultiByteToWideChar(CP_ACP, 0, lpString, c, wide.data(), n);
return TextOutW(hdc, x, y, wide.data(), n);
}