1
0

55 Commits

Author SHA1 Message Date
a5aee0a464 chore: freeze yycc dep version in github action workflow 2026-03-22 13:22:16 +08:00
dfaf911b57 doc: update dev notes 2026-03-05 12:46:24 +08:00
5b02733d20 chore: bypass std::mutex ABI issue on windows by build script 2026-03-05 08:45:55 +08:00
11336807d7 fix: fix macos build issue 2026-03-04 20:49:41 +08:00
c05dae9429 fix: fix linux build issue 2026-03-04 13:58:34 +08:00
23b14ac69f fix: fix build issue 2026-03-04 12:44:40 +08:00
c9fdd30185 feat: split the decl and impl of VxImageDescEx 2026-03-04 11:28:26 +08:00
db0bdc8618 feat: install unvirt manual in manual directory 2026-03-04 11:10:17 +08:00
a87ff6d2db feat: add new rule in BMapInspector 2026-03-04 11:06:29 +08:00
3f6d131d0d feat: add new rule in BMapInspector 2026-03-04 11:01:14 +08:00
4c71a20935 feat: fully refactor BMapInspector rule set for better layout 2026-03-03 17:11:30 +08:00
49a729078c feat: add new rules in BMapInspector 2026-03-03 14:59:43 +08:00
f0160ce7c2 doc: add unvirt doc 2026-03-03 00:14:17 +08:00
b78732f30c feat: add new rule in BMapInspector 2026-03-02 23:51:53 +08:00
86353305e8 feat: update words in BMapInspector to remove ambiguity 2026-03-02 12:47:45 +08:00
d1f4a37097 feat: finish dup mesh/mtl/tex check rule in BMapInspector
- also fix "use after free" issue in QuoteObjectNames.
2026-03-02 12:30:18 +08:00
1a36a8b6d7 feat: add exact mesh/material/texture hash and equal_to 2026-03-02 10:49:24 +08:00
eaa7814b18 fix: fix bmap-rs error 2026-03-01 21:00:20 +08:00
49c9b00c11 feat: finish bmap-rs 2026-03-01 20:40:15 +08:00
4072285425 feat: update bmmesh in bmap-rs 2026-03-01 20:01:17 +08:00
0ce752b7ba feat: finish bmmeshtrans in bmap-rs 2026-02-28 22:50:28 +08:00
1de0196f26 feat: fix bmap-rs test 2026-02-28 17:58:41 +08:00
c2da274a11 feat: finish bmfile reader and writer in bmap-rs 2026-02-28 17:02:49 +08:00
c9d369d2c4 feat: update test for bmap-rs 2026-02-25 09:51:18 +08:00
54fed7e37b feat: add new rules in BMapInspector 2026-02-24 14:24:02 +08:00
e73f649187 feat: add new rules for BMapInspector 2026-02-24 13:49:20 +08:00
2f9da2e852 feat: write shit for bmap-rs 2026-02-20 17:51:45 +08:00
8dbce47d8a feat: add new 2 rules for BMapInspector 2026-02-20 16:00:00 +08:00
d31a98a859 fix: add lost GetTexture in BMapSharp for BMMaterial 2026-02-18 22:51:50 +08:00
9c4c4a7fa4 feat: update bmap-rs 2026-02-18 22:44:10 +08:00
cf0966e6d3 feat: update bmap-rs 2026-02-18 20:23:54 +08:00
6ea43cd82f feat: update bamp-rs 2026-02-18 17:17:35 +08:00
4f24b76193 feat: update bmap-rs 2026-02-17 23:44:14 +08:00
518d2c77ec feat: update bmap-rs 2026-02-17 00:29:44 +08:00
9aa5e05a03 feat: update bmap-rs wrapper 2026-02-15 23:04:55 +08:00
a04a3a9b34 feat: finish bmap-rs ffi bindings 2026-02-15 15:46:12 +08:00
8e0c6f3793 feat: finish virtools types in bmap-rs 2026-02-15 14:10:42 +08:00
763255d2a7 refactor: merge 2 rust crate in one 2026-02-15 11:41:23 +08:00
ade1eadd50 feat: finish EnumsMigration/EnumsRender 2026-02-15 10:58:58 +08:00
4619cb5d1a feat: update flag enum and enum underlying type decision rules for codegen 2026-02-11 22:49:54 +08:00
3310cac100 feat: add rust support for code gen 2026-02-11 10:27:44 +08:00
fdf2a4fc22 doc: update doc 2026-02-10 00:10:56 +08:00
5fe62e8fb3 doc: update main readme. 2026-02-09 23:59:59 +08:00
1b991dd834 doc: update doc for BMap bindings 2026-02-09 22:56:38 +08:00
30f7201a07 feat: finish pybmap 2026-02-09 22:28:46 +08:00
9917db0399 feat: finish fixing for pybmap 2026-02-09 16:38:53 +08:00
a30a0a41d7 refactor: refactor pybmap test 2026-02-08 11:38:48 +08:00
80929039cc refactor: restore pybmap with new layout 2026-02-08 10:52:53 +08:00
11d2e5116b refactor: remove the whole PyBMap directory to avoid case-insenstive issue on Win32 2026-02-08 10:11:35 +08:00
b9d42c73f7 fix: fix BMap export function implementation bug 2026-02-07 22:23:52 +08:00
705af2aa3f fix: fix BMapSharpTest 2026-02-06 22:07:35 +08:00
f7074eb98f feat: update BMapSharp test 2026-02-06 20:33:22 +08:00
c379c00a3f feat: update BMapSharp binding 2026-02-06 17:52:13 +08:00
37b8f2d023 feat: update BMapSharp marshaler 2026-02-06 17:13:28 +08:00
d2a9b18ede fix: update BMapSharp virtools type.
- update BMapSharp virtools types.
- fix enum migration generation error.
2026-02-06 10:21:23 +08:00
126 changed files with 13243 additions and 3928 deletions

View File

@@ -9,6 +9,19 @@ MKDIR install
:: Build with x64 architecture in Release mode
CD build
:: We set this to revert the incompatible ABI for MSVC STL.
:: See: https://github.com/microsoft/STL/wiki/VS-2022-Changelog#vs-2022-1710
::
:: Ideally, I can install new VCRedist to resolve this issue.
:: However, Blender embeds its own VCRedist when distribution which has lower VCRedist version.
:: And at the same time, Blender will load our BMap.dll built by new VCRedist, so it trigger the incompatible ABI issue.
::
:: Currently, the VCRedist distributed by Blender 4.5 LTS is incompatible with our BMap.dll.
:: So I write it in script, rather than in CMake file, to temporaryly fix this issue.
::
:: This fix also is written in dependency build scripts, please remove them together if you remove this,
:: when Blender migrate to the new VCRedist.
set CXXFLAGS=/D_DISABLE_CONSTEXPR_MUTEX_CONSTRUCTOR=1
cmake -A x64 -DCMAKE_CXX_STANDARD=23 -DNEMO_BUILD_UNVIRT=ON -DNEMO_BUILD_BALLANCE=ON -DNEMO_BUILD_BMAP=ON -DNEMO_BUILD_BMAPINSPECTOR=ON -DYYCCommonplace_ROOT=%YYCCommonplace_ROOT% -DSTB_ROOT=%STB_ROOT% -DZLIB_ROOT=%ZLIB_ROOT% ../..
cmake --build . --config Release
cmake --install . --prefix=../install --config Release

View File

@@ -9,6 +9,7 @@ MKDIR install
:: Build with x64 architecture in Release mode
CD build
set CXXFLAGS=/D_DISABLE_CONSTEXPR_MUTEX_CONSTRUCTOR=1
cmake -A x64 -DCMAKE_CXX_STANDARD=23 ../..
cmake --build . --config Release
cmake --install . --prefix=../install --config Release

View File

@@ -18,7 +18,7 @@ jobs:
uses: actions/checkout@v4
with:
repository: 'yyc12345/YYCCommonplace'
ref: 'master'
ref: 'v2.0.0'
path: 'extern/YYCCommonplace'
- name: Build YYCCommonplace
shell: bash

View File

@@ -13,7 +13,7 @@ jobs:
uses: actions/checkout@v4
with:
repository: 'yyc12345/YYCCommonplace'
ref: 'master'
ref: 'v2.0.0'
path: 'extern/YYCCommonplace'
- name: Build YYCCommonplace
shell: bash

View File

@@ -20,7 +20,7 @@ jobs:
uses: actions/checkout@v4
with:
repository: 'yyc12345/YYCCommonplace'
ref: 'master'
ref: 'v2.0.0'
path: 'extern/YYCCommonplace'
- name: Build YYCCommonplace
shell: cmd

View File

@@ -1,3 +1,8 @@
## ======== Personal ========
# Remove I set environment variables for personal testing.
launchSettings.json
## ======== Visual Studio ========
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##

View File

@@ -1,4 +1,4 @@
<Solution>
<Project Path="BMapSharp/BMapSharp.csproj" />
<Project Path="BMapSharpTestbench/BMapSharpTestbench.csproj" />
<Project Path="BMapSharpTest/BMapSharpTest.csproj" />
</Solution>

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,303 @@
using System;
using System.Text;
using System.Runtime.InteropServices;
namespace BMapSharp.BMapMarshalers {
// References:
// https://stackoverflow.com/questions/18498452/how-do-i-write-a-custom-marshaler-which-allows-data-to-flow-from-native-to-manag
// https://learn.microsoft.com/en-us/dotnet/fundamentals/runtime-libraries/system-runtime-interopservices-icustommarshaler
//
// NOTE: I do not create a member to store the object we are marshaling.
// Because my binding do not have In, Out parameter. All parameters are In OR Out.
// So there is no reason to keep that member.
// YYC MARK:
// When receiving UTF8 string pointer given by BMap as managed string,
// I don't know why Microsoft try to call ICustomMarshaler.CleanUpNativeData without calling ICustomMarshaler.MarshalManagedToNative.
// It is trying to free the pointer managed by LibCmo self (for example, it will try to free we got string when getting object name)!
// So as the compromise, we introduce 2 different marshalers for In / Out string marshaling respectively.
// BMStringMarshaler for receiving string from BMap (OUT direction), and BMPOwnedStringMarshaler for passing string to BMap (IN direction).
// The name of marshaler for string array marshaling also following this pattern.
public class BMStringMarshaler : ICustomMarshaler {
private static readonly BMStringMarshaler INSTANCE = new BMStringMarshaler();
public static ICustomMarshaler GetInstance(string pstrCookie) {
return BMStringMarshaler.INSTANCE;
}
public IntPtr MarshalManagedToNative(object ManagedObj) {
// For OUT direction, we do not convert any managed data into native data.
// Return nullptr instead.
return IntPtr.Zero;
}
public object MarshalNativeToManaged(IntPtr pNativeData) {
// Check nullptr
if (pNativeData == IntPtr.Zero) return null;
// Call self
return BMStringMarshaler.ToManaged(pNativeData);
}
public void CleanUpNativeData(IntPtr pNativeData) {
// For OUT direction, we do not convert any managed data into native data.
// Do nothing here.
}
public void CleanUpManagedData(object ManagedObj) {
// Managed data will be cleaned by C# GC.
// So we do nothing here.
}
public int GetNativeDataSize() {
// Return -1 to indicate the size of the native data to be marshaled is variable.
return -1;
}
/// <summary>
/// Return the length in byte of given pointer represented C style string.
/// </summary>
/// <param name="ptr">The pointer for checking.</param>
/// <returns>The length of C style string (NUL exclusive).</returns>
internal static int GetCStringLength(IntPtr ptr) {
int count = 0, unit = Marshal.SizeOf<byte>();
while (Marshal.ReadByte(ptr) != (byte)0) {
ptr += unit;
++count;
}
return count;
}
/// <summary>
/// Extract managed string from given native pointer holding C style string data.
/// This function is shared by 2 marshalers.
/// </summary>
/// <param name="ptr">Native pointer holding string data. Caller must make sure this pointer is not nullptr.</param>
/// <returns>The extracted managed string data.</returns>
internal static string ToManaged(IntPtr ptr) {
// Get the length of given string.
int szStringItemCount = BMStringMarshaler.GetCStringLength(ptr);
int szStringItemSize = Marshal.SizeOf<byte>();
// Prepare cache and copy string data
byte[] encString = new byte[szStringItemCount];
Marshal.Copy(ptr, encString, 0, szStringItemCount);
// Decode string and return
return Encoding.UTF8.GetString(encString);
}
}
public class BMOwnedStringMarshaler : ICustomMarshaler {
private static readonly BMOwnedStringMarshaler INSTANCE = new BMOwnedStringMarshaler();
public static ICustomMarshaler GetInstance(string pstrCookie) {
return BMOwnedStringMarshaler.INSTANCE;
}
public IntPtr MarshalManagedToNative(object ManagedObj) {
// Check requirements.
if (ManagedObj is null) return IntPtr.Zero;
string castManagedObj = ManagedObj as string;
if (castManagedObj is null)
throw new MarshalDirectiveException("BMStringMarshaler must be used on a string.");
// Call self
return BMOwnedStringMarshaler.ToNative(castManagedObj);
}
public object MarshalNativeToManaged(IntPtr pNativeData) {
// For IN direction, we do not convert any native data into managed data.
// Return null instead.
return null;
}
public void CleanUpNativeData(IntPtr pNativeData) {
// Check nullptr
if (pNativeData == IntPtr.Zero) return;
// Free native pointer
Marshal.FreeHGlobal(pNativeData);
}
public void CleanUpManagedData(object ManagedObj) {
// For IN direction, we do not convert any native data into managed data.
// Do nothing here.
}
public int GetNativeDataSize() {
// Return -1 to indicate the size of the native data to be marshaled is variable.
return -1;
}
/// <summary>
/// Convert given string object to native data.
/// This function is shared by 2 marshalers.
/// </summary>
/// <param name="obj">String object. Caller must make sure this object is not null.</param>
/// <returns>The created native data pointer.</returns>
internal static IntPtr ToNative(string obj) {
// Encode string first
byte[] encString = Encoding.UTF8.GetBytes(obj);
// Allocate string memory with extra NUL.
int szStringItemCount = encString.Length;
int szStringItemSize = Marshal.SizeOf<byte>();
IntPtr pString = Marshal.AllocHGlobal(szStringItemSize * (szStringItemCount + 1));
// Copy encoded string data
Marshal.Copy(encString, 0, pString, szStringItemCount);
// Setup NUL
Marshal.WriteByte(pString + (szStringItemSize * szStringItemCount), (byte)0);
// Return value
return pString;
}
}
// YYC MARK:
// For respecting the standard of BMap,
// the native memory we created for string array is a simple array and each item is a pointer to a NULL-terminated UTF8 string.
// Please note the array self is also NULL-terminated otherwise we don't know its length.
public class BMStringArrayMarshaler : ICustomMarshaler {
private static readonly BMStringArrayMarshaler INSTANCE = new BMStringArrayMarshaler();
public static ICustomMarshaler GetInstance(string pstrCookie) {
return BMStringArrayMarshaler.INSTANCE;
}
public IntPtr MarshalManagedToNative(object ManagedObj) {
// For OUT direction, we do not convert any managed data into native data.
// Return nullptr instead.
return IntPtr.Zero;
}
public object MarshalNativeToManaged(IntPtr pNativeData) {
// Check nullptr
if (pNativeData == IntPtr.Zero) return null;
// Get the length of array
int szArrayItemCount = BMStringArrayMarshaler.GetArrayLength(pNativeData);
int szArrayItemSize = Marshal.SizeOf<IntPtr>();
// Prepare array cache and read it.
IntPtr[] apString = new IntPtr[szArrayItemCount];
Marshal.Copy(pNativeData, apString, 0, szArrayItemCount);
// Iterate the array and process each string one by one.
string[] ret = new string[szArrayItemCount];
for (int i = 0; i < szArrayItemCount; ++i) {
// Get string pointer
IntPtr pString = apString[i];
if (pString == IntPtr.Zero) {
ret[i] = null;
continue;
}
// Extract string
ret[i] = BMStringMarshaler.ToManaged(pString);
}
// Return result
return ret;
}
public void CleanUpNativeData(IntPtr pNativeData) {
// For OUT direction, we do not convert any managed data into native data.
// Do nothing here.
}
public void CleanUpManagedData(object ManagedObj) {
// Managed data will be cleaned by C# GC.
// So we do nothing here.
}
public int GetNativeDataSize() {
// Return -1 to indicate the size of the native data to be marshaled is variable.
return -1;
}
/// <summary>
/// Return the length of array created by this marshaler.
/// </summary>
/// <param name="ptr">The pointer to array for checking.</param>
/// <returns>The length of array (NULL terminal exclusive).</returns>
internal static int GetArrayLength(IntPtr ptr) {
int count = 0, unit = Marshal.SizeOf<IntPtr>();
while (Marshal.ReadIntPtr(ptr) != IntPtr.Zero) {
ptr += unit;
++count;
}
return count;
}
}
public class BMOwnedStringArrayMarshaler : ICustomMarshaler {
private static readonly BMOwnedStringArrayMarshaler INSTANCE = new BMOwnedStringArrayMarshaler();
public static ICustomMarshaler GetInstance(string pstrCookie) {
return BMOwnedStringArrayMarshaler.INSTANCE;
}
public IntPtr MarshalManagedToNative(object ManagedObj) {
// Check nullptr object.
if (ManagedObj is null) return IntPtr.Zero;
// Check argument type.
string[] castManagedObj = ManagedObj as string[];
if (castManagedObj is null)
throw new MarshalDirectiveException("BMStringArrayMashaler must be used on an string array.");
// Allocate string items first
int szArrayItemCount = castManagedObj.Length;
int szArrayItemSize = Marshal.SizeOf<IntPtr>();
IntPtr[] apString = new IntPtr[szArrayItemCount];
for (int i = 0; i < szArrayItemCount; ++i) {
// Check null string
string stringObj = castManagedObj[i];
if (stringObj is null) apString[i] = IntPtr.Zero;
else apString[i] = BMOwnedStringMarshaler.ToNative(stringObj);
}
// Allocate array pointer now.
IntPtr pArray = Marshal.AllocHGlobal(szArrayItemSize * (szArrayItemCount + 1));
// Copy string pointer data
Marshal.Copy(apString, 0, pArray, szArrayItemCount);
// Setup NULL ternimal
Marshal.WriteIntPtr(pArray + (szArrayItemSize * szArrayItemCount), IntPtr.Zero);
// Return value
return pArray;
}
public object MarshalNativeToManaged(IntPtr pNativeData) {
// For IN direction, we do not convert any native data into managed data.
// Return null instead.
return null;
}
public void CleanUpNativeData(IntPtr pNativeData) {
// Check nullptr
if (pNativeData == IntPtr.Zero) return;
// Get the length of array
int szArrayItemCount = BMStringArrayMarshaler.GetArrayLength(pNativeData);
int szArrayItemSize = Marshal.SizeOf<IntPtr>();
// Prepare array cache and read it.
IntPtr[] apString = new IntPtr[szArrayItemCount];
Marshal.Copy(pNativeData, apString, 0, szArrayItemCount);
// Free array self
Marshal.FreeHGlobal(pNativeData);
// Iterate the string pointer array and free them one by one.
foreach (IntPtr pString in apString) {
// Free string pointer
if (pString == IntPtr.Zero) continue;
Marshal.FreeHGlobal(pString);
}
}
public void CleanUpManagedData(object ManagedObj) {
// For IN direction, we do not convert any native data into managed data.
// Do nothing here.
}
public int GetNativeDataSize() {
// Return -1 to indicate the size of the native data to be marshaled is variable.
return -1;
}
}
}

View File

@@ -5,9 +5,12 @@
<ImplicitUsings>enable</ImplicitUsings>
<PackageId>BMapSharp</PackageId>
<Version>1.0.0</Version>
<Title>BMapSharp</Title>
<Version>0.4.0</Version>
<Authors>yyc12345</Authors>
<Description>The C# binding to BMap.</Description>
<Company>BearKidsTeam</Company>
<PackageLicenseExpression>MIT</PackageLicenseExpression>
</PropertyGroup>
<PropertyGroup Condition="$([System.OperatingSystem]::IsWindows())">

View File

@@ -5,6 +5,20 @@ using BMapSharp.VirtoolsTypes;
namespace BMapSharp.BMapWrapper {
/// <summary>
/// BMapSharp module specific exception.
/// </summary>
public class BMapException : Exception {
public BMapException() { }
public BMapException(string message)
: base(message) { }
public BMapException(string message, Exception inner)
: base(message, inner) { }
public static void ThrowIfFailed(bool condition) {
if (!condition) throw new BMapException("BMap operation failed.");
}
}
/// <summary>
/// The guard of native BMap environment.
/// This class initialize native BMap environment when constructing and free it when destructing.
@@ -111,8 +125,8 @@ namespace BMapSharp.BMapWrapper {
public override bool IsInvalid => this.handle == Utils.INVALID_PTR;
protected override bool ReleaseHandle() => throw new NotImplementedException();
internal bool isValid() => this.handle != Utils.INVALID_PTR;
internal IntPtr getPointer() => this.handle;
internal bool IsValid() => this.handle != Utils.INVALID_PTR;
internal IntPtr GetPointer() => this.handle;
#region IEquatable
@@ -160,9 +174,9 @@ namespace BMapSharp.BMapWrapper {
protected override bool ReleaseHandle() => throw new NotImplementedException();
private readonly uint m_CKID;
internal bool isValid() => this.handle != Utils.INVALID_PTR && m_CKID != Utils.INVALID_CKID;
internal IntPtr getPointer() => this.handle;
internal uint getCKID() => m_CKID;
internal bool IsValid() => this.handle != Utils.INVALID_PTR && m_CKID != Utils.INVALID_CKID;
internal IntPtr GetPointer() => this.handle;
internal uint GetCKID() => m_CKID;
#region IEquatable
@@ -203,13 +217,13 @@ namespace BMapSharp.BMapWrapper {
protected delegate bool FctGenericValueGetter<T>(IntPtr bmf, uint id, out T val);
protected delegate bool FctGenericValueSetter<T>(IntPtr bmf, uint id, T val);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected T getGenericValue<T>(FctGenericValueGetter<T> fct) {
BMapException.ThrowIfFailed(fct(getPointer(), getCKID(), out T out_val));
protected T GetGenericValue<T>(FctGenericValueGetter<T> fct) {
BMapException.ThrowIfFailed(fct(GetPointer(), GetCKID(), out T out_val));
return out_val;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected void setGenericValue<T>(FctGenericValueSetter<T> fct, T val) {
BMapException.ThrowIfFailed(fct(getPointer(), getCKID(), val));
protected void SetGenericValue<T>(FctGenericValueSetter<T> fct, T val) {
BMapException.ThrowIfFailed(fct(GetPointer(), GetCKID(), val));
}
#endregion
@@ -218,149 +232,159 @@ namespace BMapSharp.BMapWrapper {
public class BMObject : AbstractCKObject {
internal BMObject(IntPtr raw_pointer, uint ckid) : base(raw_pointer, ckid) { }
public string GetName() => getGenericValue<string>(BMap.BMObject_GetName);
public void SetName(string name) => setGenericValue<string>(BMap.BMObject_SetName, name);
public string GetName() => GetGenericValue<string>(BMap.BMObject_GetName);
public void SetName(string name) => SetGenericValue<string>(BMap.BMObject_SetName, name);
}
public class BMTexture : BMObject {
internal BMTexture(IntPtr raw_pointer, uint ckid) : base(raw_pointer, ckid) { }
public string GetFileName() => getGenericValue<string>(BMap.BMTexture_GetFileName);
public string GetFileName() => GetGenericValue<string>(BMap.BMTexture_GetFileName);
public void LoadImage(string filepath) {
BMapException.ThrowIfFailed(BMap.BMTexture_LoadImage(getPointer(), getCKID(), filepath));
BMapException.ThrowIfFailed(BMap.BMTexture_LoadImage(GetPointer(), GetCKID(), filepath));
}
public void SaveImage(string filepath) {
BMapException.ThrowIfFailed(BMap.BMTexture_SaveImage(getPointer(), getCKID(), filepath));
BMapException.ThrowIfFailed(BMap.BMTexture_SaveImage(GetPointer(), GetCKID(), filepath));
}
public CK_TEXTURE_SAVEOPTIONS GetSaveOptions() => getGenericValue<CK_TEXTURE_SAVEOPTIONS>(BMap.BMTexture_GetSaveOptions);
public void SetSaveOptions(CK_TEXTURE_SAVEOPTIONS opt) => setGenericValue<CK_TEXTURE_SAVEOPTIONS>(BMap.BMTexture_SetSaveOptions, opt);
public VX_PIXELFORMAT GetVideoFormat() => getGenericValue<VX_PIXELFORMAT>(BMap.BMTexture_GetVideoFormat);
public void SetVideoFormat(VX_PIXELFORMAT vfmt) => setGenericValue<VX_PIXELFORMAT>(BMap.BMTexture_SetVideoFormat, vfmt);
public CK_TEXTURE_SAVEOPTIONS GetSaveOptions() => GetGenericValue<CK_TEXTURE_SAVEOPTIONS>(BMap.BMTexture_GetSaveOptions);
public void SetSaveOptions(CK_TEXTURE_SAVEOPTIONS opt) => SetGenericValue<CK_TEXTURE_SAVEOPTIONS>(BMap.BMTexture_SetSaveOptions, opt);
public VX_PIXELFORMAT GetVideoFormat() => GetGenericValue<VX_PIXELFORMAT>(BMap.BMTexture_GetVideoFormat);
public void SetVideoFormat(VX_PIXELFORMAT vfmt) => SetGenericValue<VX_PIXELFORMAT>(BMap.BMTexture_SetVideoFormat, vfmt);
}
public class BMMaterial : BMObject {
internal BMMaterial(IntPtr raw_pointer, uint ckid) : base(raw_pointer, ckid) { }
public VxColor GetDiffuse() => getGenericValue<VxColor>(BMap.BMMaterial_GetDiffuse);
public void SetDiffuse(VxColor col) => setGenericValue<VxColor>(BMap.BMMaterial_SetDiffuse, col);
public VxColor GetAmbient() => getGenericValue<VxColor>(BMap.BMMaterial_GetAmbient);
public void SetAmbient(VxColor col) => setGenericValue<VxColor>(BMap.BMMaterial_SetAmbient, col);
public VxColor GetSpecular() => getGenericValue<VxColor>(BMap.BMMaterial_GetSpecular);
public void SetSpecular(VxColor col) => setGenericValue<VxColor>(BMap.BMMaterial_SetSpecular, col);
public VxColor GetEmissive() => getGenericValue<VxColor>(BMap.BMMaterial_GetEmissive);
public void SetEmissive(VxColor col) => setGenericValue<VxColor>(BMap.BMMaterial_SetEmissive, col);
public VxColor GetDiffuse() => GetGenericValue<VxColor>(BMap.BMMaterial_GetDiffuse);
public void SetDiffuse(VxColor col) => SetGenericValue<VxColor>(BMap.BMMaterial_SetDiffuse, col);
public VxColor GetAmbient() => GetGenericValue<VxColor>(BMap.BMMaterial_GetAmbient);
public void SetAmbient(VxColor col) => SetGenericValue<VxColor>(BMap.BMMaterial_SetAmbient, col);
public VxColor GetSpecular() => GetGenericValue<VxColor>(BMap.BMMaterial_GetSpecular);
public void SetSpecular(VxColor col) => SetGenericValue<VxColor>(BMap.BMMaterial_SetSpecular, col);
public VxColor GetEmissive() => GetGenericValue<VxColor>(BMap.BMMaterial_GetEmissive);
public void SetEmissive(VxColor col) => SetGenericValue<VxColor>(BMap.BMMaterial_SetEmissive, col);
public float GetSpecularPower() => getGenericValue<float>(BMap.BMMaterial_GetSpecularPower);
public void SetSpecularPower(float val) => setGenericValue<float>(BMap.BMMaterial_SetSpecularPower, val);
public float GetSpecularPower() => GetGenericValue<float>(BMap.BMMaterial_GetSpecularPower);
public void SetSpecularPower(float val) => SetGenericValue<float>(BMap.BMMaterial_SetSpecularPower, val);
public BMTexture GetTexture() {
BMapException.ThrowIfFailed(BMap.BMMaterial_GetTexture(GetPointer(), GetCKID(), out uint out_texid));
if (out_texid == Utils.INVALID_CKID) return null;
else return new BMTexture(GetPointer(), out_texid);
}
public void SetTexture(BMTexture tex) {
uint texid = (tex is null) ? Utils.INVALID_CKID : tex.GetCKID();
BMapException.ThrowIfFailed(BMap.BMMaterial_SetTexture(GetPointer(), GetCKID(), texid));
}
public VxColor GetTextureBorderColor() {
BMapException.ThrowIfFailed(BMap.BMMaterial_GetTextureBorderColor(getPointer(), getCKID(), out uint out_val));
BMapException.ThrowIfFailed(BMap.BMMaterial_GetTextureBorderColor(GetPointer(), GetCKID(), out uint out_val));
return new VxColor(out_val);
}
public void SetTextureBorderColor(VxColor col) {
BMapException.ThrowIfFailed(BMap.BMMaterial_SetTextureBorderColor(getPointer(), getCKID(), col.ToDword()));
BMapException.ThrowIfFailed(BMap.BMMaterial_SetTextureBorderColor(GetPointer(), GetCKID(), col.ToDword()));
}
public VXTEXTURE_BLENDMODE GetTextureBlendMode() => getGenericValue<VXTEXTURE_BLENDMODE>(BMap.BMMaterial_GetTextureBlendMode);
public void SetTextureBlendMode(VXTEXTURE_BLENDMODE val) => setGenericValue<VXTEXTURE_BLENDMODE>(BMap.BMMaterial_SetTextureBlendMode, val);
public VXTEXTURE_FILTERMODE GetTextureMinMode() => getGenericValue<VXTEXTURE_FILTERMODE>(BMap.BMMaterial_GetTextureMinMode);
public void SetTextureMinMode(VXTEXTURE_FILTERMODE val) => setGenericValue<VXTEXTURE_FILTERMODE>(BMap.BMMaterial_SetTextureMinMode, val);
public VXTEXTURE_FILTERMODE GetTextureMagMode() => getGenericValue<VXTEXTURE_FILTERMODE>(BMap.BMMaterial_GetTextureMagMode);
public void SetTextureMagMode(VXTEXTURE_FILTERMODE val) => setGenericValue<VXTEXTURE_FILTERMODE>(BMap.BMMaterial_SetTextureMagMode, val);
public VXTEXTURE_ADDRESSMODE GetTextureAddressMode() => getGenericValue<VXTEXTURE_ADDRESSMODE>(BMap.BMMaterial_GetTextureAddressMode);
public void SetTextureAddressMode(VXTEXTURE_ADDRESSMODE val) => setGenericValue<VXTEXTURE_ADDRESSMODE>(BMap.BMMaterial_SetTextureAddressMode, val);
public VXBLEND_MODE GetSourceBlend() => getGenericValue<VXBLEND_MODE>(BMap.BMMaterial_GetSourceBlend);
public void SetSourceBlend(VXBLEND_MODE val) => setGenericValue<VXBLEND_MODE>(BMap.BMMaterial_SetSourceBlend, val);
public VXBLEND_MODE GetDestBlend() => getGenericValue<VXBLEND_MODE>(BMap.BMMaterial_GetDestBlend);
public void SetDestBlend(VXBLEND_MODE val) => setGenericValue<VXBLEND_MODE>(BMap.BMMaterial_SetDestBlend, val);
public VXFILL_MODE GetFillMode() => getGenericValue<VXFILL_MODE>(BMap.BMMaterial_GetFillMode);
public void SetFillMode(VXFILL_MODE val) => setGenericValue<VXFILL_MODE>(BMap.BMMaterial_SetFillMode, val);
public VXSHADE_MODE GetShadeMode() => getGenericValue<VXSHADE_MODE>(BMap.BMMaterial_GetShadeMode);
public void SetShadeMode(VXSHADE_MODE val) => setGenericValue<VXSHADE_MODE>(BMap.BMMaterial_SetShadeMode, val);
public VXTEXTURE_BLENDMODE GetTextureBlendMode() => GetGenericValue<VXTEXTURE_BLENDMODE>(BMap.BMMaterial_GetTextureBlendMode);
public void SetTextureBlendMode(VXTEXTURE_BLENDMODE val) => SetGenericValue<VXTEXTURE_BLENDMODE>(BMap.BMMaterial_SetTextureBlendMode, val);
public VXTEXTURE_FILTERMODE GetTextureMinMode() => GetGenericValue<VXTEXTURE_FILTERMODE>(BMap.BMMaterial_GetTextureMinMode);
public void SetTextureMinMode(VXTEXTURE_FILTERMODE val) => SetGenericValue<VXTEXTURE_FILTERMODE>(BMap.BMMaterial_SetTextureMinMode, val);
public VXTEXTURE_FILTERMODE GetTextureMagMode() => GetGenericValue<VXTEXTURE_FILTERMODE>(BMap.BMMaterial_GetTextureMagMode);
public void SetTextureMagMode(VXTEXTURE_FILTERMODE val) => SetGenericValue<VXTEXTURE_FILTERMODE>(BMap.BMMaterial_SetTextureMagMode, val);
public VXTEXTURE_ADDRESSMODE GetTextureAddressMode() => GetGenericValue<VXTEXTURE_ADDRESSMODE>(BMap.BMMaterial_GetTextureAddressMode);
public void SetTextureAddressMode(VXTEXTURE_ADDRESSMODE val) => SetGenericValue<VXTEXTURE_ADDRESSMODE>(BMap.BMMaterial_SetTextureAddressMode, val);
public VXBLEND_MODE GetSourceBlend() => GetGenericValue<VXBLEND_MODE>(BMap.BMMaterial_GetSourceBlend);
public void SetSourceBlend(VXBLEND_MODE val) => SetGenericValue<VXBLEND_MODE>(BMap.BMMaterial_SetSourceBlend, val);
public VXBLEND_MODE GetDestBlend() => GetGenericValue<VXBLEND_MODE>(BMap.BMMaterial_GetDestBlend);
public void SetDestBlend(VXBLEND_MODE val) => SetGenericValue<VXBLEND_MODE>(BMap.BMMaterial_SetDestBlend, val);
public VXFILL_MODE GetFillMode() => GetGenericValue<VXFILL_MODE>(BMap.BMMaterial_GetFillMode);
public void SetFillMode(VXFILL_MODE val) => SetGenericValue<VXFILL_MODE>(BMap.BMMaterial_SetFillMode, val);
public VXSHADE_MODE GetShadeMode() => GetGenericValue<VXSHADE_MODE>(BMap.BMMaterial_GetShadeMode);
public void SetShadeMode(VXSHADE_MODE val) => SetGenericValue<VXSHADE_MODE>(BMap.BMMaterial_SetShadeMode, val);
public bool GetAlphaTestEnabled() => getGenericValue<bool>(BMap.BMMaterial_GetAlphaTestEnabled);
public void SetAlphaTestEnabled(bool val) => setGenericValue<bool>(BMap.BMMaterial_SetAlphaTestEnabled, val);
public bool GetAlphaBlendEnabled() => getGenericValue<bool>(BMap.BMMaterial_GetAlphaBlendEnabled);
public void SetAlphaBlendEnabled(bool val) => setGenericValue<bool>(BMap.BMMaterial_SetAlphaBlendEnabled, val);
public bool GetPerspectiveCorrectionEnabled() => getGenericValue<bool>(BMap.BMMaterial_GetPerspectiveCorrectionEnabled);
public void SetPerspectiveCorrectionEnabled(bool val) => setGenericValue<bool>(BMap.BMMaterial_SetPerspectiveCorrectionEnabled, val);
public bool GetZWriteEnabled() => getGenericValue<bool>(BMap.BMMaterial_GetZWriteEnabled);
public void SetZWriteEnabled(bool val) => setGenericValue<bool>(BMap.BMMaterial_SetZWriteEnabled, val);
public bool GetTwoSidedEnabled() => getGenericValue<bool>(BMap.BMMaterial_GetTwoSidedEnabled);
public void SetTwoSidedEnabled(bool val) => setGenericValue<bool>(BMap.BMMaterial_SetTwoSidedEnabled, val);
public bool GetAlphaTestEnabled() => GetGenericValue<bool>(BMap.BMMaterial_GetAlphaTestEnabled);
public void SetAlphaTestEnabled(bool val) => SetGenericValue<bool>(BMap.BMMaterial_SetAlphaTestEnabled, val);
public bool GetAlphaBlendEnabled() => GetGenericValue<bool>(BMap.BMMaterial_GetAlphaBlendEnabled);
public void SetAlphaBlendEnabled(bool val) => SetGenericValue<bool>(BMap.BMMaterial_SetAlphaBlendEnabled, val);
public bool GetPerspectiveCorrectionEnabled() => GetGenericValue<bool>(BMap.BMMaterial_GetPerspectiveCorrectionEnabled);
public void SetPerspectiveCorrectionEnabled(bool val) => SetGenericValue<bool>(BMap.BMMaterial_SetPerspectiveCorrectionEnabled, val);
public bool GetZWriteEnabled() => GetGenericValue<bool>(BMap.BMMaterial_GetZWriteEnabled);
public void SetZWriteEnabled(bool val) => SetGenericValue<bool>(BMap.BMMaterial_SetZWriteEnabled, val);
public bool GetTwoSidedEnabled() => GetGenericValue<bool>(BMap.BMMaterial_GetTwoSidedEnabled);
public void SetTwoSidedEnabled(bool val) => SetGenericValue<bool>(BMap.BMMaterial_SetTwoSidedEnabled, val);
public byte GetAlphaRef() => getGenericValue<byte>(BMap.BMMaterial_GetAlphaRef);
public void SetAlphaRef(byte val) => setGenericValue<byte>(BMap.BMMaterial_SetAlphaRef, val);
public byte GetAlphaRef() => GetGenericValue<byte>(BMap.BMMaterial_GetAlphaRef);
public void SetAlphaRef(byte val) => SetGenericValue<byte>(BMap.BMMaterial_SetAlphaRef, val);
public VXCMPFUNC GetAlphaFunc() => getGenericValue<VXCMPFUNC>(BMap.BMMaterial_GetAlphaFunc);
public void SetAlphaFunc(VXCMPFUNC val) => setGenericValue<VXCMPFUNC>(BMap.BMMaterial_SetAlphaFunc, val);
public VXCMPFUNC GetZFunc() => getGenericValue<VXCMPFUNC>(BMap.BMMaterial_GetZFunc);
public void SetZFunc(VXCMPFUNC val) => setGenericValue<VXCMPFUNC>(BMap.BMMaterial_SetZFunc, val);
public VXCMPFUNC GetAlphaFunc() => GetGenericValue<VXCMPFUNC>(BMap.BMMaterial_GetAlphaFunc);
public void SetAlphaFunc(VXCMPFUNC val) => SetGenericValue<VXCMPFUNC>(BMap.BMMaterial_SetAlphaFunc, val);
public VXCMPFUNC GetZFunc() => GetGenericValue<VXCMPFUNC>(BMap.BMMaterial_GetZFunc);
public void SetZFunc(VXCMPFUNC val) => SetGenericValue<VXCMPFUNC>(BMap.BMMaterial_SetZFunc, val);
}
public class BMMesh : BMObject {
internal BMMesh(IntPtr raw_pointer, uint ckid) : base(raw_pointer, ckid) { }
public VXMESH_LITMODE GetLitMode() => getGenericValue<VXMESH_LITMODE>(BMap.BMMesh_GetLitMode);
public void SetLitMode(VXMESH_LITMODE mode) => setGenericValue<VXMESH_LITMODE>(BMap.BMMesh_SetLitMode, mode);
public VXMESH_LITMODE GetLitMode() => GetGenericValue<VXMESH_LITMODE>(BMap.BMMesh_GetLitMode);
public void SetLitMode(VXMESH_LITMODE mode) => SetGenericValue<VXMESH_LITMODE>(BMap.BMMesh_SetLitMode, mode);
public uint GetVertexCount() => getGenericValue<uint>(BMap.BMMesh_GetVertexCount);
public void SetVertexCount(uint count) => setGenericValue<uint>(BMap.BMMesh_SetVertexCount, count);
public uint GetVertexCount() => GetGenericValue<uint>(BMap.BMMesh_GetVertexCount);
public void SetVertexCount(uint count) => SetGenericValue<uint>(BMap.BMMesh_SetVertexCount, count);
public IEnumerable<VxVector3> GetVertexPositions() {
BMapException.ThrowIfFailed(BMap.BMMesh_GetVertexPositions(getPointer(), getCKID(), out IntPtr out_mem));
BMapException.ThrowIfFailed(BMap.BMMesh_GetVertexPositions(GetPointer(), GetCKID(), out IntPtr out_mem));
return Utils.VxVector3Iterator(out_mem, GetVertexCount());
}
public void SetVertexPositions(IEnumerable<VxVector3> iem) {
BMapException.ThrowIfFailed(BMap.BMMesh_GetVertexPositions(getPointer(), getCKID(), out IntPtr out_mem));
BMapException.ThrowIfFailed(BMap.BMMesh_GetVertexPositions(GetPointer(), GetCKID(), out IntPtr out_mem));
Utils.VxVector3Assigner(out_mem, GetVertexCount(), iem);
}
public IEnumerable<VxVector3> GetVertexNormals() {
BMapException.ThrowIfFailed(BMap.BMMesh_GetVertexNormals(getPointer(), getCKID(), out IntPtr out_mem));
BMapException.ThrowIfFailed(BMap.BMMesh_GetVertexNormals(GetPointer(), GetCKID(), out IntPtr out_mem));
return Utils.VxVector3Iterator(out_mem, GetVertexCount());
}
public void SetVertexNormals(IEnumerable<VxVector3> iem) {
BMapException.ThrowIfFailed(BMap.BMMesh_GetVertexNormals(getPointer(), getCKID(), out IntPtr out_mem));
BMapException.ThrowIfFailed(BMap.BMMesh_GetVertexNormals(GetPointer(), GetCKID(), out IntPtr out_mem));
Utils.VxVector3Assigner(out_mem, GetVertexCount(), iem);
}
public IEnumerable<VxVector2> GetVertexUVs() {
BMapException.ThrowIfFailed(BMap.BMMesh_GetVertexUVs(getPointer(), getCKID(), out IntPtr out_mem));
BMapException.ThrowIfFailed(BMap.BMMesh_GetVertexUVs(GetPointer(), GetCKID(), out IntPtr out_mem));
return Utils.VxVector2Iterator(out_mem, GetVertexCount());
}
public void SetVertexUVs(IEnumerable<VxVector2> iem) {
BMapException.ThrowIfFailed(BMap.BMMesh_GetVertexUVs(getPointer(), getCKID(), out IntPtr out_mem));
BMapException.ThrowIfFailed(BMap.BMMesh_GetVertexUVs(GetPointer(), GetCKID(), out IntPtr out_mem));
Utils.VxVector2Assigner(out_mem, GetVertexCount(), iem);
}
public uint GetFaceCount() => getGenericValue<uint>(BMap.BMMesh_GetFaceCount);
public void SetFaceCount(uint count) => setGenericValue<uint>(BMap.BMMesh_SetFaceCount, count);
public uint GetFaceCount() => GetGenericValue<uint>(BMap.BMMesh_GetFaceCount);
public void SetFaceCount(uint count) => SetGenericValue<uint>(BMap.BMMesh_SetFaceCount, count);
public IEnumerable<CKShortFaceIndices> GetFaceIndices() {
BMapException.ThrowIfFailed(BMap.BMMesh_GetFaceIndices(getPointer(), getCKID(), out IntPtr out_mem));
BMapException.ThrowIfFailed(BMap.BMMesh_GetFaceIndices(GetPointer(), GetCKID(), out IntPtr out_mem));
return Utils.CKShortFaceIndicesIterator(out_mem, GetFaceCount());
}
public void SetFaceIndices(IEnumerable<CKShortFaceIndices> iem) {
BMapException.ThrowIfFailed(BMap.BMMesh_GetFaceIndices(getPointer(), getCKID(), out IntPtr out_mem));
BMapException.ThrowIfFailed(BMap.BMMesh_GetFaceIndices(GetPointer(), GetCKID(), out IntPtr out_mem));
Utils.CKShortFaceIndicesAssigner(out_mem, GetFaceCount(), iem);
}
public IEnumerable<short> GetFaceMaterialSlotIndexs() {
BMapException.ThrowIfFailed(BMap.BMMesh_GetFaceMaterialSlotIndexs(getPointer(), getCKID(), out IntPtr out_mem));
BMapException.ThrowIfFailed(BMap.BMMesh_GetFaceMaterialSlotIndexs(GetPointer(), GetCKID(), out IntPtr out_mem));
return Utils.ShortIterator(out_mem, GetFaceCount());
}
public void SetFaceMaterialSlotIndexs(IEnumerable<short> iem) {
BMapException.ThrowIfFailed(BMap.BMMesh_GetFaceMaterialSlotIndexs(getPointer(), getCKID(), out IntPtr out_mem));
BMapException.ThrowIfFailed(BMap.BMMesh_GetFaceMaterialSlotIndexs(GetPointer(), GetCKID(), out IntPtr out_mem));
Utils.ShortAssigner(out_mem, GetFaceCount(), iem);
}
public uint GetMaterialSlotCount() => getGenericValue<uint>(BMap.BMMesh_GetMaterialSlotCount);
public void SetMaterialSlotCount(uint count) => setGenericValue<uint>(BMap.BMMesh_SetMaterialSlotCount, count);
public uint GetMaterialSlotCount() => GetGenericValue<uint>(BMap.BMMesh_GetMaterialSlotCount);
public void SetMaterialSlotCount(uint count) => SetGenericValue<uint>(BMap.BMMesh_SetMaterialSlotCount, count);
public IEnumerable<BMMaterial> GetMaterialSlots() {
uint count = GetMaterialSlotCount();
for (uint i = 0; i < count; ++i) {
BMapException.ThrowIfFailed(BMap.BMMesh_GetMaterialSlot(getPointer(), getCKID(), i, out uint out_mtlid));
BMapException.ThrowIfFailed(BMap.BMMesh_GetMaterialSlot(GetPointer(), GetCKID(), i, out uint out_mtlid));
if (out_mtlid == Utils.INVALID_CKID) yield return null;
else yield return new BMMaterial(getPointer(), out_mtlid);
else yield return new BMMaterial(GetPointer(), out_mtlid);
}
}
public void SetMaterialSlots(IEnumerable<BMMaterial> iem) {
@@ -368,8 +392,8 @@ namespace BMapSharp.BMapWrapper {
var itor = iem.GetEnumerator();
for (uint i = 0; i < count; ++i) {
if (!itor.MoveNext()) throw new BMapException("The length of given material array is too short when assigning material slots.");
uint mtlid = itor.Current is null ? Utils.INVALID_CKID : itor.Current.getCKID();
BMapException.ThrowIfFailed(BMap.BMMesh_SetMaterialSlot(getPointer(), getCKID(), i, mtlid));
uint mtlid = itor.Current is null ? Utils.INVALID_CKID : itor.Current.GetCKID();
BMapException.ThrowIfFailed(BMap.BMMesh_SetMaterialSlot(GetPointer(), GetCKID(), i, mtlid));
}
}
@@ -378,21 +402,21 @@ namespace BMapSharp.BMapWrapper {
public class BM3dEntity : BMObject {
internal BM3dEntity(IntPtr raw_pointer, uint ckid) : base(raw_pointer, ckid) { }
public VxMatrix GetWorldMatrix() => getGenericValue<VxMatrix>(BMap.BM3dEntity_GetWorldMatrix);
public void SetWorldMatrix(VxMatrix mat) => setGenericValue<VxMatrix>(BMap.BM3dEntity_SetWorldMatrix, mat);
public VxMatrix GetWorldMatrix() => GetGenericValue<VxMatrix>(BMap.BM3dEntity_GetWorldMatrix);
public void SetWorldMatrix(VxMatrix mat) => SetGenericValue<VxMatrix>(BMap.BM3dEntity_SetWorldMatrix, mat);
public BMMesh GetCurrentMesh() {
BMapException.ThrowIfFailed(BMap.BM3dEntity_GetCurrentMesh(getPointer(), getCKID(), out uint out_meshid));
BMapException.ThrowIfFailed(BMap.BM3dEntity_GetCurrentMesh(GetPointer(), GetCKID(), out uint out_meshid));
if (out_meshid == Utils.INVALID_CKID) return null;
else return new BMMesh(getPointer(), out_meshid);
else return new BMMesh(GetPointer(), out_meshid);
}
public void SetCurrentMesh(BMMesh mesh) {
uint meshid = (mesh is null) ? Utils.INVALID_CKID : mesh.getCKID();
BMapException.ThrowIfFailed(BMap.BM3dEntity_SetCurrentMesh(getPointer(), getCKID(), meshid));
uint meshid = (mesh is null) ? Utils.INVALID_CKID : mesh.GetCKID();
BMapException.ThrowIfFailed(BMap.BM3dEntity_SetCurrentMesh(GetPointer(), GetCKID(), meshid));
}
public bool GetVisibility() => getGenericValue<bool>(BMap.BM3dEntity_GetVisibility);
public void SetVisibility(bool visb) => setGenericValue<bool>(BMap.BM3dEntity_SetVisibility, visb);
public bool GetVisibility() => GetGenericValue<bool>(BMap.BM3dEntity_GetVisibility);
public void SetVisibility(bool visb) => SetGenericValue<bool>(BMap.BM3dEntity_SetVisibility, visb);
}
public class BM3dObject : BM3dEntity {
@@ -402,55 +426,84 @@ namespace BMapSharp.BMapWrapper {
public class BMLight : BM3dEntity {
internal BMLight(IntPtr raw_pointer, uint ckid) : base(raw_pointer, ckid) { }
// YYC MARK:
// Name `GetType` is conflict with C# base class function name.
// So we add a `Light` prefix for it.
public VXLIGHT_TYPE GetLightType() => getGenericValue<VXLIGHT_TYPE>(BMap.BMLight_GetType);
public void SetLightType(VXLIGHT_TYPE val) => setGenericValue<VXLIGHT_TYPE>(BMap.BMLight_SetType, val);
public VXLIGHT_TYPE GetLightType() => GetGenericValue<VXLIGHT_TYPE>(BMap.BMLight_GetType);
public void SetLightType(VXLIGHT_TYPE val) => SetGenericValue<VXLIGHT_TYPE>(BMap.BMLight_SetType, val);
public VxColor GetColor() => getGenericValue<VxColor>(BMap.BMLight_GetColor);
public void SetColor(VxColor col) => setGenericValue<VxColor>(BMap.BMLight_SetColor, col);
public VxColor GetColor() => GetGenericValue<VxColor>(BMap.BMLight_GetColor);
public void SetColor(VxColor col) => SetGenericValue<VxColor>(BMap.BMLight_SetColor, col);
public float GetConstantAttenuation() => getGenericValue<float>(BMap.BMLight_GetConstantAttenuation);
public void SetConstantAttenuation(float val) => setGenericValue<float>(BMap.BMLight_SetConstantAttenuation, val);
public float GetLinearAttenuation() => getGenericValue<float>(BMap.BMLight_GetLinearAttenuation);
public void SetLinearAttenuation(float val) => setGenericValue<float>(BMap.BMLight_SetLinearAttenuation, val);
public float GetQuadraticAttenuation() => getGenericValue<float>(BMap.BMLight_GetQuadraticAttenuation);
public void SetQuadraticAttenuation(float val) => setGenericValue<float>(BMap.BMLight_SetQuadraticAttenuation, val);
public float GetConstantAttenuation() => GetGenericValue<float>(BMap.BMLight_GetConstantAttenuation);
public void SetConstantAttenuation(float val) => SetGenericValue<float>(BMap.BMLight_SetConstantAttenuation, val);
public float GetLinearAttenuation() => GetGenericValue<float>(BMap.BMLight_GetLinearAttenuation);
public void SetLinearAttenuation(float val) => SetGenericValue<float>(BMap.BMLight_SetLinearAttenuation, val);
public float GetQuadraticAttenuation() => GetGenericValue<float>(BMap.BMLight_GetQuadraticAttenuation);
public void SetQuadraticAttenuation(float val) => SetGenericValue<float>(BMap.BMLight_SetQuadraticAttenuation, val);
public float GetRange() => getGenericValue<float>(BMap.BMLight_GetRange);
public void SetRange(float val) => setGenericValue<float>(BMap.BMLight_SetRange, val);
public float GetRange() => GetGenericValue<float>(BMap.BMLight_GetRange);
public void SetRange(float val) => SetGenericValue<float>(BMap.BMLight_SetRange, val);
public float GetHotSpot() => getGenericValue<float>(BMap.BMLight_GetHotSpot);
public void SetHotSpot(float val) => setGenericValue<float>(BMap.BMLight_SetHotSpot, val);
public float GetFalloff() => getGenericValue<float>(BMap.BMLight_GetFalloff);
public void SetFalloff(float val) => setGenericValue<float>(BMap.BMLight_SetFalloff, val);
public float GetFalloffShape() => getGenericValue<float>(BMap.BMLight_GetFalloffShape);
public void SetFalloffShape(float val) => setGenericValue<float>(BMap.BMLight_SetFalloffShape, val);
public float GetHotSpot() => GetGenericValue<float>(BMap.BMLight_GetHotSpot);
public void SetHotSpot(float val) => SetGenericValue<float>(BMap.BMLight_SetHotSpot, val);
public float GetFalloff() => GetGenericValue<float>(BMap.BMLight_GetFalloff);
public void SetFalloff(float val) => SetGenericValue<float>(BMap.BMLight_SetFalloff, val);
public float GetFalloffShape() => GetGenericValue<float>(BMap.BMLight_GetFalloffShape);
public void SetFalloffShape(float val) => SetGenericValue<float>(BMap.BMLight_SetFalloffShape, val);
}
public class BMTargetLight : BMLight {
internal BMTargetLight(IntPtr raw_pointer, uint ckid) : base(raw_pointer, ckid) { }
}
public class BMCamera : BM3dEntity {
internal BMCamera(IntPtr raw_pointer, uint ckid) : base(raw_pointer, ckid) { }
public CK_CAMERA_PROJECTION GetProjectionType() => GetGenericValue<CK_CAMERA_PROJECTION>(BMap.BMCamera_GetProjectionType);
public void SetProjectionType(CK_CAMERA_PROJECTION val) => SetGenericValue<CK_CAMERA_PROJECTION>(BMap.BMCamera_SetProjectionType, val);
public float GetOrthographicZoom() => GetGenericValue<float>(BMap.BMCamera_GetOrthographicZoom);
public void SetOrthographicZoom(float val) => SetGenericValue<float>(BMap.BMCamera_SetOrthographicZoom, val);
public float GetFrontPlane() => GetGenericValue<float>(BMap.BMCamera_GetFrontPlane);
public void SetFrontPlane(float val) => SetGenericValue<float>(BMap.BMCamera_SetFrontPlane, val);
public float GetBackPlane() => GetGenericValue<float>(BMap.BMCamera_GetBackPlane);
public void SetBackPlane(float val) => SetGenericValue<float>(BMap.BMCamera_SetBackPlane, val);
public float GetFov() => GetGenericValue<float>(BMap.BMCamera_GetFov);
public void SetFov(float val) => SetGenericValue<float>(BMap.BMCamera_SetFov, val);
public void GetAspectRatio(out uint width, out uint height) {
BMapException.ThrowIfFailed(BMap.BMCamera_GetAspectRatio(GetPointer(), GetCKID(), out width, out height));
}
public void SetAspectRatio(uint width, uint height) {
BMapException.ThrowIfFailed(BMap.BMCamera_SetAspectRatio(GetPointer(), GetCKID(), width, height));
}
}
public class BMTargetCamera: BMCamera {
internal BMTargetCamera(IntPtr raw_pointer, uint ckid) : base(raw_pointer, ckid) { }
}
public class BMGroup : BMObject {
internal BMGroup(IntPtr raw_pointer, uint ckid) : base(raw_pointer, ckid) { }
public void AddObject(BM3dObject member) {
BMapException.ThrowIfFailed(BMap.BMGroup_AddObject(getPointer(), getCKID(), member.getCKID()));
BMapException.ThrowIfFailed(BMap.BMGroup_AddObject(GetPointer(), GetCKID(), member.GetCKID()));
}
public uint GetObjectCount() => getGenericValue<uint>(BMap.BMGroup_GetObjectCount);
public uint GetObjectCount() => GetGenericValue<uint>(BMap.BMGroup_GetObjectCount);
public IEnumerable<BM3dObject> GetObjects() {
var size = GetObjectCount();
for (uint i = 0; i < size; ++i) {
BMapException.ThrowIfFailed(BMap.BMGroup_GetObject(getPointer(), getCKID(), i, out uint out_objid));
yield return new BM3dObject(getPointer(), out_objid);
BMapException.ThrowIfFailed(BMap.BMGroup_GetObject(GetPointer(), GetCKID(), i, out uint out_objid));
yield return new BM3dObject(GetPointer(), out_objid);
}
}
}
public sealed class BMFileReader : AbstractPointer {
private static IntPtr allocateHandle(string file_name, string temp_folder, string texture_folder, string[] encodings) {
private static IntPtr AllocateHandle(string file_name, string temp_folder, string texture_folder, string[] encodings) {
BMapException.ThrowIfFailed(BMap.BMFile_Load(
file_name, temp_folder, texture_folder,
Utils.BMapSharpCallback,
@@ -460,55 +513,59 @@ namespace BMapSharp.BMapWrapper {
return out_file;
}
protected override bool ReleaseHandle() {
return BMap.BMFile_Free(this.getPointer());
return BMap.BMFile_Free(this.GetPointer());
}
public BMFileReader(string file_name, string temp_folder, string texture_folder, string[] encodings)
: base(allocateHandle(file_name, temp_folder, texture_folder, encodings)) { }
: base(AllocateHandle(file_name, temp_folder, texture_folder, encodings)) { }
private delegate bool FctProtoGetCount(IntPtr bmf, out uint cnt);
private delegate bool FctProtoGetObject(IntPtr bmf, uint idx, out uint id);
private delegate T FctProtoCreateInstance<T>(IntPtr bmf, uint id);
private uint getCKObjectCount(FctProtoGetCount fct_cnt) {
BMapException.ThrowIfFailed(fct_cnt(this.getPointer(), out uint out_count));
private uint GetGenericObjectCount(FctProtoGetCount fct_cnt) {
BMapException.ThrowIfFailed(fct_cnt(this.GetPointer(), out uint out_count));
return out_count;
}
private IEnumerable<T> getCKObjects<T>(FctProtoGetCount fct_cnt, FctProtoGetObject fct_obj, FctProtoCreateInstance<T> fct_crt) {
uint count = getCKObjectCount(fct_cnt);
private IEnumerable<T> GetGenericObjects<T>(FctProtoGetCount fct_cnt, FctProtoGetObject fct_obj, FctProtoCreateInstance<T> fct_crt) {
uint count = GetGenericObjectCount(fct_cnt);
for (uint i = 0; i < count; ++i) {
BMapException.ThrowIfFailed(fct_obj(this.getPointer(), i, out uint out_id));
yield return fct_crt(this.getPointer(), out_id);
BMapException.ThrowIfFailed(fct_obj(this.GetPointer(), i, out uint out_id));
yield return fct_crt(this.GetPointer(), out_id);
}
}
public uint GetTextureCount() =>
getCKObjectCount(BMap.BMFile_GetTextureCount);
GetGenericObjectCount(BMap.BMFile_GetTextureCount);
public IEnumerable<BMTexture> GetTextures() =>
getCKObjects<BMTexture>(BMap.BMFile_GetTextureCount, BMap.BMFile_GetTexture, (bmf, id) => new BMTexture(bmf, id));
GetGenericObjects<BMTexture>(BMap.BMFile_GetTextureCount, BMap.BMFile_GetTexture, (bmf, id) => new BMTexture(bmf, id));
public uint GetMaterialCount() =>
getCKObjectCount(BMap.BMFile_GetMaterialCount);
GetGenericObjectCount(BMap.BMFile_GetMaterialCount);
public IEnumerable<BMMaterial> GetMaterials() =>
getCKObjects<BMMaterial>(BMap.BMFile_GetMaterialCount, BMap.BMFile_GetMaterial, (bmf, id) => new BMMaterial(bmf, id));
GetGenericObjects<BMMaterial>(BMap.BMFile_GetMaterialCount, BMap.BMFile_GetMaterial, (bmf, id) => new BMMaterial(bmf, id));
public uint GetMeshCount() =>
getCKObjectCount(BMap.BMFile_GetMeshCount);
GetGenericObjectCount(BMap.BMFile_GetMeshCount);
public IEnumerable<BMMesh> GetMeshes() =>
getCKObjects<BMMesh>(BMap.BMFile_GetMeshCount, BMap.BMFile_GetMesh, (bmf, id) => new BMMesh(bmf, id));
GetGenericObjects<BMMesh>(BMap.BMFile_GetMeshCount, BMap.BMFile_GetMesh, (bmf, id) => new BMMesh(bmf, id));
public uint Get3dObjectCount() =>
getCKObjectCount(BMap.BMFile_Get3dObjectCount);
GetGenericObjectCount(BMap.BMFile_Get3dObjectCount);
public IEnumerable<BM3dObject> Get3dObjects() =>
getCKObjects<BM3dObject>(BMap.BMFile_Get3dObjectCount, BMap.BMFile_Get3dObject, (bmf, id) => new BM3dObject(bmf, id));
GetGenericObjects<BM3dObject>(BMap.BMFile_Get3dObjectCount, BMap.BMFile_Get3dObject, (bmf, id) => new BM3dObject(bmf, id));
public uint GetGroupCount() =>
getCKObjectCount(BMap.BMFile_GetGroupCount);
GetGenericObjectCount(BMap.BMFile_GetGroupCount);
public IEnumerable<BMGroup> GetGroups() =>
getCKObjects<BMGroup>(BMap.BMFile_GetGroupCount, BMap.BMFile_GetGroup, (bmf, id) => new BMGroup(bmf, id));
GetGenericObjects<BMGroup>(BMap.BMFile_GetGroupCount, BMap.BMFile_GetGroup, (bmf, id) => new BMGroup(bmf, id));
public uint GetTargetLightCount() =>
getCKObjectCount(BMap.BMFile_GetTargetLightCount);
GetGenericObjectCount(BMap.BMFile_GetTargetLightCount);
public IEnumerable<BMTargetLight> GetTargetLights() =>
getCKObjects<BMTargetLight>(BMap.BMFile_GetTargetLightCount, BMap.BMFile_GetTargetLight, (bmf, id) => new BMTargetLight(bmf, id));
GetGenericObjects<BMTargetLight>(BMap.BMFile_GetTargetLightCount, BMap.BMFile_GetTargetLight, (bmf, id) => new BMTargetLight(bmf, id));
public uint GetTargetCameraCount() =>
GetGenericObjectCount(BMap.BMFile_GetTargetCameraCount);
public IEnumerable<BMTargetCamera> GetTargetCameras() =>
GetGenericObjects<BMTargetCamera>(BMap.BMFile_GetTargetCameraCount, BMap.BMFile_GetTargetCamera, (bmf, id) => new BMTargetCamera(bmf, id));
}
public sealed class BMFileWriter : AbstractPointer {
private static IntPtr allocateHandle(string temp_folder, string texture_folder, string[] encodings) {
private static IntPtr AllocateHandle(string temp_folder, string texture_folder, string[] encodings) {
BMapException.ThrowIfFailed(BMap.BMFile_Create(
temp_folder, texture_folder,
Utils.BMapSharpCallback,
@@ -518,14 +575,14 @@ namespace BMapSharp.BMapWrapper {
return out_file;
}
protected override bool ReleaseHandle() {
return BMap.BMFile_Free(this.getPointer());
return BMap.BMFile_Free(this.GetPointer());
}
public BMFileWriter(string temp_folder, string texture_folder, string[] encodings)
: base(allocateHandle(temp_folder, texture_folder, encodings)) { }
: base(AllocateHandle(temp_folder, texture_folder, encodings)) { }
public void Save(string filename, CK_TEXTURE_SAVEOPTIONS texture_save_opt, bool use_compress, int compress_level) {
BMapException.ThrowIfFailed(BMap.BMFile_Save(
getPointer(),
GetPointer(),
filename,
texture_save_opt,
use_compress,
@@ -535,76 +592,78 @@ namespace BMapSharp.BMapWrapper {
private delegate bool FctProtoCreateObject(IntPtr bmf, out uint id);
private delegate T FctProtoCreateInstance<T>(IntPtr bmf, uint id);
private T createCKObject<T>(FctProtoCreateObject fct_crt, FctProtoCreateInstance<T> fct_inst) {
BMapException.ThrowIfFailed(fct_crt(this.getPointer(), out uint out_id));
return fct_inst(this.getPointer(), out_id);
private T CreateGenericObject<T>(FctProtoCreateObject fct_crt, FctProtoCreateInstance<T> fct_inst) {
BMapException.ThrowIfFailed(fct_crt(this.GetPointer(), out uint out_id));
return fct_inst(this.GetPointer(), out_id);
}
public BMTexture CreateTexture() => createCKObject<BMTexture>(BMap.BMFile_CreateTexture, (bmf, id) => new BMTexture(bmf, id));
public BMMaterial CreateMaterial() => createCKObject<BMMaterial>(BMap.BMFile_CreateMaterial, (bmf, id) => new BMMaterial(bmf, id));
public BMMesh CreateMesh() => createCKObject<BMMesh>(BMap.BMFile_CreateMesh, (bmf, id) => new BMMesh(bmf, id));
public BM3dObject Create3dObject() => createCKObject<BM3dObject>(BMap.BMFile_Create3dObject, (bmf, id) => new BM3dObject(bmf, id));
public BMGroup CreateGroup() => createCKObject<BMGroup>(BMap.BMFile_CreateGroup, (bmf, id) => new BMGroup(bmf, id));
public BMTargetLight CreateTargetLight() => createCKObject<BMTargetLight>(BMap.BMFile_CreateTargetLight, (bmf, id) => new BMTargetLight(bmf, id));
public BMTexture CreateTexture() => CreateGenericObject<BMTexture>(BMap.BMFile_CreateTexture, (bmf, id) => new BMTexture(bmf, id));
public BMMaterial CreateMaterial() => CreateGenericObject<BMMaterial>(BMap.BMFile_CreateMaterial, (bmf, id) => new BMMaterial(bmf, id));
public BMMesh CreateMesh() => CreateGenericObject<BMMesh>(BMap.BMFile_CreateMesh, (bmf, id) => new BMMesh(bmf, id));
public BM3dObject Create3dObject() => CreateGenericObject<BM3dObject>(BMap.BMFile_Create3dObject, (bmf, id) => new BM3dObject(bmf, id));
public BMGroup CreateGroup() => CreateGenericObject<BMGroup>(BMap.BMFile_CreateGroup, (bmf, id) => new BMGroup(bmf, id));
public BMTargetLight CreateTargetLight() => CreateGenericObject<BMTargetLight>(BMap.BMFile_CreateTargetLight, (bmf, id) => new BMTargetLight(bmf, id));
public BMTargetCamera CreateTargetCamera() => CreateGenericObject<BMTargetCamera>(BMap.BMFile_CreateTargetCamera, (bmf, id) => new BMTargetCamera(bmf, id));
}
public sealed class BMMeshTrans : AbstractPointer {
private static IntPtr allocateHandle() {
private static IntPtr AllocateHandle() {
BMapException.ThrowIfFailed(BMap.BMMeshTrans_New(out IntPtr out_trans));
return out_trans;
}
protected override bool ReleaseHandle() {
return BMap.BMMeshTrans_Delete(this.getPointer());
return BMap.BMMeshTrans_Delete(this.GetPointer());
}
public BMMeshTrans() : base(allocateHandle()) { }
public BMMeshTrans() : base(AllocateHandle()) { }
public void Parse(BMMesh objmesh) {
BMapException.ThrowIfFailed(BMap.BMMeshTrans_Parse(
getPointer(),
objmesh.getPointer(),
objmesh.getCKID()
GetPointer(),
objmesh.GetPointer(),
objmesh.GetCKID()
));
}
public void PrepareVertex(uint count, IEnumerable<VxVector3> iem) {
// Prepare count first
BMapException.ThrowIfFailed(BMap.BMMeshTrans_PrepareVertexCount(getPointer(), count));
BMapException.ThrowIfFailed(BMap.BMMeshTrans_PrepareVertexCount(GetPointer(), count));
// Then put data
BMapException.ThrowIfFailed(BMap.BMMeshTrans_PrepareVertex(getPointer(), out IntPtr out_mem));
BMapException.ThrowIfFailed(BMap.BMMeshTrans_PrepareVertex(GetPointer(), out IntPtr out_mem));
Utils.VxVector3Assigner(out_mem, count, iem);
}
public void PrepareNormal(uint count, IEnumerable<VxVector3> iem) {
// Prepare count first
BMapException.ThrowIfFailed(BMap.BMMeshTrans_PrepareNormalCount(getPointer(), count));
BMapException.ThrowIfFailed(BMap.BMMeshTrans_PrepareNormalCount(GetPointer(), count));
// Then put data
BMapException.ThrowIfFailed(BMap.BMMeshTrans_PrepareNormal(getPointer(), out IntPtr out_mem));
BMapException.ThrowIfFailed(BMap.BMMeshTrans_PrepareNormal(GetPointer(), out IntPtr out_mem));
Utils.VxVector3Assigner(out_mem, count, iem);
}
public void PrepareUV(uint count, IEnumerable<VxVector2> iem) {
// Prepare count first
BMapException.ThrowIfFailed(BMap.BMMeshTrans_PrepareUVCount(getPointer(), count));
BMapException.ThrowIfFailed(BMap.BMMeshTrans_PrepareUVCount(GetPointer(), count));
// Then put data
BMapException.ThrowIfFailed(BMap.BMMeshTrans_PrepareUV(getPointer(), out IntPtr out_mem));
BMapException.ThrowIfFailed(BMap.BMMeshTrans_PrepareUV(GetPointer(), out IntPtr out_mem));
Utils.VxVector2Assigner(out_mem, count, iem);
}
public void PrepareMtlSlot(uint count, IEnumerable<BMMaterial> iem) {
// Prepare count first
BMapException.ThrowIfFailed(BMap.BMMeshTrans_PrepareMtlSlotCount(getPointer(), count));
BMapException.ThrowIfFailed(BMap.BMMeshTrans_PrepareMtlSlotCount(GetPointer(), count));
// Then put data
BMapException.ThrowIfFailed(BMap.BMMeshTrans_PrepareMtlSlot(getPointer(), out IntPtr out_mem));
var cast_iem = iem.Select((mtl) => mtl is null ? Utils.INVALID_CKID : mtl.getCKID());
BMapException.ThrowIfFailed(BMap.BMMeshTrans_PrepareMtlSlot(GetPointer(), out IntPtr out_mem));
var cast_iem = iem.Select((mtl) => mtl is null ? Utils.INVALID_CKID : mtl.GetCKID());
Utils.CKIDAssigner(out_mem, count, cast_iem);
}
public void PrepareFace(uint count, IEnumerable<CKFaceIndices> vec_idx, IEnumerable<CKFaceIndices> nml_idx, IEnumerable<CKFaceIndices> uv_idx, IEnumerable<uint> mtl_idx) {
// Prepare count first
BMapException.ThrowIfFailed(BMap.BMMeshTrans_PrepareFaceCount(getPointer(), count));
BMapException.ThrowIfFailed(BMap.BMMeshTrans_PrepareFaceCount(GetPointer(), count));
// Get data address
BMapException.ThrowIfFailed(BMap.BMMeshTrans_PrepareFaceVertexIndices(getPointer(), out IntPtr raw_vec_idx));
BMapException.ThrowIfFailed(BMap.BMMeshTrans_PrepareFaceNormalIndices(getPointer(), out IntPtr raw_nml_idx));
BMapException.ThrowIfFailed(BMap.BMMeshTrans_PrepareFaceUVIndices(getPointer(), out IntPtr raw_uv_idx));
BMapException.ThrowIfFailed(BMap.BMMeshTrans_PrepareFaceMtlSlot(getPointer(), out IntPtr raw_mtl_idx));
BMapException.ThrowIfFailed(BMap.BMMeshTrans_PrepareFaceVertexIndices(GetPointer(), out IntPtr raw_vec_idx));
BMapException.ThrowIfFailed(BMap.BMMeshTrans_PrepareFaceNormalIndices(GetPointer(), out IntPtr raw_nml_idx));
BMapException.ThrowIfFailed(BMap.BMMeshTrans_PrepareFaceUVIndices(GetPointer(), out IntPtr raw_uv_idx));
BMapException.ThrowIfFailed(BMap.BMMeshTrans_PrepareFaceMtlSlot(GetPointer(), out IntPtr raw_mtl_idx));
// Assign data
Utils.CKFaceIndicesAssigner(raw_vec_idx, count, vec_idx);
Utils.CKFaceIndicesAssigner(raw_nml_idx, count, nml_idx);

View File

@@ -4,6 +4,8 @@ using System.Numerics;
namespace BMapSharp.VirtoolsTypes {
#region Structures
// NOTE: Structures defined in there is only served for marshaling.
// You should not use them in hash set or anything else,
// because they do not have proper hash function and compare function.
@@ -183,129 +185,454 @@ namespace BMapSharp.VirtoolsTypes {
}
}
#endregion
#region Enums
/// <summary>
/// Specify the way textures or sprites will be saved
/// </summary>
public enum CK_TEXTURE_SAVEOPTIONS : uint {
CKTEXTURE_RAWDATA = 0, /**< Save raw data inside file. The bitmap is saved in a raw 32 bit per pixel format. */
CKTEXTURE_EXTERNAL = 1, /**< Store only the file name for the texture. The bitmap file must be present in the bitmap paths when loading the composition. */
CKTEXTURE_IMAGEFORMAT = 2, /**< Save using format specified. The bitmap data will be converted to the specified format by the correspondant bitmap plugin and saved inside file. */
CKTEXTURE_USEGLOBAL = 3, /**< Use Global settings, that is the settings given with CKContext::SetGlobalImagesSaveOptions. (Not valid when using CKContext::SetImagesSaveOptions). */
CKTEXTURE_INCLUDEORIGINALFILE = 4, /**< Insert original image file inside CMO file. The bitmap file that was used originally for the texture or sprite will be append to the composition file and extracted when the file is loaded. */
}
/// <summary>
/// Save raw data inside file. The bitmap is saved in a raw 32 bit per pixel format.
/// </summary>
CKTEXTURE_RAWDATA = 0,
/// <summary>
/// Store only the file name for the texture. The bitmap file must be present in the bitmap pathswhen loading the composition.
/// </summary>
CKTEXTURE_EXTERNAL = 1,
/// <summary>
/// Save using format specified. The bitmap data will be converted to thespecified format by the correspondant bitmap plugin and saved inside file.
/// </summary>
CKTEXTURE_IMAGEFORMAT = 2,
/// <summary>
/// Use Global settings, that is the settings given with CKContext::SetGlobalImagesSaveOptions. (Not valid when using CKContext::SetImagesSaveOptions).
/// </summary>
CKTEXTURE_USEGLOBAL = 3,
/// <summary>
/// Insert original image file inside CMO file. The bitmap file thatwas used originally for the texture or sprite will be append tothe composition file and extracted when the file is loaded.
/// </summary>
CKTEXTURE_INCLUDEORIGINALFILE = 4,
};
/// <summary>
/// Pixel format types.
/// </summary>
public enum VX_PIXELFORMAT : uint {
UNKNOWN_PF = 0, /**< Unknown pixel format */
_32_ARGB8888 = 1, /**< 32-bit ARGB pixel format with alpha */
_32_RGB888 = 2, /**< 32-bit RGB pixel format without alpha */
_24_RGB888 = 3, /**< 24-bit RGB pixel format */
_16_RGB565 = 4, /**< 16-bit RGB pixel format */
_16_RGB555 = 5, /**< 16-bit RGB pixel format (5 bits per color) */
_16_ARGB1555 = 6, /**< 16-bit ARGB pixel format (5 bits per color + 1 bit for alpha) */
_16_ARGB4444 = 7, /**< 16-bit ARGB pixel format (4 bits per color) */
_8_RGB332 = 8, /**< 8-bit RGB pixel format */
_8_ARGB2222 = 9, /**< 8-bit ARGB pixel format */
_32_ABGR8888 = 10, /**< 32-bit ABGR pixel format */
_32_RGBA8888 = 11, /**< 32-bit RGBA pixel format */
_32_BGRA8888 = 12, /**< 32-bit BGRA pixel format */
_32_BGR888 = 13, /**< 32-bit BGR pixel format */
_24_BGR888 = 14, /**< 24-bit BGR pixel format */
_16_BGR565 = 15, /**< 16-bit BGR pixel format */
_16_BGR555 = 16, /**< 16-bit BGR pixel format (5 bits per color) */
_16_ABGR1555 = 17, /**< 16-bit ABGR pixel format (5 bits per color + 1 bit for alpha) */
_16_ABGR4444 = 18, /**< 16-bit ABGR pixel format (4 bits per color) */
_DXT1 = 19, /**< S3/DirectX Texture Compression 1 */
_DXT2 = 20, /**< S3/DirectX Texture Compression 2 */
_DXT3 = 21, /**< S3/DirectX Texture Compression 3 */
_DXT4 = 22, /**< S3/DirectX Texture Compression 4 */
_DXT5 = 23, /**< S3/DirectX Texture Compression 5 */
_16_V8U8 = 24, /**< 16-bit Bump Map format format (8 bits per color) */
_32_V16U16 = 25, /**< 32-bit Bump Map format format (16 bits per color) */
_16_L6V5U5 = 26, /**< 16-bit Bump Map format format with luminance */
_32_X8L8V8U8 = 27, /**< 32-bit Bump Map format format with luminance */
_8_ABGR8888_CLUT = 28, /**< 8 bits indexed CLUT (ABGR) */
_8_ARGB8888_CLUT = 29, /**< 8 bits indexed CLUT (ARGB) */
_4_ABGR8888_CLUT = 30, /**< 4 bits indexed CLUT (ABGR) */
_4_ARGB8888_CLUT = 31, /**< 4 bits indexed CLUT (ARGB) */
}
/// <summary>
/// Unknown pixel format
/// </summary>
UNKNOWN_PF = 0,
/// <summary>
/// 32-bit ARGB pixel format with alpha
/// </summary>
_32_ARGB8888 = 1,
/// <summary>
/// 32-bit RGB pixel format without alpha
/// </summary>
_32_RGB888 = 2,
/// <summary>
/// 24-bit RGB pixel format
/// </summary>
_24_RGB888 = 3,
/// <summary>
/// 16-bit RGB pixel format
/// </summary>
_16_RGB565 = 4,
/// <summary>
/// 16-bit RGB pixel format (5 bits per color)
/// </summary>
_16_RGB555 = 5,
/// <summary>
/// 16-bit ARGB pixel format (5 bits per color + 1 bit for alpha)
/// </summary>
_16_ARGB1555 = 6,
/// <summary>
/// 16-bit ARGB pixel format (4 bits per color)
/// </summary>
_16_ARGB4444 = 7,
/// <summary>
/// 8-bit RGB pixel format
/// </summary>
_8_RGB332 = 8,
/// <summary>
/// 8-bit ARGB pixel format
/// </summary>
_8_ARGB2222 = 9,
/// <summary>
/// 32-bit ABGR pixel format
/// </summary>
_32_ABGR8888 = 10,
/// <summary>
/// 32-bit RGBA pixel format
/// </summary>
_32_RGBA8888 = 11,
/// <summary>
/// 32-bit BGRA pixel format
/// </summary>
_32_BGRA8888 = 12,
/// <summary>
/// 32-bit BGR pixel format
/// </summary>
_32_BGR888 = 13,
/// <summary>
/// 24-bit BGR pixel format
/// </summary>
_24_BGR888 = 14,
/// <summary>
/// 16-bit BGR pixel format
/// </summary>
_16_BGR565 = 15,
/// <summary>
/// 16-bit BGR pixel format (5 bits per color)
/// </summary>
_16_BGR555 = 16,
/// <summary>
/// 16-bit ABGR pixel format (5 bits per color + 1 bit for alpha)
/// </summary>
_16_ABGR1555 = 17,
/// <summary>
/// 16-bit ABGR pixel format (4 bits per color)
/// </summary>
_16_ABGR4444 = 18,
/// <summary>
/// S3/DirectX Texture Compression 1
/// </summary>
_DXT1 = 19,
/// <summary>
/// S3/DirectX Texture Compression 2
/// </summary>
_DXT2 = 20,
/// <summary>
/// S3/DirectX Texture Compression 3
/// </summary>
_DXT3 = 21,
/// <summary>
/// S3/DirectX Texture Compression 4
/// </summary>
_DXT4 = 22,
/// <summary>
/// S3/DirectX Texture Compression 5
/// </summary>
_DXT5 = 23,
/// <summary>
/// 16-bit Bump Map format format (8 bits per color)
/// </summary>
_16_V8U8 = 24,
/// <summary>
/// 32-bit Bump Map format format (16 bits per color)
/// </summary>
_32_V16U16 = 25,
/// <summary>
/// 16-bit Bump Map format format with luminance
/// </summary>
_16_L6V5U5 = 26,
/// <summary>
/// 32-bit Bump Map format format with luminance
/// </summary>
_32_X8L8V8U8 = 27,
/// <summary>
/// 8 bits indexed CLUT (ABGR)
/// </summary>
_8_ABGR8888_CLUT = 28,
/// <summary>
/// 8 bits indexed CLUT (ARGB)
/// </summary>
_8_ARGB8888_CLUT = 29,
/// <summary>
/// 4 bits indexed CLUT (ABGR)
/// </summary>
_4_ABGR8888_CLUT = 30,
/// <summary>
/// 4 bits indexed CLUT (ARGB)
/// </summary>
_4_ARGB8888_CLUT = 31,
};
/// <summary>
/// Light type.
/// </summary>
public enum VXLIGHT_TYPE : uint {
VX_LIGHTPOINT = 1, /**< The Light is a point of light */
VX_LIGHTSPOT = 2, /**< The light is a spotlight */
VX_LIGHTDIREC = 3, /**< The light is directional light : Lights comes from an infinite point so only direction of light can be given */
// VX_LIGHTPARA = 4UL, /**< Obsolete, do not use */
}
/// <summary>
/// The Light is a point of light
/// </summary>
VX_LIGHTPOINT = 1U,
/// <summary>
/// The light is a spotlight
/// </summary>
VX_LIGHTSPOT = 2U,
/// <summary>
/// The light is directional light : Lights comes from an infinite point so only direction of light can be given
/// </summary>
VX_LIGHTDIREC = 3U,
// /// <summary>
// /// Obsolete, do not use
// /// </summary>
// VX_LIGHTPARA = 4U,
};
/// <summary>
/// Blend Mode Flags
/// </summary>
public enum VXTEXTURE_BLENDMODE : uint {
VXTEXTUREBLEND_DECAL = 1, /**< Texture replace any material information */
VXTEXTUREBLEND_MODULATE = 2, /**< Texture and material are combine. Alpha information of the texture replace material alpha component. */
VXTEXTUREBLEND_DECALALPHA = 3, /**< Alpha information in the texture specify how material and texture are combined. Alpha information of the texture replace material alpha component. */
VXTEXTUREBLEND_MODULATEALPHA = 4, /**< Alpha information in the texture specify how material and texture are combined */
VXTEXTUREBLEND_DECALMASK = 5,
VXTEXTUREBLEND_MODULATEMASK = 6,
VXTEXTUREBLEND_COPY = 7, /**< Equivalent to DECAL */
VXTEXTUREBLEND_ADD = 8,
VXTEXTUREBLEND_DOTPRODUCT3 = 9, /**< Perform a Dot Product 3 between texture (normal map) and a referential vector given in VXRENDERSTATE_TEXTUREFACTOR. */
VXTEXTUREBLEND_MAX = 10,
}
/// <summary>
/// Texture replace any material information
/// </summary>
VXTEXTUREBLEND_DECAL = 1U,
/// <summary>
/// Texture and material are combine. Alpha information of the texture replace material alpha component.
/// </summary>
VXTEXTUREBLEND_MODULATE = 2U,
/// <summary>
/// Alpha information in the texture specify how material and texture are combined. Alpha information of the texture replace material alpha component.
/// </summary>
VXTEXTUREBLEND_DECALALPHA = 3U,
/// <summary>
/// Alpha information in the texture specify how material and texture are combined
/// </summary>
VXTEXTUREBLEND_MODULATEALPHA = 4U,
VXTEXTUREBLEND_DECALMASK = 5U,
VXTEXTUREBLEND_MODULATEMASK = 6U,
/// <summary>
/// Equivalent to DECAL
/// </summary>
VXTEXTUREBLEND_COPY = 7U,
VXTEXTUREBLEND_ADD = 8U,
/// <summary>
/// Perform a Dot Product 3 between texture (normal map)and a referential vector given in VXRENDERSTATE_TEXTUREFACTOR.
/// </summary>
VXTEXTUREBLEND_DOTPRODUCT3 = 9U,
VXTEXTUREBLEND_MAX = 10U,
// VXTEXTUREBLEND_MASK = 0xFU,
};
/// <summary>
/// Filter Mode Options
/// </summary>
[Flags]
public enum VXTEXTURE_FILTERMODE : uint {
VXTEXTUREFILTER_NEAREST = 1, /**< No Filter */
VXTEXTUREFILTER_LINEAR = 2, /**< Bilinear Interpolation */
VXTEXTUREFILTER_MIPNEAREST = 3, /**< Mip mapping */
VXTEXTUREFILTER_MIPLINEAR = 4, /**< Mip Mapping with Bilinear interpolation */
VXTEXTUREFILTER_LINEARMIPNEAREST = 5, /**< Mip Mapping with Bilinear interpolation between mipmap levels. */
VXTEXTUREFILTER_LINEARMIPLINEAR = 6, /**< Trilinear Filtering */
VXTEXTUREFILTER_ANISOTROPIC = 7, /**< Anisotropic filtering */
}
/// <summary>
/// No Filter
/// </summary>
VXTEXTUREFILTER_NEAREST = 1U,
/// <summary>
/// Bilinear Interpolation
/// </summary>
VXTEXTUREFILTER_LINEAR = 2U,
/// <summary>
/// Mip mapping
/// </summary>
VXTEXTUREFILTER_MIPNEAREST = 3U,
/// <summary>
/// Mip Mapping with Bilinear interpolation
/// </summary>
VXTEXTUREFILTER_MIPLINEAR = 4U,
/// <summary>
/// Mip Mapping with Bilinear interpolation between mipmap levels.
/// </summary>
VXTEXTUREFILTER_LINEARMIPNEAREST = 5U,
/// <summary>
/// Trilinear Filtering
/// </summary>
VXTEXTUREFILTER_LINEARMIPLINEAR = 6U,
/// <summary>
/// Anisotropic filtering
/// </summary>
VXTEXTUREFILTER_ANISOTROPIC = 7U,
// VXTEXTUREFILTER_MASK = 0xFU,
};
/// <summary>
/// Texture addressing modes.
/// </summary>
public enum VXTEXTURE_ADDRESSMODE : uint {
VXTEXTURE_ADDRESSWRAP = 1, /**< Default mesh wrap mode is used (see CKMesh::SetWrapMode) */
VXTEXTURE_ADDRESSMIRROR = 2, /**< Texture coordinates outside the range [0..1] are flipped evenly. */
VXTEXTURE_ADDRESSCLAMP = 3, /**< Texture coordinates greater than 1.0 are set to 1.0, and values less than 0.0 are set to 0.0. */
VXTEXTURE_ADDRESSBORDER = 4, /**< When texture coordinates are greater than 1.0 or less than 0.0 texture is set to a color defined in CKMaterial::SetTextureBorderColor. */
VXTEXTURE_ADDRESSMIRRORONCE = 5, /**< */
/// <summary>
/// Default mesh wrap mode is used (see CKMesh::SetWrapMode)
/// </summary>
VXTEXTURE_ADDRESSWRAP = 1U,
/// <summary>
/// Texture coordinates outside the range [0..1] are flipped evenly.
/// </summary>
VXTEXTURE_ADDRESSMIRROR = 2U,
/// <summary>
/// Texture coordinates greater than 1.0 are set to 1.0, and values less than 0.0 are set to 0.0.
/// </summary>
VXTEXTURE_ADDRESSCLAMP = 3U,
/// <summary>
/// When texture coordinates are greater than 1.0 or less than 0.0 texture is set to a color defined in CKMaterial::SetTextureBorderColor.
/// </summary>
VXTEXTURE_ADDRESSBORDER = 4U,
/// <summary>
///
/// </summary>
VXTEXTURE_ADDRESSMIRRORONCE = 5U,
/// <summary>
/// mask for all values
/// </summary>
// VXTEXTURE_ADDRESSMASK = 0x7U,
}
/// <summary>
/// Blending Mode options
/// </summary>
public enum VXBLEND_MODE : uint {
VXBLEND_ZERO = 1, /**< Blend factor is (0, 0, 0, 0). */
VXBLEND_ONE = 2, /**< Blend factor is (1, 1, 1, 1). */
VXBLEND_SRCCOLOR = 3, /**< Blend factor is (Rs, Gs, Bs, As). */
VXBLEND_INVSRCCOLOR = 4, /**< Blend factor is (1-Rs, 1-Gs, 1-Bs, 1-As). */
VXBLEND_SRCALPHA = 5, /**< Blend factor is (As, As, As, As). */
VXBLEND_INVSRCALPHA = 6, /**< Blend factor is (1-As, 1-As, 1-As, 1-As). */
VXBLEND_DESTALPHA = 7, /**< Blend factor is (Ad, Ad, Ad, Ad). */
VXBLEND_INVDESTALPHA = 8, /**< Blend factor is (1-Ad, 1-Ad, 1-Ad, 1-Ad). */
VXBLEND_DESTCOLOR = 9, /**< Blend factor is (Rd, Gd, Bd, Ad). */
VXBLEND_INVDESTCOLOR = 10, /**< Blend factor is (1-Rd, 1-Gd, 1-Bd, 1-Ad). */
VXBLEND_SRCALPHASAT = 11, /**< Blend factor is (f, f, f, 1); f = min(As, 1-Ad). */
// VXBLEND_BOTHSRCALPHA = 12, /**< Source blend factor is (As, As, As, As) and destination blend factor is (1-As, 1-As, 1-As, 1-As) */
// VXBLEND_BOTHINVSRCALPHA = 13, /**< Source blend factor is (1-As, 1-As, 1-As, 1-As) and destination blend factor is (As, As, As, As) */
/// <summary>
/// Blend factor is (0, 0, 0, 0).
/// </summary>
VXBLEND_ZERO = 1U,
/// <summary>
/// Blend factor is (1, 1, 1, 1).
/// </summary>
VXBLEND_ONE = 2U,
/// <summary>
/// Blend factor is (Rs, Gs, Bs, As).
/// </summary>
VXBLEND_SRCCOLOR = 3U,
/// <summary>
/// Blend factor is (1-Rs, 1-Gs, 1-Bs, 1-As).
/// </summary>
VXBLEND_INVSRCCOLOR = 4U,
/// <summary>
/// Blend factor is (As, As, As, As).
/// </summary>
VXBLEND_SRCALPHA = 5U,
/// <summary>
/// Blend factor is (1-As, 1-As, 1-As, 1-As).
/// </summary>
VXBLEND_INVSRCALPHA = 6U,
/// <summary>
/// Blend factor is (Ad, Ad, Ad, Ad).
/// </summary>
VXBLEND_DESTALPHA = 7U,
/// <summary>
/// Blend factor is (1-Ad, 1-Ad, 1-Ad, 1-Ad).
/// </summary>
VXBLEND_INVDESTALPHA = 8U,
/// <summary>
/// Blend factor is (Rd, Gd, Bd, Ad).
/// </summary>
VXBLEND_DESTCOLOR = 9U,
/// <summary>
/// Blend factor is (1-Rd, 1-Gd, 1-Bd, 1-Ad).
/// </summary>
VXBLEND_INVDESTCOLOR = 10U,
/// <summary>
/// Blend factor is (f, f, f, 1); f = min(As, 1-Ad).
/// </summary>
VXBLEND_SRCALPHASAT = 11U,
// /// <summary>
// /// Source blend factor is (As, As, As, As) and destination blend factor is (1-As, 1-As, 1-As, 1-As)
// /// </summary>
// VXBLEND_BOTHSRCALPHA = 12U,
// /// <summary>
// /// Source blend factor is (1-As, 1-As, 1-As, 1-As) and destination blend factor is (As, As, As, As)
// /// </summary>
// VXBLEND_BOTHINVSRCALPHA = 13U,
// /// <summary>
// /// Source blend factor is (1-As, 1-As, 1-As, 1-As) and destination blend factor is (As, As, As, As)
// /// </summary>
// VXBLEND_MASK = 0xFU,
}
/// <summary>
/// Fill Mode Options
/// </summary>
public enum VXFILL_MODE : uint {
VXFILL_POINT = 1, /**< Vertices rendering */
VXFILL_WIREFRAME = 2, /**< Edges rendering */
VXFILL_SOLID = 3, /**< Face rendering */
/// <summary>
/// Vertices rendering
/// </summary>
VXFILL_POINT = 1U,
/// <summary>
/// Edges rendering
/// </summary>
VXFILL_WIREFRAME = 2U,
/// <summary>
/// Face rendering
/// </summary>
VXFILL_SOLID = 3U,
// VXFILL_MASK = 3U,
}
/// <summary>
/// Shade Mode Options
/// </summary>
public enum VXSHADE_MODE : uint {
VXSHADE_FLAT = 1, /**< Flat Shading */
VXSHADE_GOURAUD = 2, /**< Gouraud Shading */
VXSHADE_PHONG = 3, /**< Phong Shading (Not yet supported by most implementation) */
/// <summary>
/// Flat Shading
/// </summary>
VXSHADE_FLAT = 1U,
/// <summary>
/// Gouraud Shading
/// </summary>
VXSHADE_GOURAUD = 2U,
/// <summary>
/// Phong Shading (Not yet supported by most implementation)
/// </summary>
VXSHADE_PHONG = 3U,
// VXSHADE_MASK = 3U,
}
/// <summary>
/// Comparison Function
/// </summary>
public enum VXCMPFUNC : uint {
VXCMP_NEVER = 1, /**< Always fail the test. */
VXCMP_LESS = 2, /**< Accept if value if less than current value. */
VXCMP_EQUAL = 3, /**< Accept if value if equal than current value. */
VXCMP_LESSEQUAL = 4, /**< Accept if value if less or equal than current value. */
VXCMP_GREATER = 5, /**< Accept if value if greater than current value. */
VXCMP_NOTEQUAL = 6, /**< Accept if value if different than current value. */
VXCMP_GREATEREQUAL = 7, /**< Accept if value if greater or equal current value. */
VXCMP_ALWAYS = 8, /**< Always accept the test. */
/// <summary>
/// Always fail the test.
/// </summary>
VXCMP_NEVER = 1U,
/// <summary>
/// Accept if value if less than current value.
/// </summary>
VXCMP_LESS = 2U,
/// <summary>
/// Accept if value if equal than current value.
/// </summary>
VXCMP_EQUAL = 3U,
/// <summary>
/// Accept if value if less or equal than current value.
/// </summary>
VXCMP_LESSEQUAL = 4U,
/// <summary>
/// Accept if value if greater than current value.
/// </summary>
VXCMP_GREATER = 5U,
/// <summary>
/// Accept if value if different than current value.
/// </summary>
VXCMP_NOTEQUAL = 6U,
/// <summary>
/// Accept if value if greater or equal current value.
/// </summary>
VXCMP_GREATEREQUAL = 7U,
/// <summary>
/// Always accept the test.
/// </summary>
VXCMP_ALWAYS = 8U,
// /// <summary>
// /// Mask for all possible values.
// /// </summary>
// VXCMP_MASK = 0xFU,
}
/// <summary>
/// Mesh lighting options
/// </summary>
public enum VXMESH_LITMODE : uint {
VX_PRELITMESH = 0, /**< Lighting use color information store with vertices */
VX_LITMESH = 1, /**< Lighting is done by renderer using normals and face material information. */
/// <summary>
/// Lighting use color information store with vertices
/// </summary>
VX_PRELITMESH = 0,
/// <summary>
/// Lighting is done by renderer using normals and face material information.
/// </summary>
VX_LITMESH = 1,
}
public enum CK_CAMERA_PROJECTION : uint {
CK_PERSPECTIVEPROJECTION = 1,
CK_ORTHOGRAPHICPROJECTION = 2,
};
#endregion
}

View File

@@ -4,10 +4,6 @@
<ProjectReference Include="..\BMapSharp\BMapSharp.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="System.CommandLine" Version="2.0.0-beta4.22272.1" />
</ItemGroup>
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>

View File

@@ -0,0 +1,53 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BMapSharpTest {
public class CliException : Exception {
public CliException() { }
public CliException(string message)
: base(message) { }
public CliException(string message, Exception inner)
: base(message, inner) { }
}
public class Cli {
public Cli() {
var filename = System.Environment.GetEnvironmentVariable("BMAP_FILE_NAME");
if (filename is null) {
throw new CliException("You must specify BMAP_FILE_NAME environment variable before running this test.");
}
this.FileName = filename;
var ballance_dir = System.Environment.GetEnvironmentVariable("BMAP_BALLANCE_DIR");
if (ballance_dir is null) {
throw new CliException("You must specify BMAP_BALLANCE_DIR environment variable before running this test.");
}
this.BallanceDir = ballance_dir;
var encodings = System.Environment.GetEnvironmentVariable("BMAP_ENCODINGS");
if (encodings is null) {
throw new CliException("You must specify BMAP_ENCODINGS environment variable before running this test.");
}
this.Encodings = encodings.Split(",");
}
/// <summary>
/// The path to the map for loading.
/// </summary>
public string FileName { get; private set; }
/// <summary>
/// The path to the Ballance directory for finding textures
/// </summary>
public string BallanceDir { get; private set; }
/// <summary>
/// The name of encodings used by BMap for loading map.
/// </summary>
public string[] Encodings { get; private set; }
}
}

View File

@@ -0,0 +1,50 @@
using System;
using System.IO;
using System.Text;
using BMapSharp;
namespace BMapSharpTest {
internal class Program {
static int Main(string[] args) {
// Parse arguments
Cli cli;
try {
cli = new Cli();
} catch (CliException e) {
Console.WriteLine($"Can not launch test. Reason: {e.Message}");
return 2;
}
// Check console encoding.
Console.OutputEncoding = Encoding.UTF8;
// Check BMap status.
if (!BMapSharp.BMapWrapper.Utils.IsBMapAvailable()) {
Console.WriteLine("Fail to initialize native BMap.");
return 1;
}
// Waiting debugger
int pid = System.Diagnostics.Process.GetCurrentProcess().Id;
Console.WriteLine($"C# PID is {pid}. Waiting debugger, press any key to continue...");
Console.ReadKey(true);
// Start testbench
string file_name = cli.FileName;
var temp_dir_info = Directory.CreateTempSubdirectory();
string temp_dir = temp_dir_info.FullName;
string texture_dir = Path.Combine(cli.BallanceDir, "Textures");
string[] encodings = cli.Encodings;
using (var reader = new BMapSharp.BMapWrapper.BMFileReader(file_name, temp_dir, texture_dir, encodings)) {
TestSuits.TestCommon.Test(reader);
TestSuits.TestIEquatable.Test(reader);
}
Console.WriteLine("Press any key to quit...");
Console.ReadKey(true);
return 0;
}
}
}

View File

@@ -0,0 +1,181 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using BMapSharp.BMapWrapper;
namespace BMapSharpTest.TestSuits {
public static class TestCommon {
public static void Test(BMFileReader reader) {
Console.WriteLine("===== Groups =====");
TestGroup(reader);
Console.WriteLine("===== 3dObjects =====");
Test3dObject(reader);
Console.WriteLine("===== Meshes =====");
TestMesh(reader);
Console.WriteLine("===== Materials =====");
TestMaterial(reader);
Console.WriteLine("===== Textures =====");
TestTexture(reader);
Console.WriteLine("===== Target Lights =====");
TestTargetLight(reader);
Console.WriteLine("===== Target Cameras =====");
TestTargetCamera(reader);
Console.WriteLine("===== END =====");
}
private static void TestGroup(BMFileReader reader) {
foreach (var gp in reader.GetGroups()) {
Console.WriteLine(gp.GetName());
foreach (var gp_item in gp.GetObjects()) {
Console.WriteLine($"\t{gp_item.GetName()}");
}
}
}
private static void Test3dObject(BMFileReader reader) {
foreach (var obj in reader.Get3dObjects()) {
Console.WriteLine(obj.GetName());
var current_mesh = obj.GetCurrentMesh();
var mesh_name = current_mesh is null ? "<null>" : current_mesh.GetName();
Console.WriteLine($"\tMesh: {mesh_name}");
Console.WriteLine($"\tVisibility: {obj.GetVisibility()}");
Console.WriteLine($"\tMatrix: {obj.GetWorldMatrix().ToManaged()}");
}
}
private static void TestMesh(BMFileReader reader) {
foreach (var mesh in reader.GetMeshes()) {
Console.WriteLine(mesh.GetName());
Console.WriteLine($"\tLit Mode: {mesh.GetLitMode()}");
Console.WriteLine($"\tVertex Count: {mesh.GetVertexCount()}");
Console.WriteLine($"\tFace Count: {mesh.GetFaceCount()}");
Console.WriteLine($"\tMaterial Slot Count: {mesh.GetMaterialSlotCount()}");
}
}
private static void TestMaterial(BMFileReader reader) {
foreach (var mtl in reader.GetMaterials()) {
Console.WriteLine(mtl.GetName());
Console.WriteLine($"\tDiffuse: {mtl.GetDiffuse().ToManagedRGBA()}");
Console.WriteLine($"\tAmbient: {mtl.GetAmbient().ToManagedRGBA()}");
Console.WriteLine($"\tSpecular: {mtl.GetSpecular().ToManagedRGBA()}");
Console.WriteLine($"\tEmissive: {mtl.GetEmissive().ToManagedRGBA()}");
Console.WriteLine($"\tSpecular Power: {mtl.GetSpecularPower()}");
var current_texture = mtl.GetTexture();
var texture_name = current_texture is null ? "<null>" : current_texture.GetName();
Console.WriteLine($"\tTexture: {texture_name}");
Console.WriteLine($"\tTexture Border Color: {mtl.GetTextureBorderColor().ToManagedRGBA()}");
Console.WriteLine($"\tTexture Blend Mode: {mtl.GetTextureBlendMode()}");
Console.WriteLine($"\tTexture Min Mode: {mtl.GetTextureMinMode()}");
Console.WriteLine($"\tTexture Mag Mode: {mtl.GetTextureMagMode()}");
Console.WriteLine($"\tSource Blend: {mtl.GetSourceBlend()}");
Console.WriteLine($"\tDest Blend: {mtl.GetDestBlend()}");
Console.WriteLine($"\tFill Mode: {mtl.GetFillMode()}");
Console.WriteLine($"\tShade Mode: {mtl.GetShadeMode()}");
Console.WriteLine($"\tAlpha Test Enabled: {mtl.GetAlphaTestEnabled()}");
Console.WriteLine($"\tAlpha Blend Enabled: {mtl.GetAlphaBlendEnabled()}");
Console.WriteLine($"\tPerspective Correction Enabled: {mtl.GetPerspectiveCorrectionEnabled()}");
Console.WriteLine($"\tZ Write Enabled: {mtl.GetZWriteEnabled()}");
Console.WriteLine($"\tTwo Sided Enabled: {mtl.GetTwoSidedEnabled()}");
Console.WriteLine($"\tAlpha Ref: {mtl.GetAlphaRef()}");
Console.WriteLine($"\tAlpha Func: {mtl.GetAlphaFunc()}");
Console.WriteLine($"\tZ Func: {mtl.GetZFunc()}");
}
}
private static void TestTexture(BMFileReader reader) {
foreach (var tex in reader.GetTextures()) {
Console.WriteLine(tex.GetName());
Console.WriteLine($"\tFile Name: {tex.GetFileName()}");
Console.WriteLine($"\tSave Options: {tex.GetSaveOptions()}");
Console.WriteLine($"\tVideo Format: {tex.GetVideoFormat()}");
}
}
private static void TestTargetLight(BMFileReader reader) {
foreach (var lit in reader.GetTargetLights()) {
Console.WriteLine(lit.GetName());
Console.WriteLine($"\tVisibility: {lit.GetVisibility()}");
Console.WriteLine($"\tMatrix: {lit.GetWorldMatrix().ToManaged()}");
Console.WriteLine($"\tType: {lit.GetLightType()}");
Console.WriteLine($"\tColor: {lit.GetColor().ToManagedRGBA()}");
Console.WriteLine($"\tConstant Attenuation: {lit.GetConstantAttenuation()}");
Console.WriteLine($"\tLinear Attenuation: {lit.GetLinearAttenuation()}");
Console.WriteLine($"\tQuadratic Attenuation: {lit.GetQuadraticAttenuation()}");
Console.WriteLine($"\tRange: {lit.GetRange()}");
Console.WriteLine($"\tHot Spot: {lit.GetHotSpot()}");
Console.WriteLine($"\tFalloff: {lit.GetFalloff()}");
Console.WriteLine($"\tFalloff Shape: {lit.GetFalloffShape()}");
}
}
private static void TestTargetCamera(BMFileReader reader) {
foreach (var cam in reader.GetTargetCameras()) {
Console.WriteLine(cam.GetName());
Console.WriteLine($"\tVisibility: {cam.GetVisibility()}");
Console.WriteLine($"\tMatrix: {cam.GetWorldMatrix().ToManaged()}");
Console.WriteLine($"\tType: {cam.GetProjectionType()}");
Console.WriteLine($"\tOrthographic Zoom: {cam.GetOrthographicZoom()}");
Console.WriteLine($"\tFront Plane: {cam.GetFrontPlane()}");
Console.WriteLine($"\tBack Plane: {cam.GetBackPlane()}");
Console.WriteLine($"\tFov: {cam.GetFov()}");
cam.GetAspectRatio(out var width, out var height);
Console.WriteLine($"\tAspect Ratio: {width}:{height}");
}
}
}
public static class TestIEquatable {
public static void Test(BMFileReader reader) {
if (reader.Get3dObjectCount() < 2u) {
Debug.Fail(
"Invalid file for test IEquatable.",
"We can not perform IEquatable test because the length of 3dObject is too short (must greater than 2). Please choose another file to perform."
);
return;
}
// Prepare test variables
var all_3dobjects = new List<BM3dObject>(reader.Get3dObjects());
var first_3dobj = all_3dobjects[0];
var second_3dobj = all_3dobjects[1];
all_3dobjects = new List<BM3dObject>(reader.Get3dObjects());
var first_3dobj_again = all_3dobjects[0];
Debug.Assert(!Object.ReferenceEquals(first_3dobj, first_3dobj_again));
// Hashtable test
var test_hashset = new HashSet<BM3dObject>();
Debug.Assert(test_hashset.Add(first_3dobj));
Debug.Assert(!test_hashset.Add(first_3dobj_again));
Debug.Assert(test_hashset.Add(second_3dobj));
// Dictionary test
var test_dictionary = new Dictionary<BM3dObject, string>();
Debug.Assert(test_dictionary.TryAdd(first_3dobj, first_3dobj.GetName()));
Debug.Assert(!test_dictionary.TryAdd(first_3dobj_again, first_3dobj_again.GetName()));
Debug.Assert(test_dictionary.TryAdd(second_3dobj, second_3dobj.GetName()));
}
}
}

View File

@@ -1,219 +0,0 @@
using BMapSharp.BMapWrapper;
using System;
using System.Text;
using System.Collections.Generic;
using System.Diagnostics;
using System.CommandLine;
namespace BMapSharpTestbench {
internal class Program {
static void Main(string[] args) {
// Parse arguments
var resolved_args = ResolveArguments(args);
if (resolved_args is null) {
// just silent quit
Environment.Exit(0);
}
// Check environment
Console.OutputEncoding = Encoding.UTF8;
if (!BMapSharp.BMapWrapper.Utils.IsBMapAvailable()) {
Console.WriteLine("Fail to initialize native BMap.");
Environment.Exit(0);
}
// Waiting debugger
int pid = System.Diagnostics.Process.GetCurrentProcess().Id;
Console.WriteLine($"C# PID is {pid}. Waiting debugger, press any key to continue...");
Console.ReadKey(true);
// Start testbench
string file_name = resolved_args.mFileName; // "LightCameraTest.nmo";
string temp_folder = resolved_args.mTempFolder; // "Temp";
string texture_folder = resolved_args.mTextureFolder; // "F:\\Ballance\\Ballance\\Textures";
string[] encodings = resolved_args.mEncodings; // ["cp1252", "gb2312"];
using (var reader = new BMapSharp.BMapWrapper.BMFileReader(file_name, temp_folder, texture_folder, encodings)) {
TestCommon(reader);
TestIEquatable(reader);
}
Console.WriteLine("Press any key to quit...");
Console.ReadKey(true);
}
class BMapSharpArguments {
public string mFileName;
public string mTempFolder;
public string mTextureFolder;
public string[] mEncodings;
}
static BMapSharpArguments ResolveArguments(string[] args) {
// define arguments
var fileNameOpt = new Option<string>
("--file-path", "The path to input Virtools file.");
fileNameOpt.IsRequired = true;
var tempFolderOpt = new Option<string>
("--temp-dir", "The temp folder used by BMap.");
tempFolderOpt.IsRequired = true;
var textureFolderOpt = new Option<string>
("--texture-dir", "The texture folder containing Ballance texture resources.");
textureFolderOpt.IsRequired = true;
var encodingsOpt = new Option<IEnumerable<string>>
("--encodings", "The encodings used to parse the names stroed in input Virtools file.");
encodingsOpt.IsRequired = true;
encodingsOpt.Arity = ArgumentArity.OneOrMore;
encodingsOpt.AllowMultipleArgumentsPerToken = true;
// init root command
var rootCommand = new RootCommand("The testbench of BMapSharp.");
rootCommand.Add(fileNameOpt);
rootCommand.Add(tempFolderOpt);
rootCommand.Add(textureFolderOpt);
rootCommand.Add(encodingsOpt);
// init result container
BMapSharpArguments ret = new BMapSharpArguments();
// set handler
rootCommand.SetHandler((context) => {
ret.mFileName = context.ParseResult.GetValueForOption(fileNameOpt);
ret.mTempFolder = context.ParseResult.GetValueForOption(tempFolderOpt);
ret.mTextureFolder = context.ParseResult.GetValueForOption(textureFolderOpt);
ret.mEncodings = context.ParseResult.GetValueForOption(encodingsOpt).ToArray();
context.ExitCode = 61;
});
// execute root command and return value.
if (rootCommand.Invoke(args) != 61) return null;
return ret;
}
static void TestCommon(BMapSharp.BMapWrapper.BMFileReader reader) {
// Console.WriteLine("===== Groups =====");
// foreach (var gp in reader.GetGroups()) {
// Console.WriteLine(gp.GetName());
// foreach (var gp_item in gp.GetObjects()) {
// Console.WriteLine($"\t{gp_item.GetName()}");
// }
// }
// Console.WriteLine("===== 3dObjects =====");
// foreach (var obj in reader.Get3dObjects()) {
// Console.WriteLine(obj.GetName());
// var current_mesh = obj.GetCurrentMesh();
// var mesh_name = current_mesh is null ? "<null>" : current_mesh.GetName();
// Console.WriteLine($"\tMesh: {mesh_name}");
// Console.WriteLine($"\tVisibility: {obj.GetVisibility()}");
// Console.WriteLine($"\tMatrix: {obj.GetWorldMatrix().ToManaged()}");
// }
// Console.WriteLine("===== Meshes =====");
// foreach (var mesh in reader.GetMeshes()) {
// Console.WriteLine(mesh.GetName());
// Console.WriteLine($"\tLit Mode: {mesh.GetLitMode()}");
// Console.WriteLine($"\tVertex Count: {mesh.GetVertexCount()}");
// Console.WriteLine($"\tFace Count: {mesh.GetFaceCount()}");
// Console.WriteLine($"\tMaterial Slot Count: {mesh.GetMaterialSlotCount()}");
// }
// Console.WriteLine("===== Materials =====");
// foreach (var mtl in reader.GetMaterials()) {
// Console.WriteLine(mtl.GetName());
// Console.WriteLine($"\tDiffuse: {mtl.GetDiffuse().ToManagedRGBA()}");
// Console.WriteLine($"\tAmbient: {mtl.GetAmbient().ToManagedRGBA()}");
// Console.WriteLine($"\tSpecular: {mtl.GetSpecular().ToManagedRGBA()}");
// Console.WriteLine($"\tEmissive: {mtl.GetEmissive().ToManagedRGBA()}");
// Console.WriteLine($"\tSpecular Power: {mtl.GetSpecularPower()}");
// Console.WriteLine($"\tTexture Border Color: {mtl.GetTextureBorderColor().ToManagedRGBA()}");
// Console.WriteLine($"\tTexture Blend Mode: {mtl.GetTextureBlendMode()}");
// Console.WriteLine($"\tTexture Min Mode: {mtl.GetTextureMinMode()}");
// Console.WriteLine($"\tTexture Mag Mode: {mtl.GetTextureMagMode()}");
// Console.WriteLine($"\tSource Blend: {mtl.GetSourceBlend()}");
// Console.WriteLine($"\tDest Blend: {mtl.GetDestBlend()}");
// Console.WriteLine($"\tFill Mode: {mtl.GetFillMode()}");
// Console.WriteLine($"\tShade Mode: {mtl.GetShadeMode()}");
// Console.WriteLine($"\tAlpha Test Enabled: {mtl.GetAlphaTestEnabled()}");
// Console.WriteLine($"\tAlpha Blend Enabled: {mtl.GetAlphaBlendEnabled()}");
// Console.WriteLine($"\tPerspective Correction Enabled: {mtl.GetPerspectiveCorrectionEnabled()}");
// Console.WriteLine($"\tZ Write Enabled: {mtl.GetZWriteEnabled()}");
// Console.WriteLine($"\tTwo Sided Enabled: {mtl.GetTwoSidedEnabled()}");
// Console.WriteLine($"\tAlpha Ref: {mtl.GetAlphaRef()}");
// Console.WriteLine($"\tAlpha Func: {mtl.GetAlphaFunc()}");
// Console.WriteLine($"\tZ Func: {mtl.GetZFunc()}");
// }
// Console.WriteLine("===== Textures =====");
// foreach (var tex in reader.GetTextures()) {
// Console.WriteLine(tex.GetName());
// Console.WriteLine($"\tFile Name: {tex.GetFileName()}");
// Console.WriteLine($"\tSave Options: {tex.GetSaveOptions()}");
// Console.WriteLine($"\tVideo Format: {tex.GetVideoFormat()}");
// }
Console.WriteLine("===== Target Lights =====");
foreach (var lit in reader.GetTargetLights()) {
Console.WriteLine(lit.GetName());
Console.WriteLine($"\tVisibility: {lit.GetVisibility()}");
Console.WriteLine($"\tMatrix: {lit.GetWorldMatrix().ToManaged()}");
Console.WriteLine($"Type: {lit.GetLightType()}");
Console.WriteLine($"Color: {lit.GetColor().ToManagedRGBA()}");
Console.WriteLine($"Constant Attenuation: {lit.GetConstantAttenuation()}");
Console.WriteLine($"Linear Attenuation: {lit.GetLinearAttenuation()}");
Console.WriteLine($"Quadratic Attenuation: {lit.GetQuadraticAttenuation()}");
Console.WriteLine($"Range: {lit.GetRange()}");
Console.WriteLine($"Hot Spot: {lit.GetHotSpot()}");
Console.WriteLine($"Falloff: {lit.GetFalloff()}");
Console.WriteLine($"Falloff Shape: {lit.GetFalloffShape()}");
}
Console.WriteLine("===== END =====");
}
static void TestIEquatable(BMapSharp.BMapWrapper.BMFileReader reader) {
if (reader.Get3dObjectCount() < 2u) {
Debug.Fail(
"Invalid file for test IEquatable.",
"We can not perform IEquatable test because the length of 3dObject is too short (must greater than 2). Please choose another file to perform."
);
return;
}
// Prepare test variables
var all_3dobjects = new List<BM3dObject>(reader.Get3dObjects());
var first_3dobj = all_3dobjects[0];
var second_3dobj = all_3dobjects[1];
all_3dobjects = new List<BM3dObject>(reader.Get3dObjects());
var first_3dobj_again = all_3dobjects[0];
Debug.Assert(!Object.ReferenceEquals(first_3dobj, first_3dobj_again));
// Hashtable test
var test_hashset = new HashSet<BM3dObject>();
Debug.Assert(test_hashset.Add(first_3dobj));
Debug.Assert(!test_hashset.Add(first_3dobj_again));
Debug.Assert(test_hashset.Add(second_3dobj));
// Dictionary test
var test_dictionary = new Dictionary<BM3dObject, string>();
Debug.Assert(test_dictionary.TryAdd(first_3dobj, first_3dobj.GetName()));
Debug.Assert(!test_dictionary.TryAdd(first_3dobj_again, first_3dobj_again.GetName()));
Debug.Assert(test_dictionary.TryAdd(second_3dobj, second_3dobj.GetName()));
}
}
}

View File

@@ -1,9 +1,18 @@
# BMapSharp
The core of BMapSharp project is placed within `BMapSharp` subdirectory. This directory also contain a testbench project of `BMapSharp`, called `BMapSharpTestbench`. You can build it and do basic test for `BMapSharp`.
## Layout
The native BMap library should be placed together with managed `BMapSharp` dynamic library. I use gitignore file to filter all native binary so you need put them manually. The native BMap library must be named as `BMap.dll` (in Windows), `BMap.so` (in Linux or BSD), or `BMap.dylib` (in macOS). If you still can not load BMap or your system is not listed above, you should name it as `BMap.bin`.
This directory contains 2 project.
`BMapSharp` is the binding to BMap and `BMapSharpTest` is the test for `BMapSharp`.
The most content of `VirtoolsTypes.cs` is generated by EnumsMigration, and the most content of `BMap.cs` is generated by BMapBindings. You should watch these file changes if corresponding C++ code or structures are changed.
> [!NOTE]
> `BMapSharpTest` project do not utilize any existing test framework.
> The test should be executed manually by compiling it and running it.
Since BMap 0.3.0, testbench use command line arguments, instead of hardcode variables in code, as the arguments of BMap. It is convenient that debug BMapSharp without any modification of source code. For a brief instruction, you may need to launch BMapSharpTestbench in following command (just an example. you can modify it as you wished): `dotnet run -- --file-path "LightCameraTest.nmo" --temp-dir "Temp" --texture-dir "F:/Ballance/Ballance/Textures" --encodings cp1252 gb2312`.
## Native BMap Library Location
The native BMap library should be placed together with managed `BMapSharp` dynamic library.
The native BMap library must be named as `BMap.dll` (in Windows), `BMap.so` (in Linux or BSD), `BMap.dylib` (in macOS), or `BMap.bin` (in any other platforms).
If you are building final distributed package file (I have not build them yet), you may need manually put native BMap library file into package file because I have not write this behavior in any place.

View File

@@ -1,150 +0,0 @@
# -------------------- Personal --------------------
# Ignore VSCode
.vscode/
# Ignore binary BMap stuff
*.dll
*.pdb
*.so
*.dylib
*.bin
# -------------------- Python --------------------
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
.pybuilder/
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# PEP 582; used by e.g. github.com/David-OConnor/pyflow
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# pytype static type analyzer
.pytype/
# Cython debug symbols
cython_debug/

View File

@@ -1,913 +0,0 @@
import ctypes, os, sys, typing
#region Type Defines
class BMapException(Exception):
"""
The exception thrown by BMap bindings.
"""
pass
bm_CKSTRING = ctypes.c_char_p
bm_CKSTRING_p = ctypes.POINTER(bm_CKSTRING)
bm_CKDWORD = ctypes.c_uint32
bm_CKDWORD_p = ctypes.POINTER(bm_CKDWORD)
bm_CKDWORD_pp = ctypes.POINTER(bm_CKDWORD_p)
bm_CKWORD = ctypes.c_uint16
bm_CKWORD_p = ctypes.POINTER(bm_CKWORD)
bm_CKWORD_pp = ctypes.POINTER(bm_CKWORD_p)
bm_CKID = ctypes.c_uint32
bm_CKID_p = ctypes.POINTER(bm_CKID)
bm_CKID_pp = ctypes.POINTER(bm_CKID_p)
bm_CKFLOAT = ctypes.c_float
bm_CKFLOAT_p = ctypes.POINTER(bm_CKFLOAT)
bm_CKINT = ctypes.c_int32
bm_CKBYTE = ctypes.c_uint8
bm_CKBYTE_p = ctypes.POINTER(bm_CKBYTE)
bm_enum = bm_CKDWORD
bm_enum_p = ctypes.POINTER(bm_enum)
bm_bool = ctypes.c_bool
bm_bool_p = ctypes.POINTER(bm_bool)
bm_void_p = ctypes.c_void_p
bm_void_pp = ctypes.POINTER(ctypes.c_void_p)
bm_callback = ctypes.CFUNCTYPE(None, bm_CKSTRING)
class bm_VxVector2(ctypes.Structure):
_fields_ = [
('x', bm_CKFLOAT),
('y', bm_CKFLOAT),
]
bm_VxVector2_p = ctypes.POINTER(bm_VxVector2)
bm_VxVector2_pp = ctypes.POINTER(bm_VxVector2_p)
class bm_VxVector3(ctypes.Structure):
_fields_ = [
('x', bm_CKFLOAT),
('y', bm_CKFLOAT),
('z', bm_CKFLOAT),
]
bm_VxVector3_p = ctypes.POINTER(bm_VxVector3)
bm_VxVector3_pp = ctypes.POINTER(bm_VxVector3_p)
class bm_VxColor(ctypes.Structure):
_fields_ = [
('r', bm_CKFLOAT),
('g', bm_CKFLOAT),
('b', bm_CKFLOAT),
('a', bm_CKFLOAT),
]
bm_VxColor_p = ctypes.POINTER(bm_VxColor)
class bm_VxMatrix(ctypes.Structure):
_fields_ = list(
(f'i{idx}', bm_CKFLOAT) for idx in range(16)
)
bm_VxMatrix_p = ctypes.POINTER(bm_VxMatrix)
#endregion
#region BMap Loader
_g_BMapLibName: str
if sys.platform.startswith('win32') or sys.platform.startswith('cygwin'):
_g_BMapLibName = "BMap.dll"
elif sys.platform.startswith('linux') or sys.platform.startswith('freebsd'):
_g_BMapLibName = "BMap.so"
elif sys.platform.startswith('darwin'):
_g_BMapLibName = "BMap.dylib"
else:
_g_BMapLibName = "BMap.bin"
_g_BMapLibPath: str = os.path.join(os.path.dirname(__file__), _g_BMapLibName)
_g_BMapModule: ctypes.CDLL | None = None
try:
_g_BMapModule = ctypes.cdll.LoadLibrary(_g_BMapLibPath)
except:
print(f'Fail to load native BMap dynamic library file "{_g_BMapLibPath}".')
_g_BMapModule = None
def is_bmap_available() -> bool:
return _g_BMapModule is not None
def _bmap_error_check(result: bool, func, args):
if not result:
raise BMapException("BMap operation failed.")
return result
def _create_bmap_func(fct_name: str, fct_params: list[typing.Any]) -> typing.Callable[..., bm_bool]:
if _g_BMapModule is None: return None
cache: typing.Callable[..., bm_bool] = getattr(_g_BMapModule, fct_name)
cache.argtypes = fct_params
cache.restype = bm_bool
cache.errcheck = _bmap_error_check
return cache
#endregion
#region Function Defines
##### GENERATED FUNCTIONS BEGIN #####
## BMInit
# @return True if no error, otherwise False.
BMInit = _create_bmap_func('BMInit', [])
## BMDispose
# @return True if no error, otherwise False.
BMDispose = _create_bmap_func('BMDispose', [])
## BMFile_Load
# @param file_name[in] Type: LibCmo::CKSTRING.
# @param temp_folder[in] Type: LibCmo::CKSTRING.
# @param texture_folder[in] Type: LibCmo::CKSTRING.
# @param raw_callback[in] Type: BMap::NakedOutputCallback.
# @param encoding_count[in] Type: LibCmo::CKDWORD.
# @param encodings[in] Type: LibCmo::CKSTRING*.
# @param out_file[out] Type: BMap::BMFile*. Use ctypes.byref(data) pass it.
# @return True if no error, otherwise False.
BMFile_Load = _create_bmap_func('BMFile_Load', [bm_CKSTRING, bm_CKSTRING, bm_CKSTRING, bm_callback, bm_CKDWORD, bm_CKSTRING_p, bm_void_pp])
## BMFile_Create
# @param temp_folder[in] Type: LibCmo::CKSTRING.
# @param texture_folder[in] Type: LibCmo::CKSTRING.
# @param raw_callback[in] Type: BMap::NakedOutputCallback.
# @param encoding_count[in] Type: LibCmo::CKDWORD.
# @param encodings[in] Type: LibCmo::CKSTRING*.
# @param out_file[out] Type: BMap::BMFile*. Use ctypes.byref(data) pass it.
# @return True if no error, otherwise False.
BMFile_Create = _create_bmap_func('BMFile_Create', [bm_CKSTRING, bm_CKSTRING, bm_callback, bm_CKDWORD, bm_CKSTRING_p, bm_void_pp])
## BMFile_Save
# @param map_file[in] Type: BMap::BMFile*.
# @param file_name[in] Type: LibCmo::CKSTRING.
# @param texture_save_opt[in] Type: LibCmo::CK2::CK_TEXTURE_SAVEOPTIONS.
# @param use_compress[in] Type: bool.
# @param compreess_level[in] Type: LibCmo::CKINT.
# @return True if no error, otherwise False.
BMFile_Save = _create_bmap_func('BMFile_Save', [bm_void_p, bm_CKSTRING, bm_enum, bm_bool, bm_CKINT])
## BMFile_Free
# @param map_file[in] Type: BMap::BMFile*.
# @return True if no error, otherwise False.
BMFile_Free = _create_bmap_func('BMFile_Free', [bm_void_p])
## BMFile_GetGroupCount
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param out_count[out] Type: LibCmo::CKDWORD. Use ctypes.byref(data) pass it.
# @return True if no error, otherwise False.
BMFile_GetGroupCount = _create_bmap_func('BMFile_GetGroupCount', [bm_void_p, bm_CKDWORD_p])
## BMFile_GetGroup
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param idx[in] Type: LibCmo::CKDWORD.
# @param out_id[out] Type: LibCmo::CK2::CK_ID. Use ctypes.byref(data) pass it.
# @return True if no error, otherwise False.
BMFile_GetGroup = _create_bmap_func('BMFile_GetGroup', [bm_void_p, bm_CKDWORD, bm_CKID_p])
## BMFile_CreateGroup
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param out_id[out] Type: LibCmo::CK2::CK_ID. Use ctypes.byref(data) pass it.
# @return True if no error, otherwise False.
BMFile_CreateGroup = _create_bmap_func('BMFile_CreateGroup', [bm_void_p, bm_CKID_p])
## BMFile_Get3dObjectCount
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param out_count[out] Type: LibCmo::CKDWORD. Use ctypes.byref(data) pass it.
# @return True if no error, otherwise False.
BMFile_Get3dObjectCount = _create_bmap_func('BMFile_Get3dObjectCount', [bm_void_p, bm_CKDWORD_p])
## BMFile_Get3dObject
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param idx[in] Type: LibCmo::CKDWORD.
# @param out_id[out] Type: LibCmo::CK2::CK_ID. Use ctypes.byref(data) pass it.
# @return True if no error, otherwise False.
BMFile_Get3dObject = _create_bmap_func('BMFile_Get3dObject', [bm_void_p, bm_CKDWORD, bm_CKID_p])
## BMFile_Create3dObject
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param out_id[out] Type: LibCmo::CK2::CK_ID. Use ctypes.byref(data) pass it.
# @return True if no error, otherwise False.
BMFile_Create3dObject = _create_bmap_func('BMFile_Create3dObject', [bm_void_p, bm_CKID_p])
## BMFile_GetMeshCount
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param out_count[out] Type: LibCmo::CKDWORD. Use ctypes.byref(data) pass it.
# @return True if no error, otherwise False.
BMFile_GetMeshCount = _create_bmap_func('BMFile_GetMeshCount', [bm_void_p, bm_CKDWORD_p])
## BMFile_GetMesh
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param idx[in] Type: LibCmo::CKDWORD.
# @param out_id[out] Type: LibCmo::CK2::CK_ID. Use ctypes.byref(data) pass it.
# @return True if no error, otherwise False.
BMFile_GetMesh = _create_bmap_func('BMFile_GetMesh', [bm_void_p, bm_CKDWORD, bm_CKID_p])
## BMFile_CreateMesh
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param out_id[out] Type: LibCmo::CK2::CK_ID. Use ctypes.byref(data) pass it.
# @return True if no error, otherwise False.
BMFile_CreateMesh = _create_bmap_func('BMFile_CreateMesh', [bm_void_p, bm_CKID_p])
## BMFile_GetMaterialCount
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param out_count[out] Type: LibCmo::CKDWORD. Use ctypes.byref(data) pass it.
# @return True if no error, otherwise False.
BMFile_GetMaterialCount = _create_bmap_func('BMFile_GetMaterialCount', [bm_void_p, bm_CKDWORD_p])
## BMFile_GetMaterial
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param idx[in] Type: LibCmo::CKDWORD.
# @param out_id[out] Type: LibCmo::CK2::CK_ID. Use ctypes.byref(data) pass it.
# @return True if no error, otherwise False.
BMFile_GetMaterial = _create_bmap_func('BMFile_GetMaterial', [bm_void_p, bm_CKDWORD, bm_CKID_p])
## BMFile_CreateMaterial
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param out_id[out] Type: LibCmo::CK2::CK_ID. Use ctypes.byref(data) pass it.
# @return True if no error, otherwise False.
BMFile_CreateMaterial = _create_bmap_func('BMFile_CreateMaterial', [bm_void_p, bm_CKID_p])
## BMFile_GetTextureCount
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param out_count[out] Type: LibCmo::CKDWORD. Use ctypes.byref(data) pass it.
# @return True if no error, otherwise False.
BMFile_GetTextureCount = _create_bmap_func('BMFile_GetTextureCount', [bm_void_p, bm_CKDWORD_p])
## BMFile_GetTexture
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param idx[in] Type: LibCmo::CKDWORD.
# @param out_id[out] Type: LibCmo::CK2::CK_ID. Use ctypes.byref(data) pass it.
# @return True if no error, otherwise False.
BMFile_GetTexture = _create_bmap_func('BMFile_GetTexture', [bm_void_p, bm_CKDWORD, bm_CKID_p])
## BMFile_CreateTexture
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param out_id[out] Type: LibCmo::CK2::CK_ID. Use ctypes.byref(data) pass it.
# @return True if no error, otherwise False.
BMFile_CreateTexture = _create_bmap_func('BMFile_CreateTexture', [bm_void_p, bm_CKID_p])
## BMFile_GetTargetLightCount
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param out_count[out] Type: LibCmo::CKDWORD. Use ctypes.byref(data) pass it.
# @return True if no error, otherwise False.
BMFile_GetTargetLightCount = _create_bmap_func('BMFile_GetTargetLightCount', [bm_void_p, bm_CKDWORD_p])
## BMFile_GetTargetLight
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param idx[in] Type: LibCmo::CKDWORD.
# @param out_id[out] Type: LibCmo::CK2::CK_ID. Use ctypes.byref(data) pass it.
# @return True if no error, otherwise False.
BMFile_GetTargetLight = _create_bmap_func('BMFile_GetTargetLight', [bm_void_p, bm_CKDWORD, bm_CKID_p])
## BMFile_CreateTargetLight
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param out_id[out] Type: LibCmo::CK2::CK_ID. Use ctypes.byref(data) pass it.
# @return True if no error, otherwise False.
BMFile_CreateTargetLight = _create_bmap_func('BMFile_CreateTargetLight', [bm_void_p, bm_CKID_p])
## BMMeshTrans_New
# @param out_trans[out] Type: BMap::BMMeshTransition*. Use ctypes.byref(data) pass it.
# @return True if no error, otherwise False.
BMMeshTrans_New = _create_bmap_func('BMMeshTrans_New', [bm_void_pp])
## BMMeshTrans_Delete
# @param trans[in] Type: BMap::BMMeshTransition*.
# @return True if no error, otherwise False.
BMMeshTrans_Delete = _create_bmap_func('BMMeshTrans_Delete', [bm_void_p])
## BMMeshTrans_PrepareVertexCount
# @param trans[in] Type: BMap::BMMeshTransition*. The pointer to corresponding BMMeshTransition.
# @param count[in] Type: LibCmo::CKDWORD.
# @return True if no error, otherwise False.
BMMeshTrans_PrepareVertexCount = _create_bmap_func('BMMeshTrans_PrepareVertexCount', [bm_void_p, bm_CKDWORD])
## BMMeshTrans_PrepareVertex
# @param trans[in] Type: BMap::BMMeshTransition*. The pointer to corresponding BMMeshTransition.
# @param out_mem[out] Type: LibCmo::VxMath::VxVector3*. Use ctypes.byref(data) pass it.
# @return True if no error, otherwise False.
BMMeshTrans_PrepareVertex = _create_bmap_func('BMMeshTrans_PrepareVertex', [bm_void_p, bm_VxVector3_pp])
## BMMeshTrans_PrepareNormalCount
# @param trans[in] Type: BMap::BMMeshTransition*. The pointer to corresponding BMMeshTransition.
# @param count[in] Type: LibCmo::CKDWORD.
# @return True if no error, otherwise False.
BMMeshTrans_PrepareNormalCount = _create_bmap_func('BMMeshTrans_PrepareNormalCount', [bm_void_p, bm_CKDWORD])
## BMMeshTrans_PrepareNormal
# @param trans[in] Type: BMap::BMMeshTransition*. The pointer to corresponding BMMeshTransition.
# @param out_mem[out] Type: LibCmo::VxMath::VxVector3*. Use ctypes.byref(data) pass it.
# @return True if no error, otherwise False.
BMMeshTrans_PrepareNormal = _create_bmap_func('BMMeshTrans_PrepareNormal', [bm_void_p, bm_VxVector3_pp])
## BMMeshTrans_PrepareUVCount
# @param trans[in] Type: BMap::BMMeshTransition*. The pointer to corresponding BMMeshTransition.
# @param count[in] Type: LibCmo::CKDWORD.
# @return True if no error, otherwise False.
BMMeshTrans_PrepareUVCount = _create_bmap_func('BMMeshTrans_PrepareUVCount', [bm_void_p, bm_CKDWORD])
## BMMeshTrans_PrepareUV
# @param trans[in] Type: BMap::BMMeshTransition*. The pointer to corresponding BMMeshTransition.
# @param out_mem[out] Type: LibCmo::VxMath::VxVector2*. Use ctypes.byref(data) pass it.
# @return True if no error, otherwise False.
BMMeshTrans_PrepareUV = _create_bmap_func('BMMeshTrans_PrepareUV', [bm_void_p, bm_VxVector2_pp])
## BMMeshTrans_PrepareMtlSlotCount
# @param trans[in] Type: BMap::BMMeshTransition*. The pointer to corresponding BMMeshTransition.
# @param count[in] Type: LibCmo::CKDWORD.
# @return True if no error, otherwise False.
BMMeshTrans_PrepareMtlSlotCount = _create_bmap_func('BMMeshTrans_PrepareMtlSlotCount', [bm_void_p, bm_CKDWORD])
## BMMeshTrans_PrepareMtlSlot
# @param trans[in] Type: BMap::BMMeshTransition*. The pointer to corresponding BMMeshTransition.
# @param out_mem[out] Type: LibCmo::CK2::CK_ID*. Use ctypes.byref(data) pass it.
# @return True if no error, otherwise False.
BMMeshTrans_PrepareMtlSlot = _create_bmap_func('BMMeshTrans_PrepareMtlSlot', [bm_void_p, bm_CKID_pp])
## BMMeshTrans_PrepareFaceCount
# @param trans[in] Type: BMap::BMMeshTransition*. The pointer to corresponding BMMeshTransition.
# @param count[in] Type: LibCmo::CKDWORD.
# @return True if no error, otherwise False.
BMMeshTrans_PrepareFaceCount = _create_bmap_func('BMMeshTrans_PrepareFaceCount', [bm_void_p, bm_CKDWORD])
## BMMeshTrans_PrepareFaceVertexIndices
# @param trans[in] Type: BMap::BMMeshTransition*. The pointer to corresponding BMMeshTransition.
# @param out_mem[out] Type: LibCmo::CKDWORD*. Use ctypes.byref(data) pass it.
# @return True if no error, otherwise False.
BMMeshTrans_PrepareFaceVertexIndices = _create_bmap_func('BMMeshTrans_PrepareFaceVertexIndices', [bm_void_p, bm_CKDWORD_pp])
## BMMeshTrans_PrepareFaceNormalIndices
# @param trans[in] Type: BMap::BMMeshTransition*. The pointer to corresponding BMMeshTransition.
# @param out_mem[out] Type: LibCmo::CKDWORD*. Use ctypes.byref(data) pass it.
# @return True if no error, otherwise False.
BMMeshTrans_PrepareFaceNormalIndices = _create_bmap_func('BMMeshTrans_PrepareFaceNormalIndices', [bm_void_p, bm_CKDWORD_pp])
## BMMeshTrans_PrepareFaceUVIndices
# @param trans[in] Type: BMap::BMMeshTransition*. The pointer to corresponding BMMeshTransition.
# @param out_mem[out] Type: LibCmo::CKDWORD*. Use ctypes.byref(data) pass it.
# @return True if no error, otherwise False.
BMMeshTrans_PrepareFaceUVIndices = _create_bmap_func('BMMeshTrans_PrepareFaceUVIndices', [bm_void_p, bm_CKDWORD_pp])
## BMMeshTrans_PrepareFaceMtlSlot
# @param trans[in] Type: BMap::BMMeshTransition*. The pointer to corresponding BMMeshTransition.
# @param out_mem[out] Type: LibCmo::CKDWORD*. Use ctypes.byref(data) pass it.
# @return True if no error, otherwise False.
BMMeshTrans_PrepareFaceMtlSlot = _create_bmap_func('BMMeshTrans_PrepareFaceMtlSlot', [bm_void_p, bm_CKDWORD_pp])
## BMMeshTrans_Parse
# @param trans[in] Type: BMap::BMMeshTransition*. The pointer to corresponding BMMeshTransition.
# @param bmfile[in] Type: BMap::BMFile*.
# @param objid[in] Type: LibCmo::CK2::CK_ID.
# @return True if no error, otherwise False.
BMMeshTrans_Parse = _create_bmap_func('BMMeshTrans_Parse', [bm_void_p, bm_void_p, bm_CKID])
## BMObject_GetName
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param out_name[out] Type: LibCmo::CKSTRING. Use ctypes.byref(data) pass it.
# @return True if no error, otherwise False.
BMObject_GetName = _create_bmap_func('BMObject_GetName', [bm_void_p, bm_CKID, bm_CKSTRING_p])
## BMObject_SetName
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param name[in] Type: LibCmo::CKSTRING.
# @return True if no error, otherwise False.
BMObject_SetName = _create_bmap_func('BMObject_SetName', [bm_void_p, bm_CKID, bm_CKSTRING])
## BMGroup_AddObject
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param memberid[in] Type: LibCmo::CK2::CK_ID.
# @return True if no error, otherwise False.
BMGroup_AddObject = _create_bmap_func('BMGroup_AddObject', [bm_void_p, bm_CKID, bm_CKID])
## BMGroup_GetObjectCount
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param out_count[out] Type: LibCmo::CKDWORD. Use ctypes.byref(data) pass it.
# @return True if no error, otherwise False.
BMGroup_GetObjectCount = _create_bmap_func('BMGroup_GetObjectCount', [bm_void_p, bm_CKID, bm_CKDWORD_p])
## BMGroup_GetObject
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param pos[in] Type: LibCmo::CKDWORD.
# @param out_objid[out] Type: LibCmo::CK2::CK_ID. Use ctypes.byref(data) pass it.
# @return True if no error, otherwise False.
BMGroup_GetObject = _create_bmap_func('BMGroup_GetObject', [bm_void_p, bm_CKID, bm_CKDWORD, bm_CKID_p])
## BMTexture_GetFileName
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param out_filename[out] Type: LibCmo::CKSTRING. Use ctypes.byref(data) pass it.
# @return True if no error, otherwise False.
BMTexture_GetFileName = _create_bmap_func('BMTexture_GetFileName', [bm_void_p, bm_CKID, bm_CKSTRING_p])
## BMTexture_LoadImage
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param filename[in] Type: LibCmo::CKSTRING.
# @return True if no error, otherwise False.
BMTexture_LoadImage = _create_bmap_func('BMTexture_LoadImage', [bm_void_p, bm_CKID, bm_CKSTRING])
## BMTexture_SaveImage
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param filename[in] Type: LibCmo::CKSTRING.
# @return True if no error, otherwise False.
BMTexture_SaveImage = _create_bmap_func('BMTexture_SaveImage', [bm_void_p, bm_CKID, bm_CKSTRING])
## BMTexture_GetSaveOptions
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param out_saveopt[out] Type: LibCmo::CK2::CK_TEXTURE_SAVEOPTIONS. Use ctypes.byref(data) pass it.
# @return True if no error, otherwise False.
BMTexture_GetSaveOptions = _create_bmap_func('BMTexture_GetSaveOptions', [bm_void_p, bm_CKID, bm_enum_p])
## BMTexture_SetSaveOptions
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param saveopt[in] Type: LibCmo::CK2::CK_TEXTURE_SAVEOPTIONS.
# @return True if no error, otherwise False.
BMTexture_SetSaveOptions = _create_bmap_func('BMTexture_SetSaveOptions', [bm_void_p, bm_CKID, bm_enum])
## BMTexture_GetVideoFormat
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param out_vfmt[out] Type: LibCmo::VxMath::VX_PIXELFORMAT. Use ctypes.byref(data) pass it.
# @return True if no error, otherwise False.
BMTexture_GetVideoFormat = _create_bmap_func('BMTexture_GetVideoFormat', [bm_void_p, bm_CKID, bm_enum_p])
## BMTexture_SetVideoFormat
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param vfmt[in] Type: LibCmo::VxMath::VX_PIXELFORMAT.
# @return True if no error, otherwise False.
BMTexture_SetVideoFormat = _create_bmap_func('BMTexture_SetVideoFormat', [bm_void_p, bm_CKID, bm_enum])
## BMMaterial_GetDiffuse
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param out_val[out] Type: LibCmo::VxMath::VxColor. Use ctypes.byref(data) pass it.
# @return True if no error, otherwise False.
BMMaterial_GetDiffuse = _create_bmap_func('BMMaterial_GetDiffuse', [bm_void_p, bm_CKID, bm_VxColor_p])
## BMMaterial_SetDiffuse
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param col[in] Type: LibCmo::VxMath::VxColor.
# @return True if no error, otherwise False.
BMMaterial_SetDiffuse = _create_bmap_func('BMMaterial_SetDiffuse', [bm_void_p, bm_CKID, bm_VxColor])
## BMMaterial_GetAmbient
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param out_val[out] Type: LibCmo::VxMath::VxColor. Use ctypes.byref(data) pass it.
# @return True if no error, otherwise False.
BMMaterial_GetAmbient = _create_bmap_func('BMMaterial_GetAmbient', [bm_void_p, bm_CKID, bm_VxColor_p])
## BMMaterial_SetAmbient
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param col[in] Type: LibCmo::VxMath::VxColor.
# @return True if no error, otherwise False.
BMMaterial_SetAmbient = _create_bmap_func('BMMaterial_SetAmbient', [bm_void_p, bm_CKID, bm_VxColor])
## BMMaterial_GetSpecular
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param out_val[out] Type: LibCmo::VxMath::VxColor. Use ctypes.byref(data) pass it.
# @return True if no error, otherwise False.
BMMaterial_GetSpecular = _create_bmap_func('BMMaterial_GetSpecular', [bm_void_p, bm_CKID, bm_VxColor_p])
## BMMaterial_SetSpecular
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param col[in] Type: LibCmo::VxMath::VxColor.
# @return True if no error, otherwise False.
BMMaterial_SetSpecular = _create_bmap_func('BMMaterial_SetSpecular', [bm_void_p, bm_CKID, bm_VxColor])
## BMMaterial_GetEmissive
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param out_val[out] Type: LibCmo::VxMath::VxColor. Use ctypes.byref(data) pass it.
# @return True if no error, otherwise False.
BMMaterial_GetEmissive = _create_bmap_func('BMMaterial_GetEmissive', [bm_void_p, bm_CKID, bm_VxColor_p])
## BMMaterial_SetEmissive
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param col[in] Type: LibCmo::VxMath::VxColor.
# @return True if no error, otherwise False.
BMMaterial_SetEmissive = _create_bmap_func('BMMaterial_SetEmissive', [bm_void_p, bm_CKID, bm_VxColor])
## BMMaterial_GetSpecularPower
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param out_val[out] Type: LibCmo::CKFLOAT. Use ctypes.byref(data) pass it.
# @return True if no error, otherwise False.
BMMaterial_GetSpecularPower = _create_bmap_func('BMMaterial_GetSpecularPower', [bm_void_p, bm_CKID, bm_CKFLOAT_p])
## BMMaterial_SetSpecularPower
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param val[in] Type: LibCmo::CKFLOAT.
# @return True if no error, otherwise False.
BMMaterial_SetSpecularPower = _create_bmap_func('BMMaterial_SetSpecularPower', [bm_void_p, bm_CKID, bm_CKFLOAT])
## BMMaterial_GetTexture
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param out_texid[out] Type: LibCmo::CK2::CK_ID. Use ctypes.byref(data) pass it.
# @return True if no error, otherwise False.
BMMaterial_GetTexture = _create_bmap_func('BMMaterial_GetTexture', [bm_void_p, bm_CKID, bm_CKID_p])
## BMMaterial_SetTexture
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param texid[in] Type: LibCmo::CK2::CK_ID.
# @return True if no error, otherwise False.
BMMaterial_SetTexture = _create_bmap_func('BMMaterial_SetTexture', [bm_void_p, bm_CKID, bm_CKID])
## BMMaterial_GetTextureBorderColor
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param out_val[out] Type: LibCmo::CKDWORD. Use ctypes.byref(data) pass it.
# @return True if no error, otherwise False.
BMMaterial_GetTextureBorderColor = _create_bmap_func('BMMaterial_GetTextureBorderColor', [bm_void_p, bm_CKID, bm_CKDWORD_p])
## BMMaterial_SetTextureBorderColor
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param val[in] Type: LibCmo::CKDWORD.
# @return True if no error, otherwise False.
BMMaterial_SetTextureBorderColor = _create_bmap_func('BMMaterial_SetTextureBorderColor', [bm_void_p, bm_CKID, bm_CKDWORD])
## BMMaterial_GetTextureBlendMode
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param out_val[out] Type: LibCmo::VxMath::VXTEXTURE_BLENDMODE. Use ctypes.byref(data) pass it.
# @return True if no error, otherwise False.
BMMaterial_GetTextureBlendMode = _create_bmap_func('BMMaterial_GetTextureBlendMode', [bm_void_p, bm_CKID, bm_enum_p])
## BMMaterial_SetTextureBlendMode
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param val[in] Type: LibCmo::VxMath::VXTEXTURE_BLENDMODE.
# @return True if no error, otherwise False.
BMMaterial_SetTextureBlendMode = _create_bmap_func('BMMaterial_SetTextureBlendMode', [bm_void_p, bm_CKID, bm_enum])
## BMMaterial_GetTextureMinMode
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param out_val[out] Type: LibCmo::VxMath::VXTEXTURE_FILTERMODE. Use ctypes.byref(data) pass it.
# @return True if no error, otherwise False.
BMMaterial_GetTextureMinMode = _create_bmap_func('BMMaterial_GetTextureMinMode', [bm_void_p, bm_CKID, bm_enum_p])
## BMMaterial_SetTextureMinMode
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param val[in] Type: LibCmo::VxMath::VXTEXTURE_FILTERMODE.
# @return True if no error, otherwise False.
BMMaterial_SetTextureMinMode = _create_bmap_func('BMMaterial_SetTextureMinMode', [bm_void_p, bm_CKID, bm_enum])
## BMMaterial_GetTextureMagMode
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param out_val[out] Type: LibCmo::VxMath::VXTEXTURE_FILTERMODE. Use ctypes.byref(data) pass it.
# @return True if no error, otherwise False.
BMMaterial_GetTextureMagMode = _create_bmap_func('BMMaterial_GetTextureMagMode', [bm_void_p, bm_CKID, bm_enum_p])
## BMMaterial_SetTextureMagMode
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param val[in] Type: LibCmo::VxMath::VXTEXTURE_FILTERMODE.
# @return True if no error, otherwise False.
BMMaterial_SetTextureMagMode = _create_bmap_func('BMMaterial_SetTextureMagMode', [bm_void_p, bm_CKID, bm_enum])
## BMMaterial_GetTextureAddressMode
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param out_val[out] Type: LibCmo::VxMath::VXTEXTURE_ADDRESSMODE. Use ctypes.byref(data) pass it.
# @return True if no error, otherwise False.
BMMaterial_GetTextureAddressMode = _create_bmap_func('BMMaterial_GetTextureAddressMode', [bm_void_p, bm_CKID, bm_enum_p])
## BMMaterial_SetTextureAddressMode
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param val[in] Type: LibCmo::VxMath::VXTEXTURE_ADDRESSMODE.
# @return True if no error, otherwise False.
BMMaterial_SetTextureAddressMode = _create_bmap_func('BMMaterial_SetTextureAddressMode', [bm_void_p, bm_CKID, bm_enum])
## BMMaterial_GetSourceBlend
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param out_val[out] Type: LibCmo::VxMath::VXBLEND_MODE. Use ctypes.byref(data) pass it.
# @return True if no error, otherwise False.
BMMaterial_GetSourceBlend = _create_bmap_func('BMMaterial_GetSourceBlend', [bm_void_p, bm_CKID, bm_enum_p])
## BMMaterial_SetSourceBlend
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param val[in] Type: LibCmo::VxMath::VXBLEND_MODE.
# @return True if no error, otherwise False.
BMMaterial_SetSourceBlend = _create_bmap_func('BMMaterial_SetSourceBlend', [bm_void_p, bm_CKID, bm_enum])
## BMMaterial_GetDestBlend
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param out_val[out] Type: LibCmo::VxMath::VXBLEND_MODE. Use ctypes.byref(data) pass it.
# @return True if no error, otherwise False.
BMMaterial_GetDestBlend = _create_bmap_func('BMMaterial_GetDestBlend', [bm_void_p, bm_CKID, bm_enum_p])
## BMMaterial_SetDestBlend
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param val[in] Type: LibCmo::VxMath::VXBLEND_MODE.
# @return True if no error, otherwise False.
BMMaterial_SetDestBlend = _create_bmap_func('BMMaterial_SetDestBlend', [bm_void_p, bm_CKID, bm_enum])
## BMMaterial_GetFillMode
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param out_val[out] Type: LibCmo::VxMath::VXFILL_MODE. Use ctypes.byref(data) pass it.
# @return True if no error, otherwise False.
BMMaterial_GetFillMode = _create_bmap_func('BMMaterial_GetFillMode', [bm_void_p, bm_CKID, bm_enum_p])
## BMMaterial_SetFillMode
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param val[in] Type: LibCmo::VxMath::VXFILL_MODE.
# @return True if no error, otherwise False.
BMMaterial_SetFillMode = _create_bmap_func('BMMaterial_SetFillMode', [bm_void_p, bm_CKID, bm_enum])
## BMMaterial_GetShadeMode
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param out_val[out] Type: LibCmo::VxMath::VXSHADE_MODE. Use ctypes.byref(data) pass it.
# @return True if no error, otherwise False.
BMMaterial_GetShadeMode = _create_bmap_func('BMMaterial_GetShadeMode', [bm_void_p, bm_CKID, bm_enum_p])
## BMMaterial_SetShadeMode
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param val[in] Type: LibCmo::VxMath::VXSHADE_MODE.
# @return True if no error, otherwise False.
BMMaterial_SetShadeMode = _create_bmap_func('BMMaterial_SetShadeMode', [bm_void_p, bm_CKID, bm_enum])
## BMMaterial_GetAlphaTestEnabled
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param out_val[out] Type: bool. Use ctypes.byref(data) pass it.
# @return True if no error, otherwise False.
BMMaterial_GetAlphaTestEnabled = _create_bmap_func('BMMaterial_GetAlphaTestEnabled', [bm_void_p, bm_CKID, bm_bool_p])
## BMMaterial_SetAlphaTestEnabled
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param enabled[in] Type: bool.
# @return True if no error, otherwise False.
BMMaterial_SetAlphaTestEnabled = _create_bmap_func('BMMaterial_SetAlphaTestEnabled', [bm_void_p, bm_CKID, bm_bool])
## BMMaterial_GetAlphaBlendEnabled
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param out_val[out] Type: bool. Use ctypes.byref(data) pass it.
# @return True if no error, otherwise False.
BMMaterial_GetAlphaBlendEnabled = _create_bmap_func('BMMaterial_GetAlphaBlendEnabled', [bm_void_p, bm_CKID, bm_bool_p])
## BMMaterial_SetAlphaBlendEnabled
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param enabled[in] Type: bool.
# @return True if no error, otherwise False.
BMMaterial_SetAlphaBlendEnabled = _create_bmap_func('BMMaterial_SetAlphaBlendEnabled', [bm_void_p, bm_CKID, bm_bool])
## BMMaterial_GetPerspectiveCorrectionEnabled
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param out_val[out] Type: bool. Use ctypes.byref(data) pass it.
# @return True if no error, otherwise False.
BMMaterial_GetPerspectiveCorrectionEnabled = _create_bmap_func('BMMaterial_GetPerspectiveCorrectionEnabled', [bm_void_p, bm_CKID, bm_bool_p])
## BMMaterial_SetPerspectiveCorrectionEnabled
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param enabled[in] Type: bool.
# @return True if no error, otherwise False.
BMMaterial_SetPerspectiveCorrectionEnabled = _create_bmap_func('BMMaterial_SetPerspectiveCorrectionEnabled', [bm_void_p, bm_CKID, bm_bool])
## BMMaterial_GetZWriteEnabled
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param out_val[out] Type: bool. Use ctypes.byref(data) pass it.
# @return True if no error, otherwise False.
BMMaterial_GetZWriteEnabled = _create_bmap_func('BMMaterial_GetZWriteEnabled', [bm_void_p, bm_CKID, bm_bool_p])
## BMMaterial_SetZWriteEnabled
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param enabled[in] Type: bool.
# @return True if no error, otherwise False.
BMMaterial_SetZWriteEnabled = _create_bmap_func('BMMaterial_SetZWriteEnabled', [bm_void_p, bm_CKID, bm_bool])
## BMMaterial_GetTwoSidedEnabled
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param out_val[out] Type: bool. Use ctypes.byref(data) pass it.
# @return True if no error, otherwise False.
BMMaterial_GetTwoSidedEnabled = _create_bmap_func('BMMaterial_GetTwoSidedEnabled', [bm_void_p, bm_CKID, bm_bool_p])
## BMMaterial_SetTwoSidedEnabled
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param enabled[in] Type: bool.
# @return True if no error, otherwise False.
BMMaterial_SetTwoSidedEnabled = _create_bmap_func('BMMaterial_SetTwoSidedEnabled', [bm_void_p, bm_CKID, bm_bool])
## BMMaterial_GetAlphaRef
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param out_val[out] Type: LibCmo::CKBYTE. Use ctypes.byref(data) pass it.
# @return True if no error, otherwise False.
BMMaterial_GetAlphaRef = _create_bmap_func('BMMaterial_GetAlphaRef', [bm_void_p, bm_CKID, bm_CKBYTE_p])
## BMMaterial_SetAlphaRef
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param val[in] Type: LibCmo::CKBYTE.
# @return True if no error, otherwise False.
BMMaterial_SetAlphaRef = _create_bmap_func('BMMaterial_SetAlphaRef', [bm_void_p, bm_CKID, bm_CKBYTE])
## BMMaterial_GetAlphaFunc
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param out_val[out] Type: LibCmo::VxMath::VXCMPFUNC. Use ctypes.byref(data) pass it.
# @return True if no error, otherwise False.
BMMaterial_GetAlphaFunc = _create_bmap_func('BMMaterial_GetAlphaFunc', [bm_void_p, bm_CKID, bm_enum_p])
## BMMaterial_SetAlphaFunc
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param val[in] Type: LibCmo::VxMath::VXCMPFUNC.
# @return True if no error, otherwise False.
BMMaterial_SetAlphaFunc = _create_bmap_func('BMMaterial_SetAlphaFunc', [bm_void_p, bm_CKID, bm_enum])
## BMMaterial_GetZFunc
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param out_val[out] Type: LibCmo::VxMath::VXCMPFUNC. Use ctypes.byref(data) pass it.
# @return True if no error, otherwise False.
BMMaterial_GetZFunc = _create_bmap_func('BMMaterial_GetZFunc', [bm_void_p, bm_CKID, bm_enum_p])
## BMMaterial_SetZFunc
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param val[in] Type: LibCmo::VxMath::VXCMPFUNC.
# @return True if no error, otherwise False.
BMMaterial_SetZFunc = _create_bmap_func('BMMaterial_SetZFunc', [bm_void_p, bm_CKID, bm_enum])
## BMMesh_GetLitMode
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param out_mode[out] Type: LibCmo::VxMath::VXMESH_LITMODE. Use ctypes.byref(data) pass it.
# @return True if no error, otherwise False.
BMMesh_GetLitMode = _create_bmap_func('BMMesh_GetLitMode', [bm_void_p, bm_CKID, bm_enum_p])
## BMMesh_SetLitMode
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param mode[in] Type: LibCmo::VxMath::VXMESH_LITMODE.
# @return True if no error, otherwise False.
BMMesh_SetLitMode = _create_bmap_func('BMMesh_SetLitMode', [bm_void_p, bm_CKID, bm_enum])
## BMMesh_GetVertexCount
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param out_count[out] Type: LibCmo::CKDWORD. Use ctypes.byref(data) pass it.
# @return True if no error, otherwise False.
BMMesh_GetVertexCount = _create_bmap_func('BMMesh_GetVertexCount', [bm_void_p, bm_CKID, bm_CKDWORD_p])
## BMMesh_SetVertexCount
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param count[in] Type: LibCmo::CKDWORD.
# @return True if no error, otherwise False.
BMMesh_SetVertexCount = _create_bmap_func('BMMesh_SetVertexCount', [bm_void_p, bm_CKID, bm_CKDWORD])
## BMMesh_GetVertexPositions
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param out_mem[out] Type: LibCmo::VxMath::VxVector3*. Use ctypes.byref(data) pass it.
# @return True if no error, otherwise False.
BMMesh_GetVertexPositions = _create_bmap_func('BMMesh_GetVertexPositions', [bm_void_p, bm_CKID, bm_VxVector3_pp])
## BMMesh_GetVertexNormals
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param out_mem[out] Type: LibCmo::VxMath::VxVector3*. Use ctypes.byref(data) pass it.
# @return True if no error, otherwise False.
BMMesh_GetVertexNormals = _create_bmap_func('BMMesh_GetVertexNormals', [bm_void_p, bm_CKID, bm_VxVector3_pp])
## BMMesh_GetVertexUVs
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param out_mem[out] Type: LibCmo::VxMath::VxVector2*. Use ctypes.byref(data) pass it.
# @return True if no error, otherwise False.
BMMesh_GetVertexUVs = _create_bmap_func('BMMesh_GetVertexUVs', [bm_void_p, bm_CKID, bm_VxVector2_pp])
## BMMesh_GetFaceCount
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param out_count[out] Type: LibCmo::CKDWORD. Use ctypes.byref(data) pass it.
# @return True if no error, otherwise False.
BMMesh_GetFaceCount = _create_bmap_func('BMMesh_GetFaceCount', [bm_void_p, bm_CKID, bm_CKDWORD_p])
## BMMesh_SetFaceCount
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param count[in] Type: LibCmo::CKDWORD.
# @return True if no error, otherwise False.
BMMesh_SetFaceCount = _create_bmap_func('BMMesh_SetFaceCount', [bm_void_p, bm_CKID, bm_CKDWORD])
## BMMesh_GetFaceIndices
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param out_mem[out] Type: LibCmo::CKWORD*. Use ctypes.byref(data) pass it.
# @return True if no error, otherwise False.
BMMesh_GetFaceIndices = _create_bmap_func('BMMesh_GetFaceIndices', [bm_void_p, bm_CKID, bm_CKWORD_pp])
## BMMesh_GetFaceMaterialSlotIndexs
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param out_mem[out] Type: LibCmo::CKWORD*. Use ctypes.byref(data) pass it.
# @return True if no error, otherwise False.
BMMesh_GetFaceMaterialSlotIndexs = _create_bmap_func('BMMesh_GetFaceMaterialSlotIndexs', [bm_void_p, bm_CKID, bm_CKWORD_pp])
## BMMesh_GetMaterialSlotCount
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param out_count[out] Type: LibCmo::CKDWORD. Use ctypes.byref(data) pass it.
# @return True if no error, otherwise False.
BMMesh_GetMaterialSlotCount = _create_bmap_func('BMMesh_GetMaterialSlotCount', [bm_void_p, bm_CKID, bm_CKDWORD_p])
## BMMesh_SetMaterialSlotCount
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param count[in] Type: LibCmo::CKDWORD.
# @return True if no error, otherwise False.
BMMesh_SetMaterialSlotCount = _create_bmap_func('BMMesh_SetMaterialSlotCount', [bm_void_p, bm_CKID, bm_CKDWORD])
## BMMesh_GetMaterialSlot
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param index[in] Type: LibCmo::CKDWORD.
# @param out_mtlid[out] Type: LibCmo::CK2::CK_ID. Use ctypes.byref(data) pass it.
# @return True if no error, otherwise False.
BMMesh_GetMaterialSlot = _create_bmap_func('BMMesh_GetMaterialSlot', [bm_void_p, bm_CKID, bm_CKDWORD, bm_CKID_p])
## BMMesh_SetMaterialSlot
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param index[in] Type: LibCmo::CKDWORD.
# @param mtlid[in] Type: LibCmo::CK2::CK_ID.
# @return True if no error, otherwise False.
BMMesh_SetMaterialSlot = _create_bmap_func('BMMesh_SetMaterialSlot', [bm_void_p, bm_CKID, bm_CKDWORD, bm_CKID])
## BM3dEntity_GetWorldMatrix
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param out_mat[out] Type: LibCmo::VxMath::VxMatrix. Use ctypes.byref(data) pass it.
# @return True if no error, otherwise False.
BM3dEntity_GetWorldMatrix = _create_bmap_func('BM3dEntity_GetWorldMatrix', [bm_void_p, bm_CKID, bm_VxMatrix_p])
## BM3dEntity_SetWorldMatrix
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param mat[in] Type: LibCmo::VxMath::VxMatrix.
# @return True if no error, otherwise False.
BM3dEntity_SetWorldMatrix = _create_bmap_func('BM3dEntity_SetWorldMatrix', [bm_void_p, bm_CKID, bm_VxMatrix])
## BM3dEntity_GetCurrentMesh
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param out_meshid[out] Type: LibCmo::CK2::CK_ID. Use ctypes.byref(data) pass it.
# @return True if no error, otherwise False.
BM3dEntity_GetCurrentMesh = _create_bmap_func('BM3dEntity_GetCurrentMesh', [bm_void_p, bm_CKID, bm_CKID_p])
## BM3dEntity_SetCurrentMesh
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param meshid[in] Type: LibCmo::CK2::CK_ID.
# @return True if no error, otherwise False.
BM3dEntity_SetCurrentMesh = _create_bmap_func('BM3dEntity_SetCurrentMesh', [bm_void_p, bm_CKID, bm_CKID])
## BM3dEntity_GetVisibility
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param out_isVisible[out] Type: bool. Use ctypes.byref(data) pass it.
# @return True if no error, otherwise False.
BM3dEntity_GetVisibility = _create_bmap_func('BM3dEntity_GetVisibility', [bm_void_p, bm_CKID, bm_bool_p])
## BM3dEntity_SetVisibility
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param is_visible[in] Type: bool.
# @return True if no error, otherwise False.
BM3dEntity_SetVisibility = _create_bmap_func('BM3dEntity_SetVisibility', [bm_void_p, bm_CKID, bm_bool])
## BMLight_GetType
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param out_val[out] Type: LibCmo::VxMath::VXLIGHT_TYPE. Use ctypes.byref(data) pass it.
# @return True if no error, otherwise False.
BMLight_GetType = _create_bmap_func('BMLight_GetType', [bm_void_p, bm_CKID, bm_enum_p])
## BMLight_SetType
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param val[in] Type: LibCmo::VxMath::VXLIGHT_TYPE.
# @return True if no error, otherwise False.
BMLight_SetType = _create_bmap_func('BMLight_SetType', [bm_void_p, bm_CKID, bm_enum])
## BMLight_GetColor
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param out_val[out] Type: LibCmo::VxMath::VxColor. Use ctypes.byref(data) pass it.
# @return True if no error, otherwise False.
BMLight_GetColor = _create_bmap_func('BMLight_GetColor', [bm_void_p, bm_CKID, bm_VxColor_p])
## BMLight_SetColor
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param col[in] Type: LibCmo::VxMath::VxColor.
# @return True if no error, otherwise False.
BMLight_SetColor = _create_bmap_func('BMLight_SetColor', [bm_void_p, bm_CKID, bm_VxColor])
## BMLight_GetConstantAttenuation
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param out_val[out] Type: LibCmo::CKFLOAT. Use ctypes.byref(data) pass it.
# @return True if no error, otherwise False.
BMLight_GetConstantAttenuation = _create_bmap_func('BMLight_GetConstantAttenuation', [bm_void_p, bm_CKID, bm_CKFLOAT_p])
## BMLight_SetConstantAttenuation
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param val[in] Type: LibCmo::CKFLOAT.
# @return True if no error, otherwise False.
BMLight_SetConstantAttenuation = _create_bmap_func('BMLight_SetConstantAttenuation', [bm_void_p, bm_CKID, bm_CKFLOAT])
## BMLight_GetLinearAttenuation
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param out_val[out] Type: LibCmo::CKFLOAT. Use ctypes.byref(data) pass it.
# @return True if no error, otherwise False.
BMLight_GetLinearAttenuation = _create_bmap_func('BMLight_GetLinearAttenuation', [bm_void_p, bm_CKID, bm_CKFLOAT_p])
## BMLight_SetLinearAttenuation
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param val[in] Type: LibCmo::CKFLOAT.
# @return True if no error, otherwise False.
BMLight_SetLinearAttenuation = _create_bmap_func('BMLight_SetLinearAttenuation', [bm_void_p, bm_CKID, bm_CKFLOAT])
## BMLight_GetQuadraticAttenuation
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param out_val[out] Type: LibCmo::CKFLOAT. Use ctypes.byref(data) pass it.
# @return True if no error, otherwise False.
BMLight_GetQuadraticAttenuation = _create_bmap_func('BMLight_GetQuadraticAttenuation', [bm_void_p, bm_CKID, bm_CKFLOAT_p])
## BMLight_SetQuadraticAttenuation
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param val[in] Type: LibCmo::CKFLOAT.
# @return True if no error, otherwise False.
BMLight_SetQuadraticAttenuation = _create_bmap_func('BMLight_SetQuadraticAttenuation', [bm_void_p, bm_CKID, bm_CKFLOAT])
## BMLight_GetRange
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param out_val[out] Type: LibCmo::CKFLOAT. Use ctypes.byref(data) pass it.
# @return True if no error, otherwise False.
BMLight_GetRange = _create_bmap_func('BMLight_GetRange', [bm_void_p, bm_CKID, bm_CKFLOAT_p])
## BMLight_SetRange
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param val[in] Type: LibCmo::CKFLOAT.
# @return True if no error, otherwise False.
BMLight_SetRange = _create_bmap_func('BMLight_SetRange', [bm_void_p, bm_CKID, bm_CKFLOAT])
## BMLight_GetHotSpot
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param out_val[out] Type: LibCmo::CKFLOAT. Use ctypes.byref(data) pass it.
# @return True if no error, otherwise False.
BMLight_GetHotSpot = _create_bmap_func('BMLight_GetHotSpot', [bm_void_p, bm_CKID, bm_CKFLOAT_p])
## BMLight_SetHotSpot
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param val[in] Type: LibCmo::CKFLOAT.
# @return True if no error, otherwise False.
BMLight_SetHotSpot = _create_bmap_func('BMLight_SetHotSpot', [bm_void_p, bm_CKID, bm_CKFLOAT])
## BMLight_GetFalloff
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param out_val[out] Type: LibCmo::CKFLOAT. Use ctypes.byref(data) pass it.
# @return True if no error, otherwise False.
BMLight_GetFalloff = _create_bmap_func('BMLight_GetFalloff', [bm_void_p, bm_CKID, bm_CKFLOAT_p])
## BMLight_SetFalloff
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param val[in] Type: LibCmo::CKFLOAT.
# @return True if no error, otherwise False.
BMLight_SetFalloff = _create_bmap_func('BMLight_SetFalloff', [bm_void_p, bm_CKID, bm_CKFLOAT])
## BMLight_GetFalloffShape
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param out_val[out] Type: LibCmo::CKFLOAT. Use ctypes.byref(data) pass it.
# @return True if no error, otherwise False.
BMLight_GetFalloffShape = _create_bmap_func('BMLight_GetFalloffShape', [bm_void_p, bm_CKID, bm_CKFLOAT_p])
## BMLight_SetFalloffShape
# @param bmfile[in] Type: BMap::BMFile*. The pointer to corresponding BMFile.
# @param objid[in] Type: LibCmo::CK2::CK_ID. The CKID of object you accessing.
# @param val[in] Type: LibCmo::CKFLOAT.
# @return True if no error, otherwise False.
BMLight_SetFalloffShape = _create_bmap_func('BMLight_SetFalloffShape', [bm_void_p, bm_CKID, bm_CKFLOAT])
##### GENERATED FUNCTIONS END #####
#endregion

View File

@@ -1,327 +0,0 @@
import typing, enum
ConstVxVector2 = tuple[float, float]
ConstVxVector3 = tuple[float, float, float]
ConstVxVector4 = tuple[float, float, float, float]
class VxVector2():
x: float
y: float
def __init__(self, _x: float = 0.0, _y: float = 0.0):
self.x = _x
self.y = _y
def from_const(self, cv: ConstVxVector2) -> None:
(self.x, self.y, ) = cv
def to_const(self) -> ConstVxVector2:
return (self.x, self.y, )
class VxVector3():
x: float
y: float
z: float
def __init__(self, _x: float = 0.0, _y: float = 0.0, _z: float = 0.0):
self.x = _x
self.y = _y
self.z = _z
def from_const(self, cv: ConstVxVector3) -> None:
(self.x, self.y, self.z) = cv
def to_const(self) -> ConstVxVector3:
return (self.x, self.y, self.z)
ConstCKFaceIndices = tuple[int, int, int]
class CKFaceIndices():
i1: int
i2: int
i3: int
def __init__(self, i1_: int = 0, i2_: int = 0, i3_: int = 0):
self.i1 = i1_
self.i2 = i2_
self.i3 = i3_
def from_const(self, cv: ConstCKFaceIndices) -> None:
(self.i1, self.i2, self.i3) = cv
def to_const(self) -> ConstCKFaceIndices:
return (self.i1, self.i2, self.i3)
ConstVxColorRGBA = tuple[float, float, float, float]
ConstVxColorRGB = tuple[float, float, float]
class VxColor():
"""
The Color struct support RGBA.
"""
a: float
r: float
g: float
b: float
def __init__(self, _r: float = 0.0, _g: float = 0.0, _b: float = 0.0, _a: float = 1.0):
self.r = _r
self.g = _g
self.b = _b
self.a = _a
self.regulate()
def to_const_rgba(self) -> ConstVxColorRGBA:
return (self.r, self.g, self.b, self.a)
def to_const_rgb(self) -> ConstVxColorRGB:
return (self.r, self.g, self.b)
def from_const_rgba(self, val: ConstVxColorRGBA) -> None:
(self.r, self.g, self.b, self.a) = val
self.regulate()
def from_const_rgb(self, val: ConstVxColorRGB) -> None:
(self.r, self.g, self.b) = val
self.a = 1.0
self.regulate()
def from_dword(self, val: int) -> None:
self.b = float(val & 0xFF) / 255.0
val >>= 8
self.g = float(val & 0xFF) / 255.0
val >>= 8
self.r = float(val & 0xFF) / 255.0
val >>= 8
self.a = float(val & 0xFF) / 255.0
val >>= 8
def to_dword(self) -> int:
# regulate self
self.regulate()
# construct value
val: int = 0
val |= int(self.a * 255)
val <<= 8
val |= int(self.r * 255)
val <<= 8
val |= int(self.g * 255)
val <<= 8
val |= int(self.b * 255)
return val
def clone(self):
return VxColor(self.r, self.g, self.b, self.a)
@staticmethod
def _clamp_factor(val: float) -> float:
if val > 1.0: return 1.0
elif val < 0.0: return 0.0
else: return val
def regulate(self):
self.a = VxColor._clamp_factor(self.a)
self.r = VxColor._clamp_factor(self.r)
self.g = VxColor._clamp_factor(self.g)
self.b = VxColor._clamp_factor(self.b)
ConstVxMatrix = tuple[
float, float, float, float,
float, float, float, float,
float, float, float, float,
float, float, float, float
]
class VxMatrix():
"""
The Matrix representation.
The bracket statement exactly equal with Virtools.
"""
data: list[list[float]]
def __init__(self):
# init array
self.data = [[0] * 4 for i in range(4)]
# set to identy
self.reset()
def _get_raw(self) -> list[list[float]]:
return self.data
def reset(self) -> None:
# reset to identy
for i in range(4):
for j in range(4):
self.data[i][j] = 0.0
self.data[0][0] = 1.0
self.data[1][1] = 1.0
self.data[2][2] = 1.0
self.data[3][3] = 1.0
def from_const(self, cm: ConstVxMatrix) -> None:
(
self.data[0][0], self.data[0][1], self.data[0][2], self.data[0][3],
self.data[1][0], self.data[1][1], self.data[1][2], self.data[1][3],
self.data[2][0], self.data[2][1], self.data[2][2], self.data[2][3],
self.data[3][0], self.data[3][1], self.data[3][2], self.data[3][3]
) = cm
def to_const(self) -> ConstVxMatrix:
return (
self.data[0][0], self.data[0][1], self.data[0][2], self.data[0][3],
self.data[1][0], self.data[1][1], self.data[1][2], self.data[1][3],
self.data[2][0], self.data[2][1], self.data[2][2], self.data[2][3],
self.data[3][0], self.data[3][1], self.data[3][2], self.data[3][3]
)
class CK_TEXTURE_SAVEOPTIONS(enum.IntEnum):
"""!
Specify the way textures or sprites will be saved
"""
CKTEXTURE_RAWDATA = 0 ##< Save raw data inside file. The bitmap is saved in a raw 32 bit per pixel format.
CKTEXTURE_EXTERNAL = 1 ##< Store only the file name for the texture. The bitmap file must be present in the bitmap paths when loading the composition.
CKTEXTURE_IMAGEFORMAT = 2 ##< Save using format specified. The bitmap data will be converted to the specified format by the correspondant bitmap plugin and saved inside file.
CKTEXTURE_USEGLOBAL = 3 ##< Use Global settings, that is the settings given with CKContext::SetGlobalImagesSaveOptions. (Not valid when using CKContext::SetImagesSaveOptions).
CKTEXTURE_INCLUDEORIGINALFILE = 4 ##< Insert original image file inside CMO file. The bitmap file that was used originally for the texture or sprite will be append to the composition file and extracted when the file is loaded.
class VX_PIXELFORMAT(enum.IntEnum):
"""!
Pixel format types.
"""
#UNKNOWN_PF = 0 ##< Unknown pixel format
_32_ARGB8888 = 1 ##< 32-bit ARGB pixel format with alpha
_32_RGB888 = 2 ##< 32-bit RGB pixel format without alpha
_24_RGB888 = 3 ##< 24-bit RGB pixel format
_16_RGB565 = 4 ##< 16-bit RGB pixel format
_16_RGB555 = 5 ##< 16-bit RGB pixel format (5 bits per color)
_16_ARGB1555 = 6 ##< 16-bit ARGB pixel format (5 bits per color + 1 bit for alpha)
_16_ARGB4444 = 7 ##< 16-bit ARGB pixel format (4 bits per color)
_8_RGB332 = 8 ##< 8-bit RGB pixel format
_8_ARGB2222 = 9 ##< 8-bit ARGB pixel format
_32_ABGR8888 = 10 ##< 32-bit ABGR pixel format
_32_RGBA8888 = 11 ##< 32-bit RGBA pixel format
_32_BGRA8888 = 12 ##< 32-bit BGRA pixel format
_32_BGR888 = 13 ##< 32-bit BGR pixel format
_24_BGR888 = 14 ##< 24-bit BGR pixel format
_16_BGR565 = 15 ##< 16-bit BGR pixel format
_16_BGR555 = 16 ##< 16-bit BGR pixel format (5 bits per color)
_16_ABGR1555 = 17 ##< 16-bit ABGR pixel format (5 bits per color + 1 bit for alpha)
_16_ABGR4444 = 18 ##< 16-bit ABGR pixel format (4 bits per color)
_DXT1 = 19 ##< S3/DirectX Texture Compression 1
_DXT2 = 20 ##< S3/DirectX Texture Compression 2
_DXT3 = 21 ##< S3/DirectX Texture Compression 3
_DXT4 = 22 ##< S3/DirectX Texture Compression 4
_DXT5 = 23 ##< S3/DirectX Texture Compression 5
_16_V8U8 = 24 ##< 16-bit Bump Map format format (8 bits per color)
_32_V16U16 = 25 ##< 32-bit Bump Map format format (16 bits per color)
_16_L6V5U5 = 26 ##< 16-bit Bump Map format format with luminance
_32_X8L8V8U8 = 27 ##< 32-bit Bump Map format format with luminance
_8_ABGR8888_CLUT = 28 ##< 8 bits indexed CLUT (ABGR)
_8_ARGB8888_CLUT = 29 ##< 8 bits indexed CLUT (ARGB)
_4_ABGR8888_CLUT = 30 ##< 4 bits indexed CLUT (ABGR)
_4_ARGB8888_CLUT = 31 ##< 4 bits indexed CLUT (ARGB)
class VXLIGHT_TYPE(enum.IntEnum):
"""!
Light type
"""
VX_LIGHTPOINT = 1 ##< The Light is a point of light
VX_LIGHTSPOT = 2 ##< The light is a spotlight
VX_LIGHTDIREC = 3 ##< The light is directional light : Lights comes from an infinite point so only direction of light can be given
#VX_LIGHTPARA = 4 ##< Obsolete, do not use
class VXTEXTURE_BLENDMODE(enum.IntEnum):
"""!
Blend Mode Flags
"""
VXTEXTUREBLEND_DECAL = 1 ##< Texture replace any material information
VXTEXTUREBLEND_MODULATE = 2 ##< Texture and material are combine. Alpha information of the texture replace material alpha component.
VXTEXTUREBLEND_DECALALPHA = 3 ##< Alpha information in the texture specify how material and texture are combined. Alpha information of the texture replace material alpha component.
VXTEXTUREBLEND_MODULATEALPHA = 4 ##< Alpha information in the texture specify how material and texture are combined
VXTEXTUREBLEND_DECALMASK = 5
VXTEXTUREBLEND_MODULATEMASK = 6
VXTEXTUREBLEND_COPY = 7 ##< Equivalent to DECAL
VXTEXTUREBLEND_ADD = 8
VXTEXTUREBLEND_DOTPRODUCT3 = 9 ##< Perform a Dot Product 3 between texture (normal map) and a referential vector given in VXRENDERSTATE_TEXTUREFACTOR.
VXTEXTUREBLEND_MAX = 10
class VXTEXTURE_FILTERMODE(enum.IntEnum):
"""!
Filter Mode Options
"""
VXTEXTUREFILTER_NEAREST = 1 ##< No Filter
VXTEXTUREFILTER_LINEAR = 2 ##< Bilinear Interpolation
VXTEXTUREFILTER_MIPNEAREST = 3 ##< Mip mapping
VXTEXTUREFILTER_MIPLINEAR = 4 ##< Mip Mapping with Bilinear interpolation
VXTEXTUREFILTER_LINEARMIPNEAREST = 5 ##< Mip Mapping with Bilinear interpolation between mipmap levels.
VXTEXTUREFILTER_LINEARMIPLINEAR = 6 ##< Trilinear Filtering
VXTEXTUREFILTER_ANISOTROPIC = 7 ##< Anisotropic filtering
class VXTEXTURE_ADDRESSMODE(enum.IntEnum):
"""!
Texture addressing modes.
"""
VXTEXTURE_ADDRESSWRAP = 1 ##< Default mesh wrap mode is used (see CKMesh::SetWrapMode)
VXTEXTURE_ADDRESSMIRROR = 2 ##< Texture coordinates outside the range [0..1] are flipped evenly.
VXTEXTURE_ADDRESSCLAMP = 3 ##< Texture coordinates greater than 1.0 are set to 1.0, and values less than 0.0 are set to 0.0.
VXTEXTURE_ADDRESSBORDER = 4 ##< When texture coordinates are greater than 1.0 or less than 0.0 texture is set to a color defined in CKMaterial::SetTextureBorderColor.
VXTEXTURE_ADDRESSMIRRORONCE = 5 ##<
class VXBLEND_MODE(enum.IntEnum):
"""!
Blending Mode options
"""
VXBLEND_ZERO = 1 ##< Blend factor is (0, 0, 0, 0).
VXBLEND_ONE = 2 ##< Blend factor is (1, 1, 1, 1).
VXBLEND_SRCCOLOR = 3 ##< Blend factor is (Rs, Gs, Bs, As).
VXBLEND_INVSRCCOLOR = 4 ##< Blend factor is (1-Rs, 1-Gs, 1-Bs, 1-As).
VXBLEND_SRCALPHA = 5 ##< Blend factor is (As, As, As, As).
VXBLEND_INVSRCALPHA = 6 ##< Blend factor is (1-As, 1-As, 1-As, 1-As).
VXBLEND_DESTALPHA = 7 ##< Blend factor is (Ad, Ad, Ad, Ad).
VXBLEND_INVDESTALPHA = 8 ##< Blend factor is (1-Ad, 1-Ad, 1-Ad, 1-Ad).
VXBLEND_DESTCOLOR = 9 ##< Blend factor is (Rd, Gd, Bd, Ad).
VXBLEND_INVDESTCOLOR = 10 ##< Blend factor is (1-Rd, 1-Gd, 1-Bd, 1-Ad).
VXBLEND_SRCALPHASAT = 11 ##< Blend factor is (f, f, f, 1); f = min(As, 1-Ad).
#VXBLEND_BOTHSRCALPHA = 12 ##< Source blend factor is (As, As, As, As) and destination blend factor is (1-As, 1-As, 1-As, 1-As)
#VXBLEND_BOTHINVSRCALPHA = 13 ##< Source blend factor is (1-As, 1-As, 1-As, 1-As) and destination blend factor is (As, As, As, As)
class VXFILL_MODE(enum.IntEnum):
"""!
Fill Mode Options
"""
VXFILL_POINT = 1 ##< Vertices rendering
VXFILL_WIREFRAME = 2 ##< Edges rendering
VXFILL_SOLID = 3 ##< Face rendering
class VXSHADE_MODE(enum.IntEnum):
"""!
Shade Mode Options
"""
VXSHADE_FLAT = 1 ##< Flat Shading
VXSHADE_GOURAUD = 2 ##< Gouraud Shading
VXSHADE_PHONG = 3 ##< Phong Shading (Not yet supported by most implementation)
class VXCMPFUNC(enum.IntEnum):
"""!
Comparison Function
"""
VXCMP_NEVER = 1 ##< Always fail the test.
VXCMP_LESS = 2 ##< Accept if value if less than current value.
VXCMP_EQUAL = 3 ##< Accept if value if equal than current value.
VXCMP_LESSEQUAL = 4 ##< Accept if value if less or equal than current value.
VXCMP_GREATER = 5 ##< Accept if value if greater than current value.
VXCMP_NOTEQUAL = 6 ##< Accept if value if different than current value.
VXCMP_GREATEREQUAL = 7 ##< Accept if value if greater or equal current value.
VXCMP_ALWAYS = 8 ##< Always accept the test.
class VXMESH_LITMODE(enum.IntEnum):
"""!
{filename:VXMESH_LITMODE}
Summary: Mesh lighting options
Remarks:
+ The VXMESH_LITMODE is used by CKMesh::SetLitMode to specify how lighting is done.
See Also: CKMaterial,CKMesh
"""
VX_PRELITMESH = 0 ##< Lighting use color information store with vertices
VX_LITMESH = 1 ##< Lighting is done by renderer using normals and face material information.

View File

@@ -1,9 +0,0 @@
# PyBMap
The real scripts are placed in sub PyBMap folder. This folder is served for testbench scripts placing. You can run `testbench.py` to do a basic test for PyBMap but you may need some essential files to run this testbench which were written in `testbench.py`.
The native BMap library should be placed in sub PyBMap folder, and I have used gitignore file to filter them. The native BMap library must be named as `BMap.dll` (in Windows), `BMap.so` (in Linux or BSD), or `BMap.dylib` (in macOS). If you still can not load BMap or your system is not listed above, you should name it as `BMap.bin`.
Please note the most content of `virtools_types.py` are generated by EnumsMigration sub-project. Additionally the most content of `bmap.py` is generated by BMapBindings. So if some structs are updated, do not forget checking these files.
Since BMap 0.3.0, testbench use command line arguments, instead of hardcode variables in code, as the arguments of BMap. It is convenient that debug BMapSharp without any modification of source code. For a brief instruction, you may need to launch BMapSharpTestbench in following command (just an example. you can modify it as you wished): `py testbench.py --file-path "LightCameraTest.nmo" --temp-dir "Temp" --texture-dir "F:/Ballance/Ballance/Textures" --encodings cp1252 gb2312`.

View File

@@ -1,178 +0,0 @@
import os
import argparse
import PyBMap.bmap_wrapper as bmap
def main(file_name: str, temp_folder: str, texture_folder: str, encodings: tuple[str, ...]) -> None:
input(f'Python PID is {os.getpid()}. Waiting for debugger, press any key to continue...')
# file_name: str = 'LightCameraTest.nmo'
# temp_folder: str = 'Temp'
# texture_folder: str = 'F:\\Ballance\\Ballance\\Textures'
# encodings: tuple[str, ...] = ('cp1252', )
with bmap.BMFileReader(file_name, temp_folder, texture_folder, encodings) as reader:
test_common(reader)
test_equatable(reader)
def test_common(reader: bmap.BMFileReader):
# print('===== Groups =====')
# for gp in reader.get_groups():
# print(gp.get_name())
# for gp_item in gp.get_objects():
# print(f'\t{gp_item.get_name()}')
# print('===== 3dObjects =====')
# for obj in reader.get_3dobjects():
# print(obj.get_name())
# current_mesh = obj.get_current_mesh()
# mesh_name = '<null>' if current_mesh is None else current_mesh.get_name()
# print(f'\tMesh: {mesh_name}')
# print(f'\tVisibility: {obj.get_visibility()}')
# print(f'\tMatrix: {obj.get_world_matrix().to_const()}')
# print('===== Meshes =====')
# for mesh in reader.get_meshs():
# print(mesh.get_name())
# print(f'\tLit Mode: {mesh.get_lit_mode()}')
# print(f'\tVertex Count: {mesh.get_vertex_count()}')
# print(f'\tFace Count: {mesh.get_face_count()}')
# print(f'\tMaterial Slot Count: {mesh.get_material_slot_count()}')
# print('===== Materials =====')
# for mtl in reader.get_materials():
# print(mtl.get_name())
# print(f'\tDiffuse: {mtl.get_diffuse().to_const_rgba()}')
# print(f'\tAmbient: {mtl.get_ambient().to_const_rgba()}')
# print(f'\tSpecular: {mtl.get_specular().to_const_rgba()}')
# print(f'\tEmissive: {mtl.get_emissive().to_const_rgba()}')
# print(f'\tSpecular Power: {mtl.get_specular_power()}')
# print(f'\tTexture Border Color: {mtl.get_texture_border_color().to_const_rgba()}')
# print(f'\tTexture Blend Mode: {mtl.get_texture_blend_mode()}')
# print(f'\tTexture Min Mode: {mtl.get_texture_min_mode()}')
# print(f'\tTexture Mag Mode: {mtl.get_texture_mag_mode()}')
# print(f'\tSource Blend: {mtl.get_source_blend()}')
# print(f'\tDest Blend: {mtl.get_dest_blend()}')
# print(f'\tFill Mode: {mtl.get_fill_mode()}')
# print(f'\tShade Mode: {mtl.get_shade_mode()}')
# print(f'\tAlpha Test Enabled: {mtl.get_alpha_test_enabled()}')
# print(f'\tAlpha Blend Enabled: {mtl.get_alpha_blend_enabled()}')
# print(f'\tPerspective Correction Enabled: {mtl.get_perspective_correction_enabled()}')
# print(f'\tZ Write Enabled: {mtl.get_z_write_enabled()}')
# print(f'\tTwo Sided Enabled: {mtl.get_two_sided_enabled()}')
# print(f'\tAlpha Ref: {mtl.get_alpha_ref()}')
# print(f'\tAlpha Func: {mtl.get_alpha_func()}')
# print(f'\tZ Func: {mtl.get_z_func()}')
# print('===== Textures =====')
# for tex in reader.get_textures():
# print(tex.get_name())
# print(f'\tFile Name: {tex.get_file_name()}')
# print(f'\tSave Options: {tex.get_save_options()}')
# print(f'\tVideo Format: {tex.get_video_format()}')
print('===== Target Lights =====')
for lit in reader.get_target_lights():
print(lit.get_name())
print(f'\tVisibility: {lit.get_visibility()}')
print(f'\tMatrix: {lit.get_world_matrix().to_const()}')
print(f'\tType: {lit.get_type()}')
print(f'\tColor: {lit.get_color().to_const_rgba()}')
print(f'\tConstant Attenuation: {lit.get_constant_attenuation()}')
print(f'\tLinear Attenuation: {lit.get_linear_attenuation()}')
print(f'\tQuadratic Attenuation: {lit.get_quadratic_attenuation()}')
print(f'\tRange: {lit.get_range()}')
print(f'\tHot Spot: {lit.get_hot_spot()}')
print(f'\tFalloff: {lit.get_falloff()}')
print(f'\tFalloff Shape: {lit.get_falloff_shape()}')
print('===== END =====')
def test_equatable(reader: bmap.BMFileReader):
# Check requirements
assert (reader.get_3dobject_count() >= 2), '''
Invalid file for test IEquatable.
We can not perform IEquatable test because the length of 3dObject is too short (must greater than 2). Please choose another file to perform.
'''
# Prepare variables
all_3dobjects: tuple[bmap.BM3dObject, ...] = tuple(reader.get_3dobjects())
first_3dobj: bmap.BM3dObject = all_3dobjects[0]
second_3dobj: bmap.BM3dObject = all_3dobjects[1]
all_3dobjects = tuple(reader.get_3dobjects())
first_3dobj_again: bmap.BM3dObject = all_3dobjects[0]
# Test set
test_set: set[bmap.BM3dObject] = set()
test_set.add(first_3dobj)
assert len(test_set) == 1
assert first_3dobj in test_set
assert first_3dobj_again in test_set
assert second_3dobj not in test_set
test_set.add(first_3dobj_again)
assert len(test_set) == 1
test_set.add(second_3dobj)
assert len(test_set) == 2
assert second_3dobj in test_set
# Test dict
test_dict: dict[bmap.BM3dObject, str | None] = {}
test_dict[first_3dobj] = first_3dobj.get_name()
assert len(test_dict) == 1
assert first_3dobj in test_dict
assert first_3dobj_again in test_dict
assert second_3dobj not in test_dict
test_dict[first_3dobj_again] = first_3dobj_again.get_name()
assert len(test_dict) == 1
test_dict[second_3dobj] = second_3dobj.get_name()
assert len(test_dict) == 2
assert second_3dobj in test_dict
if __name__ == '__main__':
# parse argument
parser = argparse.ArgumentParser(
prog='PyBMap Testbench',
description='The testbench of PyBMap.'
)
parser.add_argument(
'--file-path',
action='store', dest='file_path', required=True,
help='The path to input Virtools file.'
)
parser.add_argument(
'--temp-dir',
action='store', dest='temp_dir', required=True,
help='The temp folder used by BMap.'
)
parser.add_argument(
'--texture-dir',
action='store', dest='texture_dir', required=True,
help='The texture folder containing Ballance texture resources.'
)
parser.add_argument(
'--encodings',
action='extend', nargs='+', dest='encodings', required=True,
help='The encodings used to parse the names stroed in input Virtools file.'
)
args = parser.parse_args()
# run main function
main(args.file_path, args.temp_dir, args.texture_dir, tuple(args.encodings))

View File

@@ -0,0 +1,28 @@
# BMap Bindings
This directory contains bindings for C++ written BMap for interacting with Ballance map.
We now provide following bindings due to different reasons:
* pybmap: The Python bindings for BMap. [Ballance Blender Plugin](https://github.com/yyc12345/BallanceBlenderHelper) require this.
* BMapSharp: The C# bindings for BMap. This can be used in C#-available game engine (Unity, Godot, etc.) for implementing next generation of Ballance with legacy map format support.
* bmap-rs: The Rust bindings for BMap. ZZQ request it for his Ballance launcher.
## Package Principle
In theory, these BMap bindings can be distributed as the package in their corresponding package manager.
However, considering these bindings is specific for a minor territory, Ballance mapping,
and the complexity of building the essential artificate, dynamic library BMap written in C++,
I give up the idea of distributing them as package.
For all users who want to utilize these bindings, you should build them on their own,
according to the build manual provided in respective directory.
## Test
These BMap bindings all have test for testing whether they work correctly.
And these test program following the same pattern for fetching test parameters
indluding where to find the map and etc.
More preciously, you should set environment variables list following before running test programs.
* `BMAP_FILE_NAME`: The path to the map for loading.
* `BMAP_BALLANCE_DIR`:The path to the Ballance directory for finding textures
* `BMAP_ENCODINGS`: The name of encodings used by BMap for loading map. Multiple encodings is supported by separating them with commas, for example: `cp1252,gbk`.

463
Assets/BMapBindings/bmap-rs/Cargo.lock generated Normal file
View File

@@ -0,0 +1,463 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "anyhow"
version = "1.0.102"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c"
[[package]]
name = "bitflags"
version = "2.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "843867be96c8daad0d758b57df9392b6d8d271134fce549de6ce169ff98a92af"
[[package]]
name = "bmap-rs"
version = "0.4.0"
dependencies = [
"tempfile",
"thiserror",
]
[[package]]
name = "cfg-if"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
[[package]]
name = "equivalent"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
[[package]]
name = "errno"
version = "0.3.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
dependencies = [
"libc",
"windows-sys",
]
[[package]]
name = "fastrand"
version = "2.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be"
[[package]]
name = "foldhash"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2"
[[package]]
name = "getrandom"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "139ef39800118c7683f2fd3c98c1b23c09ae076556b435f8e9064ae108aaeeec"
dependencies = [
"cfg-if",
"libc",
"r-efi",
"wasip2",
"wasip3",
]
[[package]]
name = "hashbrown"
version = "0.15.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1"
dependencies = [
"foldhash",
]
[[package]]
name = "hashbrown"
version = "0.16.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100"
[[package]]
name = "heck"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
[[package]]
name = "id-arena"
version = "2.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
[[package]]
name = "indexmap"
version = "2.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7714e70437a7dc3ac8eb7e6f8df75fd8eb422675fc7678aff7364301092b1017"
dependencies = [
"equivalent",
"hashbrown 0.16.1",
"serde",
"serde_core",
]
[[package]]
name = "itoa"
version = "1.0.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "92ecc6618181def0457392ccd0ee51198e065e016d1d527a7ac1b6dc7c1f09d2"
[[package]]
name = "leb128fmt"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2"
[[package]]
name = "libc"
version = "0.2.182"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6800badb6cb2082ffd7b6a67e6125bb39f18782f793520caee8cb8846be06112"
[[package]]
name = "linux-raw-sys"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
[[package]]
name = "log"
version = "0.4.29"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897"
[[package]]
name = "memchr"
version = "2.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79"
[[package]]
name = "once_cell"
version = "1.21.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d"
[[package]]
name = "prettyplease"
version = "0.2.37"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b"
dependencies = [
"proc-macro2",
"syn",
]
[[package]]
name = "proc-macro2"
version = "1.0.106"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.44"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "21b2ebcf727b7760c461f091f9f0f539b77b8e87f2fd88131e7f1b433b3cece4"
dependencies = [
"proc-macro2",
]
[[package]]
name = "r-efi"
version = "5.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f"
[[package]]
name = "rustix"
version = "1.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190"
dependencies = [
"bitflags",
"errno",
"libc",
"linux-raw-sys",
"windows-sys",
]
[[package]]
name = "semver"
version = "1.0.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d767eb0aabc880b29956c35734170f26ed551a859dbd361d140cdbeca61ab1e2"
[[package]]
name = "serde"
version = "1.0.228"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e"
dependencies = [
"serde_core",
]
[[package]]
name = "serde_core"
version = "1.0.228"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.228"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "serde_json"
version = "1.0.149"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "83fc039473c5595ace860d8c4fafa220ff474b3fc6bfdb4293327f1a37e94d86"
dependencies = [
"itoa",
"memchr",
"serde",
"serde_core",
"zmij",
]
[[package]]
name = "syn"
version = "2.0.115"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e614ed320ac28113fa64972c4262d5dbc89deacdfd00c34a3e4cea073243c12"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "tempfile"
version = "3.26.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "82a72c767771b47409d2345987fda8628641887d5466101319899796367354a0"
dependencies = [
"fastrand",
"getrandom",
"once_cell",
"rustix",
"windows-sys",
]
[[package]]
name = "thiserror"
version = "2.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4"
dependencies = [
"thiserror-impl",
]
[[package]]
name = "thiserror-impl"
version = "2.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "unicode-ident"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "537dd038a89878be9b64dd4bd1b260315c1bb94f4d784956b81e27a088d9a09e"
[[package]]
name = "unicode-xid"
version = "0.2.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853"
[[package]]
name = "wasip2"
version = "1.0.2+wasi-0.2.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9517f9239f02c069db75e65f174b3da828fe5f5b945c4dd26bd25d89c03ebcf5"
dependencies = [
"wit-bindgen",
]
[[package]]
name = "wasip3"
version = "0.4.0+wasi-0.3.0-rc-2026-01-06"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5428f8bf88ea5ddc08faddef2ac4a67e390b88186c703ce6dbd955e1c145aca5"
dependencies = [
"wit-bindgen",
]
[[package]]
name = "wasm-encoder"
version = "0.244.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "990065f2fe63003fe337b932cfb5e3b80e0b4d0f5ff650e6985b1048f62c8319"
dependencies = [
"leb128fmt",
"wasmparser",
]
[[package]]
name = "wasm-metadata"
version = "0.244.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bb0e353e6a2fbdc176932bbaab493762eb1255a7900fe0fea1a2f96c296cc909"
dependencies = [
"anyhow",
"indexmap",
"wasm-encoder",
"wasmparser",
]
[[package]]
name = "wasmparser"
version = "0.244.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "47b807c72e1bac69382b3a6fb3dbe8ea4c0ed87ff5629b8685ae6b9a611028fe"
dependencies = [
"bitflags",
"hashbrown 0.15.5",
"indexmap",
"semver",
]
[[package]]
name = "windows-link"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
[[package]]
name = "windows-sys"
version = "0.61.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
dependencies = [
"windows-link",
]
[[package]]
name = "wit-bindgen"
version = "0.51.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d7249219f66ced02969388cf2bb044a09756a083d0fab1e566056b04d9fbcaa5"
dependencies = [
"wit-bindgen-rust-macro",
]
[[package]]
name = "wit-bindgen-core"
version = "0.51.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ea61de684c3ea68cb082b7a88508a8b27fcc8b797d738bfc99a82facf1d752dc"
dependencies = [
"anyhow",
"heck",
"wit-parser",
]
[[package]]
name = "wit-bindgen-rust"
version = "0.51.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b7c566e0f4b284dd6561c786d9cb0142da491f46a9fbed79ea69cdad5db17f21"
dependencies = [
"anyhow",
"heck",
"indexmap",
"prettyplease",
"syn",
"wasm-metadata",
"wit-bindgen-core",
"wit-component",
]
[[package]]
name = "wit-bindgen-rust-macro"
version = "0.51.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0c0f9bfd77e6a48eccf51359e3ae77140a7f50b1e2ebfe62422d8afdaffab17a"
dependencies = [
"anyhow",
"prettyplease",
"proc-macro2",
"quote",
"syn",
"wit-bindgen-core",
"wit-bindgen-rust",
]
[[package]]
name = "wit-component"
version = "0.244.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9d66ea20e9553b30172b5e831994e35fbde2d165325bec84fc43dbf6f4eb9cb2"
dependencies = [
"anyhow",
"bitflags",
"indexmap",
"log",
"serde",
"serde_derive",
"serde_json",
"wasm-encoder",
"wasm-metadata",
"wasmparser",
"wit-parser",
]
[[package]]
name = "wit-parser"
version = "0.244.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ecc8ac4bc1dc3381b7f59c34f00b67e18f910c2c0f50015669dde7def656a736"
dependencies = [
"anyhow",
"id-arena",
"indexmap",
"log",
"semver",
"serde",
"serde_derive",
"serde_json",
"unicode-xid",
"wasmparser",
]
[[package]]
name = "zmij"
version = "1.0.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa"

View File

@@ -1,5 +1,5 @@
[package]
name = "bmap-sys"
name = "bmap-rs"
version = "0.4.0"
authors = ["yyc12345"]
edition = "2024"
@@ -7,3 +7,8 @@ description = "The Rust binding to BMap."
license = "SPDX:MIT"
[dependencies]
thiserror = "2.0.12"
[dev-dependencies]
tempfile = "3.26.0"

View File

@@ -0,0 +1,43 @@
# bmap-rs
## Layout
This project follows standard Rust project layout.
Source code are located in `src` directory and test code are in `tests` directory.
Please note that the raw FFI functions and the wrapper of it are placed in the single project,
not like other Rust project that raw bindings and wrapper are put into 2 different project,
one of them is ended with `-sys` and another one is not.
This is a considerable decision due to the following reasons:
- I want this project has same pattern with other bindings. In other bindings, FFI binding code and wrapper are put together.
- They (FFI binding and wrapper) can not be easily splitted due to logic reasons. Putting them together can avoid some extra work.
## Native BMap Library Location
This project uses native way (native compiler and linker) to link the BMap library.
This is different with other bindings.
> [!IMPORTANT]
> We highly suggest that you make sure that the toolchain building your BMap is same as your configured Rust toolchain.
> Although BMap is a dynamic library and its function is exposed as C function, the link issue may still occurs due to the different toolchain.
According to this, you should set `LibCmo_ROOT` environment variable pointing to the CMake install directory of LibCmo with built BMap before configuring this Rust project.
This project will find it in `build.rs` script and tell Rust compiler how to link it.
> [!IMPORTANT]
> For Linux and macOS user, you may need manually to rename the final built BMap artifact.
> Because in these platforms, CMake produced BMap dynamic library may have `lib` prefix in its name.
> This can not be recognized by our build script.
>
> You should rename it to `BMap.so` or `BMap.dylib` depending on your platform.
> You also may need rename some contents of other files involving this rename change.
Also due to this, when distributing your Rust project, please do not forget copy the built BMap library with your Rust artifacts.
## Test
The test code located in `tests` directory is NOT designed for plain "cargo test".
It is more close to an independent test program, so executing it may require some extra work.
First you need configure all environment variables for testing.
Then you can execute `cargo test complete -- --nocapture` to run the complete test program.

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,113 @@
//! BMap wrapper used marshaler for string and string array.
use crate::bmap::{CKSTRING, PCKSTRING};
use std::ffi::{CStr, CString};
use thiserror::Error as TeError;
// region: Error and Result Types
/// Any possible error occurs in this module.
#[derive(Debug, TeError, Clone)]
pub enum Error {
#[error("can not parse from native string")]
FromNative(#[from] std::str::Utf8Error),
#[error("can not format into native string")]
ToNative(#[from] std::ffi::NulError),
}
/// The result type used in this module.
pub type Result<T> = std::result::Result<T, Error>;
// endregion
pub unsafe fn from_native_string(ptr: CKSTRING) -> Result<String> {
let s = unsafe { CStr::from_ptr(ptr) };
Ok(String::from(s.to_str()?))
}
pub unsafe fn to_native_string<T>(words: T) -> Result<BMString>
where
T: Into<Vec<u8>>,
{
BMString::new(words)
}
pub struct BMString {
inner: CString,
}
impl BMString {
fn new<T>(words: T) -> Result<Self>
where
T: Into<Vec<u8>>,
{
Ok(Self {
inner: CString::new(words)?,
})
}
pub unsafe fn as_raw(&self) -> CKSTRING {
self.inner.as_ptr() as CKSTRING
}
}
pub unsafe fn from_native_string_array(ptr: PCKSTRING) -> Result<Vec<String>> {
let mut rv = Vec::new();
loop {
let item_ptr = unsafe { *ptr } as CKSTRING;
if item_ptr.is_null() {
break;
}
let item = unsafe { from_native_string(item_ptr)? };
rv.push(item);
}
Ok(rv)
}
pub unsafe fn to_native_string_array<I, T>(words: I) -> Result<BMStringArray>
where
I: Iterator<Item = T>,
T: Into<Vec<u8>>,
{
BMStringArray::new(words)
}
pub struct BMStringArray {
array_items: Vec<CString>,
array_body: Vec<CKSTRING>,
}
impl BMStringArray {
fn new<I, T>(words: I) -> Result<Self>
where
I: Iterator<Item = T>,
T: Into<Vec<u8>>,
{
// Build array items
let array_items = words
.map(|word| CString::new(word))
.collect::<std::result::Result<Vec<CString>, std::ffi::NulError>>()?;
// Build array body.
// In theory, move operation will not affect data allocated on heap.
// So we can simply fetch the address of this new generated array.
let array_body = array_items
.iter()
.map(|i| i.as_ptr() as CKSTRING)
.chain(std::iter::once(std::ptr::null_mut() as CKSTRING))
.collect::<Vec<CKSTRING>>();
// Return value
Ok(Self { array_items, array_body })
}
pub fn len(&self) -> usize {
self.array_items.len()
}
pub unsafe fn as_raw(&self) -> PCKSTRING {
self.array_body.as_ptr() as PCKSTRING
}
}

View File

@@ -0,0 +1,4 @@
//! The Rust binding to BMap.
pub mod virtools_types;
pub mod bmap;
pub mod bmap_wrapper;

View File

@@ -0,0 +1,480 @@
//! The module conatins all basic Virtools types used by BMap native FFI calling.
// region: Structures
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
#[repr(C)]
#[repr(packed(4))]
pub struct VxVector2 {
pub x: f32,
pub y: f32,
}
impl VxVector2 {
pub fn new() -> Self {
Self::with_xy(0.0, 0.0)
}
pub fn with_xy(x: f32, y: f32) -> Self {
Self { x, y }
}
}
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
#[repr(C)]
#[repr(packed(4))]
pub struct VxVector3 {
pub x: f32,
pub y: f32,
pub z: f32,
}
impl VxVector3 {
pub fn new() -> Self {
Self::with_xyz(0.0, 0.0, 0.0)
}
pub fn with_xyz(x: f32, y: f32, z: f32) -> Self {
Self { x, y, z }
}
}
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
#[repr(C)]
#[repr(packed(4))]
pub struct VxColor {
pub r: f32,
pub g: f32,
pub b: f32,
pub a: f32,
}
impl VxColor {
pub fn new() -> Self {
Self::with_rgba(0.0, 0.0, 0.0, 0.0)
}
pub fn with_rgba(r: f32, g: f32, b: f32, a: f32) -> Self {
let mut rv = Self { r, g, b, a };
rv.regulate();
return rv;
}
pub fn with_rgb(r: f32, g: f32, b: f32) -> Self {
Self::with_rgba(r, g, b, 1.0)
}
pub fn with_dword(val: u32) -> Self {
let mut rv = Self::new();
rv.from_dword(val);
return rv;
}
pub fn from_dword(&mut self, mut val: u32) {
self.b = (val & 0xFF) as f32 / 255.0;
val >>= 8;
self.g = (val & 0xFF) as f32 / 255.0;
val >>= 8;
self.r = (val & 0xFF) as f32 / 255.0;
val >>= 8;
self.a = (val & 0xFF) as f32 / 255.0;
}
pub fn to_dword(&self) -> u32 {
// Make a copy and regulate self first
let mut copied = self.clone();
copied.regulate();
// Build result
let mut rv = 0;
rv |= (copied.b * 255.0) as u32;
rv <<= 8;
rv |= (copied.g * 255.0) as u32;
rv <<= 8;
rv |= (copied.r * 255.0) as u32;
rv <<= 8;
rv |= (copied.a * 255.0) as u32;
return rv;
}
fn clamp_factor(factor: f32) -> f32 {
factor.min(1.0).max(0.0)
}
pub fn regulate(&mut self) {
self.r = Self::clamp_factor(self.r);
self.g = Self::clamp_factor(self.g);
self.b = Self::clamp_factor(self.b);
self.a = Self::clamp_factor(self.a);
}
}
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
#[repr(C)]
#[repr(packed(4))]
pub struct VxMatrix {
pub data: [[f32; 4]; 4],
}
impl VxMatrix {
pub fn new() -> Self {
Self {
data: [
[1.0, 0.0, 0.0, 0.0],
[0.0, 1.0, 0.0, 0.0],
[0.0, 0.0, 1.0, 0.0],
[0.0, 0.0, 0.0, 1.0],
],
}
}
#[rustfmt::skip]
pub fn reset(&mut self) {
self.data[0][0] = 1.0; self.data[0][1] = 0.0; self.data[0][2] = 0.0; self.data[0][3] = 0.0;
self.data[1][0] = 0.0; self.data[1][1] = 1.0; self.data[1][2] = 0.0; self.data[1][3] = 0.0;
self.data[2][0] = 0.0; self.data[2][1] = 0.0; self.data[2][2] = 1.0; self.data[2][3] = 0.0;
self.data[3][0] = 0.0; self.data[3][1] = 0.0; self.data[3][2] = 0.0; self.data[3][3] = 1.0;
}
}
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
#[repr(C)]
#[repr(packed(4))]
pub struct CKFaceIndices {
pub i1: u32,
pub i2: u32,
pub i3: u32,
}
impl CKFaceIndices {
pub fn new() -> Self {
Self::with_indices(0, 0, 0)
}
pub fn with_indices(i1: u32, i2: u32, i3: u32) -> Self {
Self { i1, i2, i3 }
}
}
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
#[repr(C)]
#[repr(packed(4))]
pub struct CKShortFaceIndices {
pub i1: u16,
pub i2: u16,
pub i3: u16,
}
impl CKShortFaceIndices {
pub fn new() -> Self {
Self::with_indices(0, 0, 0)
}
pub fn with_indices(i1: u16, i2: u16, i3: u16) -> Self {
Self { i1, i2, i3 }
}
}
// endregion
// region: Enums
/// Specify the way textures or sprites will be saved
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(u32)]
#[non_exhaustive]
#[rustfmt::skip]
#[allow(non_camel_case_types)]
pub enum CK_TEXTURE_SAVEOPTIONS {
/// Save raw data inside file. The bitmap is saved in a raw 32 bit per pixel format.
CKTEXTURE_RAWDATA = 0,
/// Store only the file name for the texture. The bitmap file must be present in the bitmap pathswhen loading the composition.
CKTEXTURE_EXTERNAL = 1,
/// Save using format specified. The bitmap data will be converted to thespecified format by the correspondant bitmap plugin and saved inside file.
CKTEXTURE_IMAGEFORMAT = 2,
/// Use Global settings, that is the settings given with CKContext::SetGlobalImagesSaveOptions. (Not valid when using CKContext::SetImagesSaveOptions).
CKTEXTURE_USEGLOBAL = 3,
/// Insert original image file inside CMO file. The bitmap file thatwas used originally for the texture or sprite will be append tothe composition file and extracted when the file is loaded.
CKTEXTURE_INCLUDEORIGINALFILE = 4,
}
/// Pixel format types.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(u32)]
#[non_exhaustive]
#[rustfmt::skip]
#[allow(non_camel_case_types)]
pub enum VX_PIXELFORMAT {
/// Unknown pixel format
UNKNOWN_PF = 0,
/// 32-bit ARGB pixel format with alpha
_32_ARGB8888 = 1,
/// 32-bit RGB pixel format without alpha
_32_RGB888 = 2,
/// 24-bit RGB pixel format
_24_RGB888 = 3,
/// 16-bit RGB pixel format
_16_RGB565 = 4,
/// 16-bit RGB pixel format (5 bits per color)
_16_RGB555 = 5,
/// 16-bit ARGB pixel format (5 bits per color + 1 bit for alpha)
_16_ARGB1555 = 6,
/// 16-bit ARGB pixel format (4 bits per color)
_16_ARGB4444 = 7,
/// 8-bit RGB pixel format
_8_RGB332 = 8,
/// 8-bit ARGB pixel format
_8_ARGB2222 = 9,
/// 32-bit ABGR pixel format
_32_ABGR8888 = 10,
/// 32-bit RGBA pixel format
_32_RGBA8888 = 11,
/// 32-bit BGRA pixel format
_32_BGRA8888 = 12,
/// 32-bit BGR pixel format
_32_BGR888 = 13,
/// 24-bit BGR pixel format
_24_BGR888 = 14,
/// 16-bit BGR pixel format
_16_BGR565 = 15,
/// 16-bit BGR pixel format (5 bits per color)
_16_BGR555 = 16,
/// 16-bit ABGR pixel format (5 bits per color + 1 bit for alpha)
_16_ABGR1555 = 17,
/// 16-bit ABGR pixel format (4 bits per color)
_16_ABGR4444 = 18,
/// S3/DirectX Texture Compression 1
_DXT1 = 19,
/// S3/DirectX Texture Compression 2
_DXT2 = 20,
/// S3/DirectX Texture Compression 3
_DXT3 = 21,
/// S3/DirectX Texture Compression 4
_DXT4 = 22,
/// S3/DirectX Texture Compression 5
_DXT5 = 23,
/// 16-bit Bump Map format format (8 bits per color)
_16_V8U8 = 24,
/// 32-bit Bump Map format format (16 bits per color)
_32_V16U16 = 25,
/// 16-bit Bump Map format format with luminance
_16_L6V5U5 = 26,
/// 32-bit Bump Map format format with luminance
_32_X8L8V8U8 = 27,
/// 8 bits indexed CLUT (ABGR)
_8_ABGR8888_CLUT = 28,
/// 8 bits indexed CLUT (ARGB)
_8_ARGB8888_CLUT = 29,
/// 4 bits indexed CLUT (ABGR)
_4_ABGR8888_CLUT = 30,
/// 4 bits indexed CLUT (ARGB)
_4_ARGB8888_CLUT = 31,
}
/// Light type.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(u32)]
#[non_exhaustive]
#[rustfmt::skip]
#[allow(non_camel_case_types)]
pub enum VXLIGHT_TYPE {
/// The Light is a point of light
VX_LIGHTPOINT = 1,
/// The light is a spotlight
VX_LIGHTSPOT = 2,
/// The light is directional light : Lights comes from an infinite point so only direction of light can be given
VX_LIGHTDIREC = 3,
// /// Obsolete, do not use
// VX_LIGHTPARA = 4,
}
/// Blend Mode Flags
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(u32)]
#[non_exhaustive]
#[rustfmt::skip]
#[allow(non_camel_case_types)]
pub enum VXTEXTURE_BLENDMODE {
/// Texture replace any material information
VXTEXTUREBLEND_DECAL = 1,
/// Texture and material are combine. Alpha information of the texture replace material alpha component.
VXTEXTUREBLEND_MODULATE = 2,
/// Alpha information in the texture specify how material and texture are combined. Alpha information of the texture replace material alpha component.
VXTEXTUREBLEND_DECALALPHA = 3,
/// Alpha information in the texture specify how material and texture are combined
VXTEXTUREBLEND_MODULATEALPHA = 4,
VXTEXTUREBLEND_DECALMASK = 5,
VXTEXTUREBLEND_MODULATEMASK = 6,
/// Equivalent to DECAL
VXTEXTUREBLEND_COPY = 7,
VXTEXTUREBLEND_ADD = 8,
/// Perform a Dot Product 3 between texture (normal map)and a referential vector given in VXRENDERSTATE_TEXTUREFACTOR.
VXTEXTUREBLEND_DOTPRODUCT3 = 9,
VXTEXTUREBLEND_MAX = 10,
// VXTEXTUREBLEND_MASK = 0xF,
}
/// Filter Mode Options
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(u32)]
#[non_exhaustive]
#[rustfmt::skip]
#[allow(non_camel_case_types)]
pub enum VXTEXTURE_FILTERMODE {
/// No Filter
VXTEXTUREFILTER_NEAREST = 1,
/// Bilinear Interpolation
VXTEXTUREFILTER_LINEAR = 2,
/// Mip mapping
VXTEXTUREFILTER_MIPNEAREST = 3,
/// Mip Mapping with Bilinear interpolation
VXTEXTUREFILTER_MIPLINEAR = 4,
/// Mip Mapping with Bilinear interpolation between mipmap levels.
VXTEXTUREFILTER_LINEARMIPNEAREST = 5,
/// Trilinear Filtering
VXTEXTUREFILTER_LINEARMIPLINEAR = 6,
/// Anisotropic filtering
VXTEXTUREFILTER_ANISOTROPIC = 7,
// VXTEXTUREFILTER_MASK = 0xF,
}
/// Texture addressing modes.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(u32)]
#[non_exhaustive]
#[rustfmt::skip]
#[allow(non_camel_case_types)]
pub enum VXTEXTURE_ADDRESSMODE {
/// Default mesh wrap mode is used (see CKMesh::SetWrapMode)
VXTEXTURE_ADDRESSWRAP = 1,
/// Texture coordinates outside the range [0..1] are flipped evenly.
VXTEXTURE_ADDRESSMIRROR = 2,
/// Texture coordinates greater than 1.0 are set to 1.0, and values less than 0.0 are set to 0.0.
VXTEXTURE_ADDRESSCLAMP = 3,
/// When texture coordinates are greater than 1.0 or less than 0.0 texture is set to a color defined in CKMaterial::SetTextureBorderColor.
VXTEXTURE_ADDRESSBORDER = 4,
///
VXTEXTURE_ADDRESSMIRRORONCE = 5,
// /// mask for all values
// VXTEXTURE_ADDRESSMASK = 0x7,
}
/// Blending Mode options
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(u32)]
#[non_exhaustive]
#[rustfmt::skip]
#[allow(non_camel_case_types)]
pub enum VXBLEND_MODE {
/// Blend factor is (0, 0, 0, 0).
VXBLEND_ZERO = 1,
/// Blend factor is (1, 1, 1, 1).
VXBLEND_ONE = 2,
/// Blend factor is (Rs, Gs, Bs, As).
VXBLEND_SRCCOLOR = 3,
/// Blend factor is (1-Rs, 1-Gs, 1-Bs, 1-As).
VXBLEND_INVSRCCOLOR = 4,
/// Blend factor is (As, As, As, As).
VXBLEND_SRCALPHA = 5,
/// Blend factor is (1-As, 1-As, 1-As, 1-As).
VXBLEND_INVSRCALPHA = 6,
/// Blend factor is (Ad, Ad, Ad, Ad).
VXBLEND_DESTALPHA = 7,
/// Blend factor is (1-Ad, 1-Ad, 1-Ad, 1-Ad).
VXBLEND_INVDESTALPHA = 8,
/// Blend factor is (Rd, Gd, Bd, Ad).
VXBLEND_DESTCOLOR = 9,
/// Blend factor is (1-Rd, 1-Gd, 1-Bd, 1-Ad).
VXBLEND_INVDESTCOLOR = 10,
/// Blend factor is (f, f, f, 1); f = min(As, 1-Ad).
VXBLEND_SRCALPHASAT = 11,
// /// Source blend factor is (As, As, As, As) and destination blend factor is (1-As, 1-As, 1-As, 1-As)
// VXBLEND_BOTHSRCALPHA = 12,
// /// Source blend factor is (1-As, 1-As, 1-As, 1-As) and destination blend factor is (As, As, As, As)
// VXBLEND_BOTHINVSRCALPHA = 13,
// /// Source blend factor is (1-As, 1-As, 1-As, 1-As) and destination blend factor is (As, As, As, As)
// VXBLEND_MASK = 0xF,
}
/// Fill Mode Options
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(u32)]
#[non_exhaustive]
#[rustfmt::skip]
#[allow(non_camel_case_types)]
pub enum VXFILL_MODE {
/// Vertices rendering
VXFILL_POINT = 1,
/// Edges rendering
VXFILL_WIREFRAME = 2,
/// Face rendering
VXFILL_SOLID = 3,
// VXFILL_MASK = 3,
}
/// Shade Mode Options
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(u32)]
#[non_exhaustive]
#[rustfmt::skip]
#[allow(non_camel_case_types)]
pub enum VXSHADE_MODE {
/// Flat Shading
VXSHADE_FLAT = 1,
/// Gouraud Shading
VXSHADE_GOURAUD = 2,
/// Phong Shading (Not yet supported by most implementation)
VXSHADE_PHONG = 3,
// VXSHADE_MASK = 3,
}
/// Comparison Function
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(u32)]
#[non_exhaustive]
#[rustfmt::skip]
#[allow(non_camel_case_types)]
pub enum VXCMPFUNC {
/// Always fail the test.
VXCMP_NEVER = 1,
/// Accept if value if less than current value.
VXCMP_LESS = 2,
/// Accept if value if equal than current value.
VXCMP_EQUAL = 3,
/// Accept if value if less or equal than current value.
VXCMP_LESSEQUAL = 4,
/// Accept if value if greater than current value.
VXCMP_GREATER = 5,
/// Accept if value if different than current value.
VXCMP_NOTEQUAL = 6,
/// Accept if value if greater or equal current value.
VXCMP_GREATEREQUAL = 7,
/// Always accept the test.
VXCMP_ALWAYS = 8,
// /// Mask for all possible values.
// VXCMP_MASK = 0xF,
}
/// Mesh lighting options
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(u32)]
#[non_exhaustive]
#[rustfmt::skip]
#[allow(non_camel_case_types)]
pub enum VXMESH_LITMODE {
/// Lighting use color information store with vertices
VX_PRELITMESH = 0,
/// Lighting is done by renderer using normals and face material information.
VX_LITMESH = 1,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(u32)]
#[non_exhaustive]
#[rustfmt::skip]
#[allow(non_camel_case_types)]
pub enum CK_CAMERA_PROJECTION {
CK_PERSPECTIVEPROJECTION = 1,
CK_ORTHOGRAPHICPROJECTION = 2,
}
// endregion

View File

@@ -0,0 +1,288 @@
use bmap_rs::bmap_wrapper as bmap;
use std::io::Read;
use std::path::PathBuf;
#[test]
fn test_complete() {
// Parse arguments
let cliopts = cli::Cli::new();
// Check BMap status.
if !bmap::BMap::is_available() {
panic!("Fail to initialize native BMap.");
}
// Waiting debugger
println!(
"Rust PID is {}. Waiting for debugger, press any key to continue...",
std::process::id()
);
let buffer = &mut [0u8];
std::io::stdin().read_exact(buffer).unwrap();
// Start testbench
let file_name = cliopts.file_name.clone();
let temp_folder = tempfile::tempdir().unwrap();
let mut texture_folder = cliopts.ballance_dir.clone();
texture_folder.push("Textures");
let encodings = cliopts.encodings.clone();
bmap::BMap::with_bmap(|b| {
let r = b
.create_file_reader(
file_name.to_str().unwrap(),
temp_folder.path().to_str().unwrap(),
texture_folder.to_str().unwrap(),
encodings.iter().map(|e| e.as_str()),
)
.unwrap();
testsuits::common::test(&r);
testsuits::eq::test(&r);
});
drop(temp_folder);
}
mod cli {
use super::PathBuf;
pub struct Cli {
/// The path to the map for loading.
pub file_name: PathBuf,
/// The path to the Ballance directory for finding textures
pub ballance_dir: PathBuf,
/// The name of encodings used by BMap for loading map.
pub encodings: Vec<String>,
}
impl Cli {
pub fn new() -> Self {
let file_name = std::env::var("BMAP_FILE_NAME").expect(
"You must specify BMAP_FILE_NAME environment variable before running this test.",
);
let ballance_dir = std::env::var("BMAP_BALLANCE_DIR").expect(
"You must specify BMAP_BALLANCE_DIR environment variable before running this test.",
);
let encodings = std::env::var("BMAP_ENCODINGS").expect(
"You must specify BMAP_ENCODINGS environment variable before running this test.",
);
Self {
file_name: PathBuf::from(file_name),
ballance_dir: PathBuf::from(ballance_dir),
encodings: encodings
.split(",")
.map(|e| e.to_string())
.collect::<Vec<_>>(),
}
}
}
}
mod testsuits {
use super::bmap;
pub mod common {
use super::bmap;
use bmap::{
BM3dEntityDecl, BMCameraDecl, BMLightDecl, BMMaterialDecl, BMMeshDecl, BMObjectDecl,
BMTextureDecl, BMGroupDecl
};
pub fn test(reader: &bmap::BMFileReader) {
println!("===== Groups =====");
test_group(reader);
println!("===== 3dObjects =====");
test_3dobject(reader);
println!("===== Meshes =====");
test_mesh(reader);
println!("===== Materials =====");
test_material(reader);
println!("===== Textures =====");
test_texture(reader);
println!("===== Target Lights =====");
test_target_light(reader);
println!("===== Target Cameras =====");
test_target_camera(reader);
println!("===== END =====");
}
#[rustfmt::skip]
fn test_group(reader: &bmap::BMFileReader) {
for gp in reader.get_groups().unwrap() {
let gp = gp.unwrap();
println!("{:?}", gp.get_name().unwrap());
for gp_item in gp.get_objects().unwrap() {
let gp_item = gp_item.unwrap();
println!("\t{:?}", gp_item.get_name().unwrap());
}
}
}
#[rustfmt::skip]
fn test_3dobject(reader: &bmap::BMFileReader) {
for obj in reader.get_3dobjects().unwrap() {
let obj = obj.unwrap();
println!("{:?}", obj.get_name().unwrap());
let current_mesh = obj.get_current_mesh().unwrap();
let mesh_name = match current_mesh {
Some(mesh) => format!("{:?}", mesh.get_name()),
None => "<null>".to_string(),
};
println!("\tMesh: {}", mesh_name);
println!("\tVisibility: {}", obj.get_visibility().unwrap());
println!("\tMatrix: {:?}", obj.get_world_matrix().unwrap());
}
}
#[rustfmt::skip]
fn test_mesh(reader: &bmap::BMFileReader) {
for mesh in reader.get_meshes().unwrap() {
let mesh = mesh.unwrap();
println!("{:?}", mesh.get_name().unwrap());
println!("\tLit Mode: {:?}", mesh.get_lit_mode().unwrap());
println!("\tVertex Count: {}", mesh.get_vertex_count().unwrap());
println!("\tFace Count: {}", mesh.get_face_count().unwrap());
println!("\tMaterial Slot Count: {}", mesh.get_material_slot_count().unwrap());
}
}
#[rustfmt::skip]
fn test_material(reader: &bmap::BMFileReader) {
for mtl in reader.get_materials().unwrap() {
let mtl = mtl.unwrap();
println!("{:?}", mtl.get_name().unwrap());
println!("\tDiffuse: {:?}", mtl.get_diffuse().unwrap());
println!("\tAmbient: {:?}", mtl.get_ambient().unwrap());
println!("\tSpecular: {:?}", mtl.get_specular().unwrap());
println!("\tEmissive: {:?}", mtl.get_emissive().unwrap());
println!("\tSpecular Power: {}", mtl.get_specular_power().unwrap());
println!("\tTexture Border Color: {:?}", mtl.get_texture_border_color().unwrap());
println!("\tTexture Blend Mode: {:?}", mtl.get_texture_blend_mode().unwrap());
println!("\tTexture Min Mode: {:?}", mtl.get_texture_min_mode().unwrap());
println!("\tTexture Mag Mode: {:?}", mtl.get_texture_mag_mode().unwrap());
println!("\tSource Blend: {:?}", mtl.get_source_blend().unwrap());
println!("\tDest Blend: {:?}", mtl.get_dest_blend().unwrap());
println!("\tFill Mode: {:?}", mtl.get_fill_mode().unwrap());
println!("\tShade Mode: {:?}", mtl.get_shade_mode().unwrap());
println!("\tAlpha Test Enabled: {}", mtl.get_alpha_test_enabled().unwrap());
println!("\tAlpha Blend Enabled: {}", mtl.get_alpha_blend_enabled().unwrap());
println!("\tPerspective Correction Enabled: {}", mtl.get_perspective_correction_enabled().unwrap());
println!("\tZ Write Enabled: {}", mtl.get_z_write_enabled().unwrap());
println!("\tTwo Sided Enabled: {}", mtl.get_two_sided_enabled().unwrap());
println!("\tAlpha Ref: {}", mtl.get_alpha_ref().unwrap());
println!("\tAlpha Func: {:?}", mtl.get_alpha_func().unwrap());
println!("\tZ Func: {:?}", mtl.get_z_func().unwrap());
}
}
#[rustfmt::skip]
fn test_texture(reader: &bmap::BMFileReader) {
for tex in reader.get_textures().unwrap() {
let tex = tex.unwrap();
println!("{:?}", tex.get_name().unwrap());
println!("\tFile Name: {:?}", tex.get_file_name().unwrap());
println!("\tSave Options: {:?}", tex.get_save_options().unwrap());
println!("\tVideo Format: {:?}", tex.get_video_format().unwrap());
}
}
#[rustfmt::skip]
fn test_target_light(reader: &bmap::BMFileReader) {
for lit in reader.get_target_lights().unwrap() {
let lit = lit.unwrap();
println!("{:?}", lit.get_name().unwrap());
println!("\tVisibility: {:?}", lit.get_visibility().unwrap());
println!("\tMatrix: {:?}", lit.get_world_matrix().unwrap());
println!("\tType: {:?}", lit.get_type().unwrap());
println!("\tColor: {:?}", lit.get_color().unwrap());
println!("\tConstant Attenuation: {}", lit.get_constant_attenuation().unwrap());
println!("\tLinear Attenuation: {}", lit.get_linear_attenuation().unwrap());
println!("\tQuadratic Attenuation: {}", lit.get_quadratic_attenuation().unwrap());
println!("\tRange: {}", lit.get_range().unwrap());
println!("\tHot Spot: {}", lit.get_hot_spot().unwrap());
println!("\tFalloff: {}", lit.get_falloff().unwrap());
println!("\tFalloff Shape: {}", lit.get_falloff_shape().unwrap());
}
}
#[rustfmt::skip]
fn test_target_camera(reader: &bmap::BMFileReader) {
for cam in reader.get_target_cameras().unwrap() {
let cam = cam.unwrap();
println!("{:?}", cam.get_name().unwrap());
println!("\tVisibility: {:?}", cam.get_visibility().unwrap());
println!("\tMatrix: {:?}", cam.get_world_matrix().unwrap());
println!("\tType: {:?}", cam.get_projection_type().unwrap());
println!("\tOrthographic Zoom: {}", cam.get_orthographic_zoom().unwrap());
println!("\tFront Plane: {}", cam.get_front_plane().unwrap());
println!("\tBack Plane: {}", cam.get_back_plane().unwrap());
println!("\tFov: {}", cam.get_fov().unwrap());
let (width, height) = cam.get_aspect_ratio().unwrap();
println!("\tAspect Ratio: {}:{}", width, height);
}
}
}
pub mod eq {
use super::bmap;
use std::collections::{BTreeSet, HashSet};
pub fn test(reader: &bmap::BMFileReader) {
// Check requirements
assert!(
reader.get_3dobject_count().unwrap() >= 2,
r#"Invalid file for test Eq.
We can not perform Eq test because the length of 3dObject is too short (must greater than 2). Please choose another file to perform."#
);
// Prepare variables
let all_3dobjects = reader
.get_3dobjects()
.unwrap()
.map(|o| o.unwrap())
.collect::<Vec<_>>();
let first_3dobj = &all_3dobjects[0];
let second_3dobj = &all_3dobjects[1];
let all_3dobjects_again = reader
.get_3dobjects()
.unwrap()
.map(|o| o.unwrap())
.collect::<Vec<_>>();
let first_3dobj_again = &all_3dobjects_again[0];
// Test HashSet
let mut test_hashset = HashSet::new();
assert!(test_hashset.insert(first_3dobj));
assert!(!test_hashset.insert(first_3dobj_again));
assert!(test_hashset.insert(second_3dobj));
// Test BTreeSet
let mut test_btreeset = BTreeSet::new();
assert!(test_btreeset.insert(first_3dobj));
assert!(!test_btreeset.insert(first_3dobj_again));
assert!(test_btreeset.insert(second_3dobj));
}
}
}

View File

@@ -0,0 +1,7 @@
use bmap_rs::bmap;
#[test]
fn test_raw() {
assert!(unsafe { bmap::BMInit() });
assert!(unsafe { bmap::BMDispose() });
}

19
Assets/BMapBindings/pybmap/.gitignore vendored Normal file
View File

@@ -0,0 +1,19 @@
## ======== Personal ========
# Ignore binary BMap stuff
*.dll
*.pdb
*.so
*.dylib
*.bin
## ======== Python ========
# Python-generated files
__pycache__/
*.py[oc]
build/
dist/
wheels/
*.egg-info
# Virtual environments
.venv

View File

@@ -0,0 +1 @@
3.11

View File

@@ -0,0 +1,19 @@
# pybmap
## Layout
This project follows `src` and `test` layout and is managed by Astral UV.
The source code of pybmap is located inside `src`.
And the files located in `test` is used for testing.
> [!NOTE]
> The files located in `test` are not prepared for `pytest` framework.
> The test should be executed manually by `uv run test/main.py`.
## Native BMap Library Location
The native BMap library file should be placed with `bmap.py` file.
The native BMap library must be named as `BMap.dll` (in Windows), `BMap.so` (in Linux or BSD), `BMap.dylib` (in macOS), or `BMap.bin` (in any other platforms).
If you are building final distributed package file, such as `.whl` file, you may need manually put native BMap library file into package file because I have not write this behavior in any script.

View File

@@ -0,0 +1,14 @@
[project]
name = "pybmap"
version = "0.4.0"
description = "The Python binding to BMap."
readme = "README.md"
license = "MIT"
authors = [{ name = "yyc12345" }]
classifiers = ["Private :: Do Not Upload"]
requires-python = ">=3.11"
dependencies = []
[build-system]
requires = ["uv_build>=0.8.0,<0.9"]
build-backend = "uv_build"

File diff suppressed because it is too large Load Diff

View File

@@ -1,30 +1,36 @@
import ctypes, typing, atexit, enum
from . import bmap, virtools_types
import ctypes
import typing
import atexit
import enum
from . import bmap
from . import virtools_types
#region Basic Class & Constant Defines
g_InvalidPtr: bmap.bm_void_p = bmap.bm_void_p(0)
g_InvalidCKID: int = 0
g_BMapEncoding: str = "utf-8"
INVALID_PTR: bmap.bm_void_p = bmap.bm_void_p(0)
INVALID_CKID: int = 0
BMAP_ENCODING: str = "utf-8"
def _python_callback(strl: bytes):
"""
The Python type callback for BMFile.
Simply add a prefix when output.
Need a convertion before passing to BMFile.
This function simply add a prefix when output.
Extra convertion is required before passing to BMFile FFI function.
"""
# YYC Remarks:
# YYC MARK:
# The passing value to this function is bytes, not bmap.bm_CKSTRING.
# I think Python do an auto convertion in there.
if strl is not None:
print(f'[PyBMap] {strl.decode(g_BMapEncoding)}')
_g_RawCallback: bmap.bm_callback = bmap.bm_callback(_python_callback)
print(f'[pybmap] {strl.decode(BMAP_ENCODING)}')
RAW_CALLBACK: bmap.bm_callback = bmap.bm_callback(_python_callback)
#endregion
#region Help Functions
class _Utils:
class _utils:
@staticmethod
def raise_out_of_length_exception() -> None:
raise bmap.BMapException("The length of given data is too short when assigning struct array.")
@@ -39,7 +45,7 @@ class _Utils:
pdata[idx] = user_vector[_j]
idx += 1
except StopIteration:
_Utils.raise_out_of_length_exception()
_utils.raise_out_of_length_exception()
@staticmethod
def _vector_iterator(pdata: typing.Any, item_count: int, factor_count: int) -> typing.Iterator[tuple[typing.Any, ...]]:
@@ -53,39 +59,37 @@ class _Utils:
@staticmethod
def vxvector3_assigner(pvector: bmap.bm_VxVector3_p, count: int, itor: typing.Iterator[virtools_types.VxVector3]) -> None:
_Utils._vector_assigner(ctypes.cast(pvector, bmap.bm_CKFLOAT_p), count, 3, map(lambda v: (v.x, v.y, v.z), itor))
_utils._vector_assigner(ctypes.cast(pvector, bmap.bm_CKFLOAT_p), count, 3, map(lambda v: (v.x, v.y, v.z), itor))
@staticmethod
def vxvector3_iterator(pvector: bmap.bm_VxVector3_p, count: int) -> typing.Iterator[virtools_types.VxVector3]:
return map(
lambda v: virtools_types.VxVector3(*v),
_Utils._vector_iterator(ctypes.cast(pvector, bmap.bm_CKFLOAT_p), count, 3)
_utils._vector_iterator(ctypes.cast(pvector, bmap.bm_CKFLOAT_p), count, 3)
)
@staticmethod
def vxvector2_assigner(pvector: bmap.bm_VxVector2_p, count: int, itor: typing.Iterator[virtools_types.VxVector2]) -> None:
_Utils._vector_assigner(ctypes.cast(pvector, bmap.bm_CKFLOAT_p), count, 2, map(lambda v: (v.x, v.y), itor))
_utils._vector_assigner(ctypes.cast(pvector, bmap.bm_CKFLOAT_p), count, 2, map(lambda v: (v.x, v.y), itor))
@staticmethod
def vxvector2_iterator(pvector: bmap.bm_VxVector2_p, count: int) -> typing.Iterator[virtools_types.VxVector2]:
return map(
lambda v: virtools_types.VxVector2(*v),
_Utils._vector_iterator(ctypes.cast(pvector, bmap.bm_CKFLOAT_p), count, 2)
_utils._vector_iterator(ctypes.cast(pvector, bmap.bm_CKFLOAT_p), count, 2)
)
"""!
@remarks
bmap.bm_CKWORD_p | bmap.bm_CKDWORD_p is just a type hint.
We actually do not need distinguish them in code.
Because the stride when increasing them is decided by their runtime type.
"""
# YYC MARK:
# bmap.bm_CKWORD_p | bmap.bm_CKDWORD_p is just a type hint.
# We actually do not need distinguish them in code.
# Because the stride when increasing them is decided by their runtime type.
@staticmethod
def ckfaceindices_assigner(pindices: bmap.bm_CKWORD_p | bmap.bm_CKDWORD_p, count: int, itor: typing.Iterator[virtools_types.CKFaceIndices]) -> None:
_Utils._vector_assigner(pindices, count, 3, map(lambda v: (v.i1, v.i2, v.i3), itor))
_utils._vector_assigner(pindices, count, 3, map(lambda v: (v.i1, v.i2, v.i3), itor))
@staticmethod
def ckfaceindices_iterator(pindices: bmap.bm_CKWORD_p | bmap.bm_CKDWORD_p, count: int) -> typing.Iterator[virtools_types.CKFaceIndices]:
return map(
lambda v: virtools_types.CKFaceIndices(*v),
_Utils._vector_iterator(pindices, count, 3)
_utils._vector_iterator(pindices, count, 3)
)
#endregion
@@ -122,7 +126,7 @@ class _AbstractPointer():
TEnumType = typing.TypeVar('TEnumType', bound = enum.IntEnum)
TIntegralType = bmap.bm_CKDWORD | bmap.bm_CKWORD | bmap.bm_CKINT | bmap.bm_CKBYTE | bmap.bm_CKID
TFloatPointType = bmap.bm_CKFLOAT
TPointerType = typing.TypeVar('TPointerType')
TPointerType = typing.TypeVar('TPointerType', bound=ctypes._Pointer)
class _AbstractCKObject(_AbstractPointer):
__mCKID: int
@@ -148,6 +152,7 @@ class _AbstractCKObject(_AbstractPointer):
def __hash__(self) -> int:
return hash((_AbstractPointer.__hash__(self), self.__mCKID))
# YYC MARK:
# Convenient Value Getter Setter
# Focusing on those which widely called types.
@@ -183,11 +188,11 @@ class _AbstractCKObject(_AbstractPointer):
data: bmap.bm_CKSTRING = bmap.bm_CKSTRING()
getter_(self._get_pointer(), self._get_ckid(), ctypes.byref(data))
if data.value is None: return None
else: return data.value.decode(g_BMapEncoding)
else: return data.value.decode(BMAP_ENCODING)
def _set_str_value(self, setter_: typing.Callable[[bmap.bm_void_p, bmap.bm_CKID, bmap.bm_CKSTRING], bmap.bm_bool], data_: str | None) -> None:
data: bmap.bm_CKSTRING
if data_ is None: data = bmap.bm_CKSTRING(0)
else: data = bmap.bm_CKSTRING(data_.encode(g_BMapEncoding))
else: data = bmap.bm_CKSTRING(data_.encode(BMAP_ENCODING))
setter_(self._get_pointer(), self._get_ckid(), data)
def _set_vxcolor_value(self,
@@ -209,7 +214,7 @@ class _AbstractCKObject(_AbstractPointer):
return ret
def _get_pointer_value(self, ptr_type_: type[TPointerType], getter_: typing.Callable[[bmap.bm_void_p, bmap.bm_CKID, typing.Any], bmap.bm_bool]) -> TPointerType:
data = ptr_type_()
data: TPointerType = ptr_type_()
getter_(self._get_pointer(), self._get_ckid(), ctypes.byref(data))
return data
@@ -234,18 +239,16 @@ if is_bmap_available():
#region Real Type Defines
"""!
@remarks
BMFileReader, BMFileWriter, and BMMeshTrans can be create by given constructor.
But they must be destroyed by calling dispose(). Otherwise it may cause memory leak.
You also can use python `with` statement to achieve this automatically.
BMObject, BMTexture, BMMaterial, BMMesh, and BM3dObject should NOT be constructed from given constructor.
They must be obtained from BMFileReader, BMFileWriter, and BMMeshTrans.
Thus BMObject, BMTexture, BMMaterial, BMMesh, and BM3dObject also do not need to free
because these resources are sotred in BMFileReader, BMFileWriter, and BMMeshTrans.
We just provide them as a visitor.
"""
# YYC MARK:
# BMFileReader, BMFileWriter, and BMMeshTrans can be create by given constructor.
# But they must be destroyed by calling dispose(). Otherwise it may cause memory leak.
# You also can use python `with` statement to achieve this automatically.
#
# BMObject, BMTexture, BMMaterial, BMMesh, and BM3dObject should NOT be constructed from given constructor.
# They must be obtained from BMFileReader, BMFileWriter, and BMMeshTrans.
# Thus BMObject, BMTexture, BMMaterial, BMMesh, and BM3dObject also do not need to free
# because these resources are sotred in BMFileReader, BMFileWriter, and BMMeshTrans.
# We just provide them as a visitor.
class BMObject(_AbstractCKObject):
def get_name(self) -> str | None:
@@ -258,10 +261,10 @@ class BMTexture(BMObject):
return self._get_str_value(bmap.BMTexture_GetFileName)
def load_image(self, filepath: str) -> None:
filename: bmap.bm_CKSTRING = bmap.bm_CKSTRING(filepath.encode(g_BMapEncoding))
filename: bmap.bm_CKSTRING = bmap.bm_CKSTRING(filepath.encode(BMAP_ENCODING))
bmap.BMTexture_LoadImage(self._get_pointer(), self._get_ckid(), filename)
def save_image(self, filepath: str) -> None:
filename: bmap.bm_CKSTRING = bmap.bm_CKSTRING(filepath.encode(g_BMapEncoding))
filename: bmap.bm_CKSTRING = bmap.bm_CKSTRING(filepath.encode(BMAP_ENCODING))
bmap.BMTexture_SaveImage(self._get_pointer(), self._get_ckid(), filename)
def get_save_options(self) -> virtools_types.CK_TEXTURE_SAVEOPTIONS:
@@ -299,11 +302,11 @@ class BMMaterial(BMObject):
def get_texture(self) -> BMTexture | None:
objid: bmap.bm_CKID = bmap.bm_CKID()
bmap.BMMaterial_GetTexture(self._get_pointer(), self._get_ckid(), ctypes.byref(objid))
if objid.value == g_InvalidCKID: return None
if objid.value == INVALID_CKID: return None
else: return BMTexture(self._get_pointer(), objid)
def set_texture(self, tex_: BMTexture | None) -> None:
objid: bmap.bm_CKID = bmap.bm_CKID(g_InvalidCKID)
objid: bmap.bm_CKID = bmap.bm_CKID(INVALID_CKID)
if tex_ is not None: objid = tex_._get_ckid()
bmap.BMMaterial_SetTexture(self._get_pointer(), self._get_ckid(), objid)
@@ -398,25 +401,25 @@ class BMMesh(BMObject):
def get_vertex_positions(self) -> typing.Iterator[virtools_types.VxVector3]:
# get raw pointer and return
raw_vector = self._get_pointer_value(bmap.bm_VxVector3_p, bmap.BMMesh_GetVertexPositions)
return _Utils.vxvector3_iterator(raw_vector, self.get_vertex_count())
return _utils.vxvector3_iterator(raw_vector, self.get_vertex_count())
def set_vertex_positions(self, itor: typing.Iterator[virtools_types.VxVector3]) -> None:
# get raw float pointer and assign
raw_vector = self._get_pointer_value(bmap.bm_VxVector3_p, bmap.BMMesh_GetVertexPositions)
_Utils.vxvector3_assigner(raw_vector, self.get_vertex_count(), itor)
_utils.vxvector3_assigner(raw_vector, self.get_vertex_count(), itor)
def get_vertex_normals(self) -> typing.Iterator[virtools_types.VxVector3]:
raw_vector = self._get_pointer_value(bmap.bm_VxVector3_p, bmap.BMMesh_GetVertexNormals)
return _Utils.vxvector3_iterator(raw_vector, self.get_vertex_count())
return _utils.vxvector3_iterator(raw_vector, self.get_vertex_count())
def set_vertex_normals(self, itor: typing.Iterator[virtools_types.VxVector3]) -> None:
raw_vector = self._get_pointer_value(bmap.bm_VxVector3_p, bmap.BMMesh_GetVertexNormals)
_Utils.vxvector3_assigner(raw_vector, self.get_vertex_count(), itor)
_utils.vxvector3_assigner(raw_vector, self.get_vertex_count(), itor)
def get_vertex_uvs(self) -> typing.Iterator[virtools_types.VxVector2]:
raw_vector = self._get_pointer_value(bmap.bm_VxVector2_p, bmap.BMMesh_GetVertexUVs)
return _Utils.vxvector2_iterator(raw_vector, self.get_vertex_count())
return _utils.vxvector2_iterator(raw_vector, self.get_vertex_count())
def set_vertex_uvs(self, itor: typing.Iterator[virtools_types.VxVector2]) -> None:
raw_vector = self._get_pointer_value(bmap.bm_VxVector2_p, bmap.BMMesh_GetVertexUVs)
_Utils.vxvector2_assigner(raw_vector, self.get_vertex_count(), itor)
_utils.vxvector2_assigner(raw_vector, self.get_vertex_count(), itor)
def get_face_count(self) -> int:
return self._get_integral_value(bmap.bm_CKDWORD, bmap.BMMesh_GetFaceCount)
@@ -425,10 +428,10 @@ class BMMesh(BMObject):
def get_face_indices(self) -> typing.Iterator[virtools_types.CKFaceIndices]:
raw_idx = self._get_pointer_value(bmap.bm_CKWORD_p, bmap.BMMesh_GetFaceIndices)
return _Utils.ckfaceindices_iterator(raw_idx, self.get_face_count())
return _utils.ckfaceindices_iterator(raw_idx, self.get_face_count())
def set_face_indices(self, itor: typing.Iterator[virtools_types.CKFaceIndices]) -> None:
raw_idx = self._get_pointer_value(bmap.bm_CKWORD_p, bmap.BMMesh_GetFaceIndices)
_Utils.ckfaceindices_assigner(raw_idx, self.get_face_count(), itor)
_utils.ckfaceindices_assigner(raw_idx, self.get_face_count(), itor)
def get_face_material_slot_indexs(self) -> typing.Iterator[int]:
raw_idx = self._get_pointer_value(bmap.bm_CKWORD_p, bmap.BMMesh_GetFaceMaterialSlotIndexs)
@@ -441,7 +444,7 @@ class BMMesh(BMObject):
for i in range(self.get_face_count()):
raw_idx[i] = next(itor)
except StopIteration:
_Utils.raise_out_of_length_exception()
_utils.raise_out_of_length_exception()
def get_material_slot_count(self) -> int:
return self._get_integral_value(bmap.bm_CKDWORD, bmap.BMMesh_GetMaterialSlotCount)
@@ -454,7 +457,7 @@ class BMMesh(BMObject):
for i in range(self.get_material_slot_count()):
idx.value = i
bmap.BMMesh_GetMaterialSlot(self._get_pointer(), self._get_ckid(), idx, ctypes.byref(mtlid))
if mtlid.value == g_InvalidCKID:
if mtlid.value == INVALID_CKID:
yield None
else:
yield BMMaterial(self._get_pointer(), mtlid)
@@ -468,13 +471,13 @@ class BMMesh(BMObject):
# analyze mtl item
mtlobj: BMMaterial | None = next(itor)
if mtlobj is None:
mtlid.value = g_InvalidCKID
mtlid.value = INVALID_CKID
else:
mtlid = mtlobj._get_ckid()
# set
bmap.BMMesh_SetMaterialSlot(self._get_pointer(), self._get_ckid(), idx, mtlid)
except StopIteration:
_Utils.raise_out_of_length_exception()
_utils.raise_out_of_length_exception()
class BM3dEntity(BMObject):
def get_world_matrix(self) -> virtools_types.VxMatrix:
@@ -494,13 +497,13 @@ class BM3dEntity(BMObject):
def get_current_mesh(self) -> BMMesh | None:
ckid: bmap.bm_CKID = bmap.bm_CKID()
bmap.BM3dEntity_GetCurrentMesh(self._get_pointer(), self._get_ckid(), ctypes.byref(ckid))
if ckid.value == g_InvalidCKID:
if ckid.value == INVALID_CKID:
return None
else:
return BMMesh(self._get_pointer(), ckid)
def set_current_mesh(self, mesh: BMMesh | None) -> None:
ckid: bmap.bm_CKID = bmap.bm_CKID(g_InvalidCKID)
ckid: bmap.bm_CKID = bmap.bm_CKID(INVALID_CKID)
if mesh is not None:
ckid = mesh._get_ckid()
bmap.BM3dEntity_SetCurrentMesh(self._get_pointer(), self._get_ckid(), ckid)
@@ -558,6 +561,43 @@ class BMLight(BM3dEntity):
class BMTargetLight(BMLight):
pass
class BMCamera(BM3dEntity):
def get_projection_type(self) -> virtools_types.CK_CAMERA_PROJECTION:
return self._get_enum_value(virtools_types.CK_CAMERA_PROJECTION, bmap.BMCamera_GetProjectionType)
def set_projection_type(self, data_: virtools_types.CK_CAMERA_PROJECTION) -> None:
self._set_enum_value(bmap.BMCamera_SetProjectionType, data_)
def get_orthographic_zoom(self) -> float:
return self._get_float_point_value(bmap.bm_CKFLOAT, bmap.BMCamera_GetOrthographicZoom)
def set_orthographic_zoom(self, val_: float) -> None:
self._set_float_point_value(bmap.bm_CKFLOAT, bmap.BMCamera_SetOrthographicZoom, val_)
def get_front_plane(self) -> float:
return self._get_float_point_value(bmap.bm_CKFLOAT, bmap.BMCamera_GetFrontPlane)
def set_front_plane(self, val_: float) -> None:
self._set_float_point_value(bmap.bm_CKFLOAT, bmap.BMCamera_SetFrontPlane, val_)
def get_back_plane(self) -> float:
return self._get_float_point_value(bmap.bm_CKFLOAT, bmap.BMCamera_GetBackPlane)
def set_back_plane(self, val_: float) -> None:
self._set_float_point_value(bmap.bm_CKFLOAT, bmap.BMCamera_SetBackPlane, val_)
def get_fov(self) -> float:
return self._get_float_point_value(bmap.bm_CKFLOAT, bmap.BMCamera_GetFov)
def set_fov(self, val_: float) -> None:
self._set_float_point_value(bmap.bm_CKFLOAT, bmap.BMCamera_SetFov, val_)
def get_aspect_ratio(self) -> tuple[int, int]:
width = bmap.bm_CKDWORD()
height = bmap.bm_CKDWORD()
bmap.BMCamera_GetAspectRatio(self._get_pointer(), self._get_ckid(), ctypes.byref(width), ctypes.byref(height))
return (width.value, height.value)
def set_aspect_ratio(self, width_: int, height_: int) -> None:
width = bmap.bm_CKDWORD(width_)
height = bmap.bm_CKDWORD(height_)
bmap.BMCamera_SetAspectRatio(self._get_pointer(), self._get_ckid(), width, height)
class BMTargetCamera(BMCamera):
pass
class BMGroup(BMObject):
def add_object(self, member: BM3dObject) -> None:
bmap.BMGroup_AddObject(self._get_pointer(), self._get_ckid(), member._get_ckid())
@@ -578,19 +618,19 @@ class BMGroup(BMObject):
yield BM3dObject(self._get_pointer(), retid)
class BMFileReader(_AbstractPointer):
def __init__(self, file_name_: str, temp_folder_: str, texture_folder_: str, encodings_: tuple[str]):
def __init__(self, file_name_: str, temp_folder_: str, texture_folder_: str, encodings_: tuple[str, ...]):
# create param
file_name: bmap.bm_CKSTRING = bmap.bm_CKSTRING(file_name_.encode(g_BMapEncoding))
temp_folder: bmap.bm_CKSTRING = bmap.bm_CKSTRING(temp_folder_.encode(g_BMapEncoding))
texture_folder: bmap.bm_CKSTRING = bmap.bm_CKSTRING(texture_folder_.encode(g_BMapEncoding))
file_name: bmap.bm_CKSTRING = bmap.bm_CKSTRING(file_name_.encode(BMAP_ENCODING))
temp_folder: bmap.bm_CKSTRING = bmap.bm_CKSTRING(temp_folder_.encode(BMAP_ENCODING))
texture_folder: bmap.bm_CKSTRING = bmap.bm_CKSTRING(texture_folder_.encode(BMAP_ENCODING))
encoding_count: bmap.bm_CKDWORD = bmap.bm_CKDWORD(len(encodings_))
encodings: ctypes.Array = (bmap.bm_CKSTRING * len(encodings_))(
*(strl.encode(g_BMapEncoding) for strl in encodings_)
*(strl.encode(BMAP_ENCODING) for strl in encodings_)
)
out_file: bmap.bm_void_p = bmap.bm_void_p()
# exec
bmap.BMFile_Load(
file_name, temp_folder, texture_folder, _g_RawCallback,
file_name, temp_folder, texture_folder, RAW_CALLBACK,
encoding_count, encodings,
ctypes.byref(out_file)
)
@@ -606,7 +646,7 @@ class BMFileReader(_AbstractPointer):
def dispose(self) -> None:
if self._is_valid():
bmap.BMFile_Free(self._get_pointer())
self._set_pointer(g_InvalidPtr)
self._set_pointer(INVALID_PTR)
def __get_ckobject_count(self,
count_getter: typing.Callable[[bmap.bm_void_p, bmap.bm_CKDWORD_p], bmap.bm_bool]) -> int:
@@ -655,20 +695,25 @@ class BMFileReader(_AbstractPointer):
return self.__get_ckobject_count(bmap.BMFile_GetTargetLightCount)
def get_target_lights(self) -> typing.Iterator[BMTargetLight]:
return self.__get_ckobjects(BMTargetLight, bmap.BMFile_GetTargetLightCount, bmap.BMFile_GetTargetLight)
def get_target_camera_count(self) -> int:
return self.__get_ckobject_count(bmap.BMFile_GetTargetCameraCount)
def get_target_cameras(self) -> typing.Iterator[BMTargetCamera]:
return self.__get_ckobjects(BMTargetCamera, bmap.BMFile_GetTargetCameraCount, bmap.BMFile_GetTargetCamera)
class BMFileWriter(_AbstractPointer):
def __init__(self, temp_folder_: str, texture_folder_: str, encodings_: tuple[str]):
def __init__(self, temp_folder_: str, texture_folder_: str, encodings_: tuple[str, ...]):
# create param
temp_folder: bmap.bm_CKSTRING = bmap.bm_CKSTRING(temp_folder_.encode(g_BMapEncoding))
texture_folder: bmap.bm_CKSTRING = bmap.bm_CKSTRING(texture_folder_.encode(g_BMapEncoding))
temp_folder: bmap.bm_CKSTRING = bmap.bm_CKSTRING(temp_folder_.encode(BMAP_ENCODING))
texture_folder: bmap.bm_CKSTRING = bmap.bm_CKSTRING(texture_folder_.encode(BMAP_ENCODING))
encoding_count: bmap.bm_CKDWORD = bmap.bm_CKDWORD(len(encodings_))
encodings: ctypes.Array = (bmap.bm_CKSTRING * len(encodings_))(
*(strl.encode(g_BMapEncoding) for strl in encodings_)
*(strl.encode(BMAP_ENCODING) for strl in encodings_)
)
out_file: bmap.bm_void_p = bmap.bm_void_p()
# exec
bmap.BMFile_Create(
temp_folder, texture_folder, _g_RawCallback,
temp_folder, texture_folder, RAW_CALLBACK,
encoding_count, encodings,
ctypes.byref(out_file)
)
@@ -683,7 +728,7 @@ class BMFileWriter(_AbstractPointer):
def save(self, file_name_: str, texture_save_opt_: virtools_types.CK_TEXTURE_SAVEOPTIONS, use_compress_: bool, compress_level_: int) -> None:
# create param
file_name: bmap.bm_CKSTRING = bmap.bm_CKSTRING(file_name_.encode(g_BMapEncoding))
file_name: bmap.bm_CKSTRING = bmap.bm_CKSTRING(file_name_.encode(BMAP_ENCODING))
texture_save_opt: bmap.bm_enum = bmap.bm_enum(texture_save_opt_.value)
use_compress: bmap.bm_bool = bmap.bm_bool(use_compress_)
compress_level: bmap.bm_CKINT = bmap.bm_CKINT(compress_level_)
@@ -693,7 +738,7 @@ class BMFileWriter(_AbstractPointer):
def dispose(self) -> None:
if self._is_valid():
bmap.BMFile_Free(self._get_pointer())
self._set_pointer(g_InvalidPtr)
self._set_pointer(INVALID_PTR)
def __create_ckobject(self,
class_type: type[TCKObject],
@@ -717,6 +762,8 @@ class BMFileWriter(_AbstractPointer):
return self.__create_ckobject(BMGroup, bmap.BMFile_CreateGroup)
def create_target_light(self) -> BMTargetLight:
return self.__create_ckobject(BMTargetLight, bmap.BMFile_CreateTargetLight)
def create_target_camera(self) -> BMTargetCamera:
return self.__create_ckobject(BMTargetCamera, bmap.BMFile_CreateTargetCamera)
class BMMeshTrans(_AbstractPointer):
def __init__(self):
@@ -733,7 +780,7 @@ class BMMeshTrans(_AbstractPointer):
def dispose(self) -> None:
if self._is_valid():
bmap.BMMeshTrans_Delete(self._get_pointer())
self._set_pointer(g_InvalidPtr)
self._set_pointer(INVALID_PTR)
def parse(self, objmesh: BMMesh) -> None:
bmap.BMMeshTrans_Parse(self._get_pointer(), objmesh._get_pointer(), objmesh._get_ckid())
@@ -746,7 +793,7 @@ class BMMeshTrans(_AbstractPointer):
raw_vector: bmap.bm_VxVector3_p = bmap.bm_VxVector3_p()
bmap.BMMeshTrans_PrepareVertex(self._get_pointer(), ctypes.byref(raw_vector))
# set by pointer
_Utils.vxvector3_assigner(raw_vector, count, itor)
_utils.vxvector3_assigner(raw_vector, count, itor)
def prepare_normal(self, count: int, itor: typing.Iterator[virtools_types.VxVector3]) -> None:
csize: bmap.bm_CKDWORD = bmap.bm_CKDWORD(count)
@@ -755,7 +802,7 @@ class BMMeshTrans(_AbstractPointer):
raw_vector: bmap.bm_VxVector3_p = bmap.bm_VxVector3_p()
bmap.BMMeshTrans_PrepareNormal(self._get_pointer(), ctypes.byref(raw_vector))
_Utils.vxvector3_assigner(raw_vector, count, itor)
_utils.vxvector3_assigner(raw_vector, count, itor)
def prepare_uv(self, count: int, itor: typing.Iterator[virtools_types.VxVector2]) -> None:
csize: bmap.bm_CKDWORD = bmap.bm_CKDWORD(count)
@@ -764,7 +811,7 @@ class BMMeshTrans(_AbstractPointer):
raw_vector: bmap.bm_VxVector2_p = bmap.bm_VxVector2_p()
bmap.BMMeshTrans_PrepareUV(self._get_pointer(), ctypes.byref(raw_vector))
_Utils.vxvector2_assigner(raw_vector, count, itor)
_utils.vxvector2_assigner(raw_vector, count, itor)
def prepare_mtl_slot(self, count: int, itor: typing.Iterator[BMMaterial | None]) -> None:
csize: bmap.bm_CKDWORD = bmap.bm_CKDWORD(count)
@@ -777,12 +824,12 @@ class BMMeshTrans(_AbstractPointer):
for _ in range(count):
usermtl: BMMaterial | None = next(itor)
if usermtl is None:
raw_ckid[idx] = g_InvalidCKID
raw_ckid[idx] = INVALID_CKID
else:
raw_ckid[idx] = usermtl._get_ckid().value
idx += 1
except StopIteration:
_Utils.raise_out_of_length_exception()
_utils.raise_out_of_length_exception()
def prepare_face(self,
count: int,
@@ -806,9 +853,9 @@ class BMMeshTrans(_AbstractPointer):
# iterate and assign
# assigne triple indices
_Utils.ckfaceindices_assigner(raw_vec_idx, count, vec_idx)
_Utils.ckfaceindices_assigner(raw_nml_idx, count, nml_idx)
_Utils.ckfaceindices_assigner(raw_uv_idx, count, uv_idx)
_utils.ckfaceindices_assigner(raw_vec_idx, count, vec_idx)
_utils.ckfaceindices_assigner(raw_nml_idx, count, nml_idx)
_utils.ckfaceindices_assigner(raw_uv_idx, count, uv_idx)
# assign mtl index
try:
idx: int = 0
@@ -816,6 +863,6 @@ class BMMeshTrans(_AbstractPointer):
raw_mtl_idx[idx] = next(mtl_idx)
idx += 1
except StopIteration:
_Utils.raise_out_of_length_exception()
_utils.raise_out_of_length_exception()
#endregion

View File

@@ -0,0 +1,424 @@
import enum
ConstVxVector2 = tuple[float, float]
ConstVxVector3 = tuple[float, float, float]
ConstVxVector4 = tuple[float, float, float, float]
class VxVector2():
x: float
y: float
def __init__(self, _x: float = 0.0, _y: float = 0.0):
self.x = _x
self.y = _y
def from_const(self, cv: ConstVxVector2) -> None:
(self.x, self.y, ) = cv
def to_const(self) -> ConstVxVector2:
return (self.x, self.y, )
class VxVector3():
x: float
y: float
z: float
def __init__(self, _x: float = 0.0, _y: float = 0.0, _z: float = 0.0):
self.x = _x
self.y = _y
self.z = _z
def from_const(self, cv: ConstVxVector3) -> None:
(self.x, self.y, self.z) = cv
def to_const(self) -> ConstVxVector3:
return (self.x, self.y, self.z)
ConstCKFaceIndices = tuple[int, int, int]
class CKFaceIndices():
i1: int
i2: int
i3: int
def __init__(self, i1_: int = 0, i2_: int = 0, i3_: int = 0):
self.i1 = i1_
self.i2 = i2_
self.i3 = i3_
def from_const(self, cv: ConstCKFaceIndices) -> None:
(self.i1, self.i2, self.i3) = cv
def to_const(self) -> ConstCKFaceIndices:
return (self.i1, self.i2, self.i3)
ConstVxColorRGBA = tuple[float, float, float, float]
ConstVxColorRGB = tuple[float, float, float]
class VxColor():
"""
The Color struct support RGBA.
"""
a: float
r: float
g: float
b: float
def __init__(self, _r: float = 0.0, _g: float = 0.0, _b: float = 0.0, _a: float = 1.0):
self.r = _r
self.g = _g
self.b = _b
self.a = _a
self.regulate()
def to_const_rgba(self) -> ConstVxColorRGBA:
return (self.r, self.g, self.b, self.a)
def to_const_rgb(self) -> ConstVxColorRGB:
return (self.r, self.g, self.b)
def from_const_rgba(self, val: ConstVxColorRGBA) -> None:
(self.r, self.g, self.b, self.a) = val
self.regulate()
def from_const_rgb(self, val: ConstVxColorRGB) -> None:
(self.r, self.g, self.b) = val
self.a = 1.0
self.regulate()
def from_dword(self, val: int) -> None:
self.b = float(val & 0xFF) / 255.0
val >>= 8
self.g = float(val & 0xFF) / 255.0
val >>= 8
self.r = float(val & 0xFF) / 255.0
val >>= 8
self.a = float(val & 0xFF) / 255.0
val >>= 8
def to_dword(self) -> int:
# regulate self
self.regulate()
# construct value
val: int = 0
val |= int(self.a * 255)
val <<= 8
val |= int(self.r * 255)
val <<= 8
val |= int(self.g * 255)
val <<= 8
val |= int(self.b * 255)
return val
def clone(self):
return VxColor(self.r, self.g, self.b, self.a)
@staticmethod
def _clamp_factor(val: float) -> float:
if val > 1.0: return 1.0
elif val < 0.0: return 0.0
else: return val
def regulate(self):
self.a = VxColor._clamp_factor(self.a)
self.r = VxColor._clamp_factor(self.r)
self.g = VxColor._clamp_factor(self.g)
self.b = VxColor._clamp_factor(self.b)
ConstVxMatrix = tuple[
float, float, float, float,
float, float, float, float,
float, float, float, float,
float, float, float, float
]
class VxMatrix():
"""
The Matrix representation.
The bracket statement exactly equal with Virtools.
"""
data: list[list[float]]
def __init__(self):
# init array
self.data = [[0] * 4 for i in range(4)]
# set to identy
self.reset()
def _get_raw(self) -> list[list[float]]:
return self.data
def reset(self) -> None:
# reset to identy
for i in range(4):
for j in range(4):
self.data[i][j] = 0.0
self.data[0][0] = 1.0
self.data[1][1] = 1.0
self.data[2][2] = 1.0
self.data[3][3] = 1.0
def from_const(self, cm: ConstVxMatrix) -> None:
(
self.data[0][0], self.data[0][1], self.data[0][2], self.data[0][3],
self.data[1][0], self.data[1][1], self.data[1][2], self.data[1][3],
self.data[2][0], self.data[2][1], self.data[2][2], self.data[2][3],
self.data[3][0], self.data[3][1], self.data[3][2], self.data[3][3]
) = cm
def to_const(self) -> ConstVxMatrix:
return (
self.data[0][0], self.data[0][1], self.data[0][2], self.data[0][3],
self.data[1][0], self.data[1][1], self.data[1][2], self.data[1][3],
self.data[2][0], self.data[2][1], self.data[2][2], self.data[2][3],
self.data[3][0], self.data[3][1], self.data[3][2], self.data[3][3]
)
class CK_TEXTURE_SAVEOPTIONS(enum.IntEnum):
"""
Specify the way textures or sprites will be saved
"""
CKTEXTURE_RAWDATA = 0
"""Save raw data inside file. The bitmap is saved in a raw 32 bit per pixel format."""
CKTEXTURE_EXTERNAL = 1
"""Store only the file name for the texture. The bitmap file must be present in the bitmap pathswhen loading the composition."""
CKTEXTURE_IMAGEFORMAT = 2
"""Save using format specified. The bitmap data will be converted to thespecified format by the correspondant bitmap plugin and saved inside file."""
CKTEXTURE_USEGLOBAL = 3
"""Use Global settings, that is the settings given with CKContext::SetGlobalImagesSaveOptions. (Not valid when using CKContext::SetImagesSaveOptions)."""
CKTEXTURE_INCLUDEORIGINALFILE = 4
"""Insert original image file inside CMO file. The bitmap file thatwas used originally for the texture or sprite will be append tothe composition file and extracted when the file is loaded."""
class VX_PIXELFORMAT(enum.IntEnum):
"""
Pixel format types.
"""
# UNKNOWN_PF = 0
# """Unknown pixel format"""
_32_ARGB8888 = 1
"""32-bit ARGB pixel format with alpha"""
_32_RGB888 = 2
"""32-bit RGB pixel format without alpha"""
_24_RGB888 = 3
"""24-bit RGB pixel format"""
_16_RGB565 = 4
"""16-bit RGB pixel format"""
_16_RGB555 = 5
"""16-bit RGB pixel format (5 bits per color)"""
_16_ARGB1555 = 6
"""16-bit ARGB pixel format (5 bits per color + 1 bit for alpha)"""
_16_ARGB4444 = 7
"""16-bit ARGB pixel format (4 bits per color)"""
_8_RGB332 = 8
"""8-bit RGB pixel format"""
_8_ARGB2222 = 9
"""8-bit ARGB pixel format"""
_32_ABGR8888 = 10
"""32-bit ABGR pixel format"""
_32_RGBA8888 = 11
"""32-bit RGBA pixel format"""
_32_BGRA8888 = 12
"""32-bit BGRA pixel format"""
_32_BGR888 = 13
"""32-bit BGR pixel format"""
_24_BGR888 = 14
"""24-bit BGR pixel format"""
_16_BGR565 = 15
"""16-bit BGR pixel format"""
_16_BGR555 = 16
"""16-bit BGR pixel format (5 bits per color)"""
_16_ABGR1555 = 17
"""16-bit ABGR pixel format (5 bits per color + 1 bit for alpha)"""
_16_ABGR4444 = 18
"""16-bit ABGR pixel format (4 bits per color)"""
_DXT1 = 19
"""S3/DirectX Texture Compression 1"""
_DXT2 = 20
"""S3/DirectX Texture Compression 2"""
_DXT3 = 21
"""S3/DirectX Texture Compression 3"""
_DXT4 = 22
"""S3/DirectX Texture Compression 4"""
_DXT5 = 23
"""S3/DirectX Texture Compression 5"""
_16_V8U8 = 24
"""16-bit Bump Map format format (8 bits per color)"""
_32_V16U16 = 25
"""32-bit Bump Map format format (16 bits per color)"""
_16_L6V5U5 = 26
"""16-bit Bump Map format format with luminance"""
_32_X8L8V8U8 = 27
"""32-bit Bump Map format format with luminance"""
_8_ABGR8888_CLUT = 28
"""8 bits indexed CLUT (ABGR)"""
_8_ARGB8888_CLUT = 29
"""8 bits indexed CLUT (ARGB)"""
_4_ABGR8888_CLUT = 30
"""4 bits indexed CLUT (ABGR)"""
_4_ARGB8888_CLUT = 31
"""4 bits indexed CLUT (ARGB)"""
class VXLIGHT_TYPE(enum.IntEnum):
"""
Light type.
"""
VX_LIGHTPOINT = 1
"""The Light is a point of light"""
VX_LIGHTSPOT = 2
"""The light is a spotlight"""
VX_LIGHTDIREC = 3
"""The light is directional light : Lights comes from an infinite point so only direction of light can be given"""
# VX_LIGHTPARA = 4
# """Obsolete, do not use"""
class VXTEXTURE_BLENDMODE(enum.IntEnum):
"""
Blend Mode Flags
"""
VXTEXTUREBLEND_DECAL = 1
"""Texture replace any material information"""
VXTEXTUREBLEND_MODULATE = 2
"""Texture and material are combine. Alpha information of the texture replace material alpha component."""
VXTEXTUREBLEND_DECALALPHA = 3
"""Alpha information in the texture specify how material and texture are combined. Alpha information of the texture replace material alpha component."""
VXTEXTUREBLEND_MODULATEALPHA = 4
"""Alpha information in the texture specify how material and texture are combined"""
VXTEXTUREBLEND_DECALMASK = 5
VXTEXTUREBLEND_MODULATEMASK = 6
VXTEXTUREBLEND_COPY = 7
"""Equivalent to DECAL"""
VXTEXTUREBLEND_ADD = 8
VXTEXTUREBLEND_DOTPRODUCT3 = 9
"""Perform a Dot Product 3 between texture (normal map)and a referential vector given in VXRENDERSTATE_TEXTUREFACTOR."""
VXTEXTUREBLEND_MAX = 10
# VXTEXTUREBLEND_MASK = 0xF
class VXTEXTURE_FILTERMODE(enum.IntEnum):
"""
Filter Mode Options
"""
VXTEXTUREFILTER_NEAREST = 1
"""No Filter"""
VXTEXTUREFILTER_LINEAR = 2
"""Bilinear Interpolation"""
VXTEXTUREFILTER_MIPNEAREST = 3
"""Mip mapping"""
VXTEXTUREFILTER_MIPLINEAR = 4
"""Mip Mapping with Bilinear interpolation"""
VXTEXTUREFILTER_LINEARMIPNEAREST = 5
"""Mip Mapping with Bilinear interpolation between mipmap levels."""
VXTEXTUREFILTER_LINEARMIPLINEAR = 6
"""Trilinear Filtering"""
VXTEXTUREFILTER_ANISOTROPIC = 7
"""Anisotropic filtering"""
# VXTEXTUREFILTER_MASK = 0xF
class VXTEXTURE_ADDRESSMODE(enum.IntEnum):
"""
Texture addressing modes.
"""
VXTEXTURE_ADDRESSWRAP = 1
"""Default mesh wrap mode is used (see CKMesh::SetWrapMode)"""
VXTEXTURE_ADDRESSMIRROR = 2
"""Texture coordinates outside the range [0..1] are flipped evenly."""
VXTEXTURE_ADDRESSCLAMP = 3
"""Texture coordinates greater than 1.0 are set to 1.0, and values less than 0.0 are set to 0.0."""
VXTEXTURE_ADDRESSBORDER = 4
"""When texture coordinates are greater than 1.0 or less than 0.0 texture is set to a color defined in CKMaterial::SetTextureBorderColor."""
VXTEXTURE_ADDRESSMIRRORONCE = 5
""""""
# VXTEXTURE_ADDRESSMASK = 0x7
# """mask for all values"""
class VXBLEND_MODE(enum.IntEnum):
"""
Blending Mode options
"""
VXBLEND_ZERO = 1
"""Blend factor is (0, 0, 0, 0)."""
VXBLEND_ONE = 2
"""Blend factor is (1, 1, 1, 1)."""
VXBLEND_SRCCOLOR = 3
"""Blend factor is (Rs, Gs, Bs, As)."""
VXBLEND_INVSRCCOLOR = 4
"""Blend factor is (1-Rs, 1-Gs, 1-Bs, 1-As)."""
VXBLEND_SRCALPHA = 5
"""Blend factor is (As, As, As, As)."""
VXBLEND_INVSRCALPHA = 6
"""Blend factor is (1-As, 1-As, 1-As, 1-As)."""
VXBLEND_DESTALPHA = 7
"""Blend factor is (Ad, Ad, Ad, Ad)."""
VXBLEND_INVDESTALPHA = 8
"""Blend factor is (1-Ad, 1-Ad, 1-Ad, 1-Ad)."""
VXBLEND_DESTCOLOR = 9
"""Blend factor is (Rd, Gd, Bd, Ad)."""
VXBLEND_INVDESTCOLOR = 10
"""Blend factor is (1-Rd, 1-Gd, 1-Bd, 1-Ad)."""
VXBLEND_SRCALPHASAT = 11
"""Blend factor is (f, f, f, 1); f = min(As, 1-Ad)."""
# VXBLEND_BOTHSRCALPHA = 12
# """Source blend factor is (As, As, As, As) and destination blend factor is (1-As, 1-As, 1-As, 1-As)"""
# VXBLEND_BOTHINVSRCALPHA = 13
# """Source blend factor is (1-As, 1-As, 1-As, 1-As) and destination blend factor is (As, As, As, As)"""
# VXBLEND_MASK = 0xF
# """Source blend factor is (1-As, 1-As, 1-As, 1-As) and destination blend factor is (As, As, As, As)"""
class VXFILL_MODE(enum.IntEnum):
"""
Fill Mode Options
"""
VXFILL_POINT = 1
"""Vertices rendering"""
VXFILL_WIREFRAME = 2
"""Edges rendering"""
VXFILL_SOLID = 3
"""Face rendering"""
# VXFILL_MASK = 3
class VXSHADE_MODE(enum.IntEnum):
"""
Shade Mode Options
"""
VXSHADE_FLAT = 1
"""Flat Shading"""
VXSHADE_GOURAUD = 2
"""Gouraud Shading"""
VXSHADE_PHONG = 3
"""Phong Shading (Not yet supported by most implementation)"""
# VXSHADE_MASK = 3
class VXCMPFUNC(enum.IntEnum):
"""
Comparison Function
"""
VXCMP_NEVER = 1
"""Always fail the test."""
VXCMP_LESS = 2
"""Accept if value if less than current value."""
VXCMP_EQUAL = 3
"""Accept if value if equal than current value."""
VXCMP_LESSEQUAL = 4
"""Accept if value if less or equal than current value."""
VXCMP_GREATER = 5
"""Accept if value if greater than current value."""
VXCMP_NOTEQUAL = 6
"""Accept if value if different than current value."""
VXCMP_GREATEREQUAL = 7
"""Accept if value if greater or equal current value."""
VXCMP_ALWAYS = 8
"""Always accept the test."""
# VXCMP_MASK = 0xF
# """Mask for all possible values."""
class VXMESH_LITMODE(enum.IntEnum):
"""
Mesh lighting options
"""
VX_PRELITMESH = 0
"""Lighting use color information store with vertices"""
VX_LITMESH = 1
"""Lighting is done by renderer using normals and face material information."""
class CK_CAMERA_PROJECTION(enum.IntEnum):
CK_PERSPECTIVEPROJECTION = 1
CK_ORTHOGRAPHICPROJECTION = 2

View File

@@ -0,0 +1,40 @@
import os
from pathlib import Path
class CliException(Exception):
"""Error occurs when parsing test arguments."""
pass
class Cli:
file_name: Path
"""
The path to the map for loading.
"""
ballance_dir: Path
"""
The path to the Ballance directory for finding textures
"""
encodings: tuple[str, ...]
"""
The name of encodings used by BMap for loading map.
"""
def __init__(self) -> None:
file_name = os.environ.get('BMAP_FILE_NAME', None)
if file_name is None:
raise CliException('You must specify BMAP_FILE_NAME environment variable before running this test.')
else:
self.file_name = Path(file_name).resolve()
ballance_dir = os.environ.get('BMAP_BALLANCE_DIR', None)
if ballance_dir is None:
raise CliException('You must specify BMAP_BALLANCE_DIR environment variable before running this test.')
else:
self.ballance_dir = Path(ballance_dir).resolve()
encodings = os.environ.get('BMAP_ENCODINGS', None)
if encodings is None:
raise CliException('You must specify BMAP_ENCODINGS environment variable before running this test.')
else:
self.encodings = tuple(encodings.split(','))

View File

@@ -0,0 +1,35 @@
import os
from pathlib import Path
from tempfile import TemporaryDirectory
import pybmap.bmap_wrapper as bmap
import cli
import testsuits
def main() -> None:
# Parse arguments
try:
cliopts = cli.Cli()
except cli.CliException as e:
print(f'Can not launch test. Reason: {e}')
return
# Check BMap status.
if not bmap.is_bmap_available():
print('Fail to initialize native BMap.')
return
# Waiting debugger
input(f'Python PID is {os.getpid()}. Waiting for debugger, press any key to continue...')
# Start testbench
with TemporaryDirectory() as tempdir:
file_name = str(cliopts.file_name)
temp_folder = str(tempdir)
texture_folder = str(cliopts.ballance_dir / 'Textures')
encodings = cliopts.encodings
with bmap.BMFileReader(file_name, temp_folder, texture_folder, encodings) as reader:
testsuits.TestCommon.test(reader)
testsuits.TestEq.test(reader)
if __name__ == '__main__':
main()

View File

@@ -0,0 +1,177 @@
import pybmap.bmap_wrapper as bmap
from pybmap.bmap_wrapper import BMFileReader
class TestCommon:
@staticmethod
def test(reader: BMFileReader) -> None:
print('===== Groups =====')
TestCommon.__test_group(reader)
print('===== 3dObjects =====')
TestCommon.__test_3dobject(reader)
print('===== Meshes =====')
TestCommon.__test_mesh(reader)
print('===== Materials =====')
TestCommon.__test_material(reader)
print('===== Textures =====')
TestCommon.__test_texture(reader)
print('===== Target Lights =====')
TestCommon.__test_target_light(reader)
print('===== Target Cameras =====')
TestCommon.__test_target_camera(reader)
print('===== END =====')
@staticmethod
def __test_group(reader: BMFileReader) -> None:
for gp in reader.get_groups():
print(gp.get_name())
for gp_item in gp.get_objects():
print(f'\t{gp_item.get_name()}')
@staticmethod
def __test_3dobject(reader: BMFileReader) -> None:
for obj in reader.get_3dobjects():
print(obj.get_name())
current_mesh = obj.get_current_mesh()
mesh_name = '<null>' if current_mesh is None else current_mesh.get_name()
print(f'\tMesh: {mesh_name}')
print(f'\tVisibility: {obj.get_visibility()}')
print(f'\tMatrix: {obj.get_world_matrix().to_const()}')
@staticmethod
def __test_mesh(reader: BMFileReader) -> None:
for mesh in reader.get_meshs():
print(mesh.get_name())
print(f'\tLit Mode: {mesh.get_lit_mode()}')
print(f'\tVertex Count: {mesh.get_vertex_count()}')
print(f'\tFace Count: {mesh.get_face_count()}')
print(f'\tMaterial Slot Count: {mesh.get_material_slot_count()}')
@staticmethod
def __test_material(reader: BMFileReader) -> None:
for mtl in reader.get_materials():
print(mtl.get_name())
print(f'\tDiffuse: {mtl.get_diffuse().to_const_rgba()}')
print(f'\tAmbient: {mtl.get_ambient().to_const_rgba()}')
print(f'\tSpecular: {mtl.get_specular().to_const_rgba()}')
print(f'\tEmissive: {mtl.get_emissive().to_const_rgba()}')
print(f'\tSpecular Power: {mtl.get_specular_power()}')
print(f'\tTexture Border Color: {mtl.get_texture_border_color().to_const_rgba()}')
print(f'\tTexture Blend Mode: {mtl.get_texture_blend_mode()}')
print(f'\tTexture Min Mode: {mtl.get_texture_min_mode()}')
print(f'\tTexture Mag Mode: {mtl.get_texture_mag_mode()}')
print(f'\tSource Blend: {mtl.get_source_blend()}')
print(f'\tDest Blend: {mtl.get_dest_blend()}')
print(f'\tFill Mode: {mtl.get_fill_mode()}')
print(f'\tShade Mode: {mtl.get_shade_mode()}')
print(f'\tAlpha Test Enabled: {mtl.get_alpha_test_enabled()}')
print(f'\tAlpha Blend Enabled: {mtl.get_alpha_blend_enabled()}')
print(f'\tPerspective Correction Enabled: {mtl.get_perspective_correction_enabled()}')
print(f'\tZ Write Enabled: {mtl.get_z_write_enabled()}')
print(f'\tTwo Sided Enabled: {mtl.get_two_sided_enabled()}')
print(f'\tAlpha Ref: {mtl.get_alpha_ref()}')
print(f'\tAlpha Func: {mtl.get_alpha_func()}')
print(f'\tZ Func: {mtl.get_z_func()}')
@staticmethod
def __test_texture(reader: BMFileReader) -> None:
for tex in reader.get_textures():
print(tex.get_name())
print(f'\tFile Name: {tex.get_file_name()}')
print(f'\tSave Options: {tex.get_save_options()}')
print(f'\tVideo Format: {tex.get_video_format()}')
@staticmethod
def __test_target_light(reader: BMFileReader) -> None:
for lit in reader.get_target_lights():
print(lit.get_name())
print(f'\tVisibility: {lit.get_visibility()}')
print(f'\tMatrix: {lit.get_world_matrix().to_const()}')
print(f'\tType: {lit.get_type()}')
print(f'\tColor: {lit.get_color().to_const_rgba()}')
print(f'\tConstant Attenuation: {lit.get_constant_attenuation()}')
print(f'\tLinear Attenuation: {lit.get_linear_attenuation()}')
print(f'\tQuadratic Attenuation: {lit.get_quadratic_attenuation()}')
print(f'\tRange: {lit.get_range()}')
print(f'\tHot Spot: {lit.get_hot_spot()}')
print(f'\tFalloff: {lit.get_falloff()}')
print(f'\tFalloff Shape: {lit.get_falloff_shape()}')
@staticmethod
def __test_target_camera(reader: BMFileReader) -> None:
for cam in reader.get_target_cameras():
print(cam.get_name())
print(f'\tVisibility: {cam.get_visibility()}')
print(f'\tMatrix: {cam.get_world_matrix().to_const()}')
print(f'\tType: {cam.get_projection_type()}')
print(f'\tOrthographic Zoom: {cam.get_orthographic_zoom()}')
print(f'\tFront Plane: {cam.get_front_plane()}')
print(f'\tBack Plane: {cam.get_back_plane()}')
print(f'\tFov: {cam.get_fov()}')
(width, height) = cam.get_aspect_ratio()
print(f'\tAspect Ratio: {width}:{height}')
class TestEq:
@staticmethod
def test(reader: BMFileReader) -> None:
# Check requirements
assert (reader.get_3dobject_count() >= 2), '''
Invalid file for test __eq__.
We can not perform __eq__ test because the length of 3dObject is too short (must greater than 2). Please choose another file to perform.
'''
# Prepare variables
all_3dobjects: tuple[bmap.BM3dObject, ...] = tuple(reader.get_3dobjects())
first_3dobj: bmap.BM3dObject = all_3dobjects[0]
second_3dobj: bmap.BM3dObject = all_3dobjects[1]
all_3dobjects = tuple(reader.get_3dobjects())
first_3dobj_again: bmap.BM3dObject = all_3dobjects[0]
# Test set
test_set: set[bmap.BM3dObject] = set()
test_set.add(first_3dobj)
assert len(test_set) == 1
assert first_3dobj in test_set
assert first_3dobj_again in test_set
assert second_3dobj not in test_set
test_set.add(first_3dobj_again)
assert len(test_set) == 1
test_set.add(second_3dobj)
assert len(test_set) == 2
assert second_3dobj in test_set
# Test dict
test_dict: dict[bmap.BM3dObject, str | None] = {}
test_dict[first_3dobj] = first_3dobj.get_name()
assert len(test_dict) == 1
assert first_3dobj in test_dict
assert first_3dobj_again in test_dict
assert second_3dobj not in test_dict
test_dict[first_3dobj_again] = first_3dobj_again.get_name()
assert len(test_dict) == 1
test_dict[second_3dobj] = second_3dobj.get_name()
assert len(test_dict) == 2
assert second_3dobj in test_dict

8
Assets/BMapBindings/pybmap/uv.lock generated Normal file
View File

@@ -0,0 +1,8 @@
version = 1
revision = 2
requires-python = ">=3.11"
[[package]]
name = "pybmap"
version = "0.4.0"
source = { editable = "." }

View File

@@ -1,70 +0,0 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "bmap"
version = "0.4.0"
dependencies = [
"bmap-sys",
"thiserror",
]
[[package]]
name = "bmap-sys"
version = "0.4.0"
[[package]]
name = "proc-macro2"
version = "1.0.106"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.44"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "21b2ebcf727b7760c461f091f9f0f539b77b8e87f2fd88131e7f1b433b3cece4"
dependencies = [
"proc-macro2",
]
[[package]]
name = "syn"
version = "2.0.114"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d4d107df263a3013ef9b1879b0df87d706ff80f65a86ea879bd9c31f9b307c2a"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "thiserror"
version = "2.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4"
dependencies = [
"thiserror-impl",
]
[[package]]
name = "thiserror-impl"
version = "2.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "unicode-ident"
version = "1.0.22"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9312f7c4f6ff9069b165498234ce8be658059c6728633667c526e27dc2cf1df5"

View File

@@ -1,6 +0,0 @@
[workspace]
resolver = "3"
members = ["bmap","bmap-sys"]
[workspace.dependencies]
thiserror = "2.0.12"

View File

@@ -1,9 +0,0 @@
use std::ffi::{CStr, CString};
use std::os::raw::{c_float, c_void};
//use std::ptr;
#[link(name = "BMap", kind = "dylib")]
unsafe extern "C" {
pub unsafe fn BMInit() -> bool;
pub unsafe fn BMDispose() -> bool;
}

View File

@@ -1,7 +0,0 @@
use bmap_sys;
#[test]
fn test_init_and_dispose() {
assert!(unsafe { bmap_sys::BMInit() });
assert!(unsafe { bmap_sys::BMDispose() });
}

View File

@@ -1,11 +0,0 @@
[package]
name = "bmap"
version = "0.4.0"
authors = ["yyc12345"]
edition = "2024"
description = "The wrapper for Rust binding to BMap."
license = "SPDX:MIT"
[dependencies]
thiserror = { workspace = true }
bmap-sys = { path="../bmap-sys" }

View File

@@ -1 +0,0 @@
use bmap_sys;

View File

@@ -14,7 +14,7 @@ def _get_libcmo21_repo_directory() -> Path:
def get_input_file_path() -> Path:
return _get_libcmo21_repo_directory() / "BMap" / "BMap" / "BMExports.hpp"
return _get_libcmo21_repo_directory() / "Ballance" / "BMap" / "BMap" / "BMExports.hpp"
def _get_bmap_binder_directory() -> Path:

View File

@@ -32,6 +32,7 @@ CPP_PY_TYPE_MAP: dict[str, str] = {
"VXSHADE_MODE": "enum",
"VXCMPFUNC": "enum",
"VXMESH_LITMODE": "enum",
"CK_CAMERA_PROJECTION": "enum",
}
CS_ENUM_LIKE: set[str] = set((
@@ -46,8 +47,39 @@ CS_ENUM_LIKE: set[str] = set((
"VXSHADE_MODE",
"VXCMPFUNC",
"VXMESH_LITMODE",
"CK_CAMERA_PROJECTION",
))
CPP_RS_TYPE_MAP: dict[str, str] = {
"CKSTRING": "CKSTRING",
"CKDWORD": "CKDWORD",
"CKWORD": "CKWORD",
"CKINT": "CKINT",
"bool": "BMBOOL",
"CKFLOAT": "CKFLOAT",
"CKBYTE": "CKBYTE",
"CK_ID": "CKID",
"NakedOutputCallback": "BMCALLBACK",
"BMFile": "BMVOID",
"BMMeshTransition": "BMVOID",
"VxVector3": "VxVector3",
"VxVector2": "VxVector2",
"VxColor": "VxColor",
"VxMatrix": "VxMatrix",
"CK_TEXTURE_SAVEOPTIONS": "CK_TEXTURE_SAVEOPTIONS",
"VX_PIXELFORMAT": "VX_PIXELFORMAT",
"VXLIGHT_TYPE": "VXLIGHT_TYPE",
"VXTEXTURE_BLENDMODE": "VXTEXTURE_BLENDMODE",
"VXTEXTURE_FILTERMODE": "VXTEXTURE_FILTERMODE",
"VXTEXTURE_ADDRESSMODE": "VXTEXTURE_ADDRESSMODE",
"VXBLEND_MODE": "VXBLEND_MODE",
"VXFILL_MODE": "VXFILL_MODE",
"VXSHADE_MODE": "VXSHADE_MODE",
"VXCMPFUNC": "VXCMPFUNC",
"VXMESH_LITMODE": "VXMESH_LITMODE",
"CK_CAMERA_PROJECTION": "CK_CAMERA_PROJECTION",
}
@dataclass(frozen=True)
class CsInteropType:
"""The class represent the C# type corresponding to extracted variable type."""
@@ -108,10 +140,12 @@ class RenderUtils:
# only allow 0 and 1 pointer level for string.
match vt_pointer_level:
case 0:
marshal_as = f'UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(BMStringMarshaler), MarshalCookie = "{direction_cookie}"'
marshaler = 'BMOwnedStringMarshaler' if param.is_input else 'BMStringMarshaler'
marshal_as = f'UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof({marshaler})'
cs_type = "string"
case 1:
marshal_as = f'UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(BMStringArrayMarshaler), MarshalCookie = "{direction_cookie}"'
marshaler = 'BMOwnedStringArrayMarshaler' if param.is_input else 'BMStringArrayMarshaler'
marshal_as = f'UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof({marshaler})'
cs_type = "string[]"
case "CKDWORD":
if vt_pointer_level == 0:
@@ -225,6 +259,25 @@ class RenderUtils:
# return value
return CsInteropType(marshal_as, cs_type)
@staticmethod
def get_rust_type(param: ExpFctParam) -> str:
vt = param.var_type
# setup pointer level
sb: str = 'P' * vt.get_pointer_level()
# try getting cpp type from base type and add it
cpp_type = CPP_RS_TYPE_MAP.get(vt.get_base_type(), None)
if cpp_type is None:
raise RuntimeError(f"unexpected type {vt.to_c_type()}")
else:
sb += cpp_type
# return built type string.
if param.is_input:
return f'param_in!({sb})'
else:
return f'param_out!({sb})'
class TemplateRender:
"""Render templates to code files"""

View File

@@ -4,7 +4,7 @@
/// <param name="{{ param.var_name }}">Direction: {% if param.is_input -%} input {%- else -%} output {%- endif %}. C++ type: {{ param.var_type.to_c_type() }}. {{ param.var_desc }}</param>
{%- endfor %}
/// <returns>True if no error, otherwise False.</returns>
[DllImport(g_DllName, EntryPoint = "{{ fct.fct_name }}", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)]
[DllImport(DLL_NAME, EntryPoint = "{{ fct.fct_name }}", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)]
[return: MarshalAs(UnmanagedType.U1)]
internal static extern bool {{ fct.fct_name }}(
{%- for param in fct.fct_params -%}

View File

@@ -1,15 +1,10 @@
{%- for fct in payload.fcts %}
{{ fct.fct_name }} = _create_bmap_func('{{ fct.fct_name }}', [
{%- for param in fct.fct_params %}
{{- utils.get_python_type(param) }}
{%- if not loop.last %}, {% endif %}
{%- endfor -%}
])
{{ fct.fct_name }} = _create_bmap_func('{{ fct.fct_name }}', ({% for param in fct.fct_params %}{{ utils.get_python_type(param) }}, {% endfor %}))
"""
{{ fct.fct_name }}
{% for param in fct.fct_params %}
:param {{ param.var_name }}: Direction: {% if param.is_input -%} input {%- else -%} output {%- endif %}. {{ param.var_desc }}
:type {{ param.var_name }}: {{ utils.get_python_type(param) }} ({{ param.var_type.to_c_type() }} in C++). {% if param.is_input -%} Use ctypes.byref() pass it. {%- endif %}
:type {{ param.var_name }}: {{ utils.get_python_type(param) }} ({{ param.var_type.to_c_type() }} in C++). {% if not param.is_input -%} Use ctypes.byref(data) pass it. {%- endif %}
{%- endfor %}
:return: True if no error, otherwise False.
:rtype: bool

View File

@@ -0,0 +1,19 @@
{%- for fct in payload.fcts %}
/// {{ fct.fct_name }}
///
/// # Parameters
///
{%- for param in fct.fct_params %}
/// - `{{ param.var_name }}`: Direction: {% if param.is_input -%} input {%- else -%} output {%- endif %}. C++ type: `{{ param.var_type.to_c_type() }}`. {{ param.var_desc }}
{%- endfor %}
///
/// # Return
///
/// True if no error, otherwise False.
pub unsafe fn {{ fct.fct_name }}(
{%- for param in fct.fct_params -%}
{{ param.var_name }}: {{ utils.get_rust_type(param) }}
{%- if not loop.last %}, {% endif %}
{%- endfor -%}
) -> BMBOOL;
{%- endfor %}

View File

@@ -72,9 +72,13 @@ public class ClassidWalker extends CKDefinesParserBaseListener {
mLevel = 0;
mLevelStack = null;
// classid is signed int and do not have flags feature.
mCurrentEnum.mCanUnsigned = false;
mCurrentEnum.mUseFlags = false;
// update self
mCurrentEnum.updateByEntries();
// we forcely set classid is signed and do not have flags feature.
mCurrentEnum.mIsFlag = false;
mCurrentEnum.mIsUnsigned = false;
// and return
mResult = mCurrentEnum;
mCurrentEnum = null;
}
@@ -90,6 +94,11 @@ public class ClassidWalker extends CKDefinesParserBaseListener {
mCurrentEntry.mEntryName = ctx.CKGENERIC_ID(0).getText();
mCurrentEntry.mEntryValue = ctx.CKGENERIC_NUM().getText();
// All classid number is positive.
mCurrentEntry.mEntrySignKind = EnumsHelper.BEnumEntrySignKind.Positive;
// And all in ordinary number style so it doesn't have flag feature.
mCurrentEntry.mEntryFlagKind = EnumsHelper.BEnumEntryFlagKind.NotFlag;
// fill entry level info
int this_level = getClassidLevel(ctx.getStart());
if (this_level > mLevel) {

View File

@@ -30,6 +30,9 @@ public class DefinesWalker extends CKDefinesParserBaseListener {
@Override
public void exitProg(CKDefinesParser.ProgContext ctx) {
// update enum
mCurrentEnum.updateByEntries();
// and return
mResult = mCurrentEnum;
mCurrentEnum = null;
}
@@ -48,19 +51,26 @@ public class DefinesWalker extends CKDefinesParserBaseListener {
if (ctx.CKGENERIC_NUM() == null) {
// define with id
mCurrentEntry.mEntryValue = ctx.CKGENERIC_ID(1).getText();
// it refers other memeber, so its sign is unknown
mCurrentEntry.mEntrySignKind = EnumsHelper.BEnumEntrySignKind.Unknown;
// it refers other memeber, so it may flag.
mCurrentEntry.mEntryFlagKind = EnumsHelper.BEnumEntryFlagKind.MayFlag;
} else {
// define with number
String num = ctx.CKGENERIC_NUM().getText();
mCurrentEntry.mEntryValue = num;
// check whether this enum can be unsigned
// check the sign of this number
if (CommonHelper.isNegativeNumber(num)) {
mCurrentEnum.mCanUnsigned = false;
mCurrentEntry.mEntrySignKind = EnumsHelper.BEnumEntrySignKind.Negative;
} else {
mCurrentEntry.mEntrySignKind = EnumsHelper.BEnumEntrySignKind.Positive;
}
// if the number is in hex form, this enum MIGHT have flags feature
// if the number is in hex form, it may belong to flag enum
if (CommonHelper.isHexNumber(num)) {
mCurrentEnum.mUseFlags = true;
mCurrentEntry.mEntryFlagKind = EnumsHelper.BEnumEntryFlagKind.MayFlag;
} else {
mCurrentEntry.mEntryFlagKind = EnumsHelper.BEnumEntryFlagKind.NotFlag;
}
}

View File

@@ -1,6 +1,45 @@
import java.util.Vector;
public class EnumsHelper {
/**
* The kind of enum entry value.
* This kind indicates whether this enum entry belong to a flag enum.
*/
public enum BEnumEntryFlagKind {
/**
* This enum entry can not belong to a flag enum.
* Because its value is ordinary.
*/
NotFlag,
/**
* This enum entry may belong to a flag enum.
* Because its value is in HEX format, and refering other members.
*/
MayFlag,
/**
* This enum entry must belong to a flag enum.
* Because its value use bitwise operation.
*/
MustFlag,
}
/**
* The kind of enum entry value.
* This kind indicates the sign of this enum entry value.
*/
public enum BEnumEntrySignKind {
/** The value of this enum entry is positive number or zero. */
Positive,
/** The value of this enum entry is negative number. */
Negative,
/**
* The value of this enum entry is unknown.
* This is may be caused by that it refer other memeber.
*/
Unknown,
}
/**
* The struct to describe the entry of an enum.
*/
@@ -8,6 +47,8 @@ public class EnumsHelper {
public BEnumEntry() {
mEntryName = null;
mEntryValue = null;
mEntryFlagKind = null;
mEntrySignKind = null;
mEntryComment = null;
}
@@ -15,6 +56,10 @@ public class EnumsHelper {
public String mEntryName;
/** The value of this entry. null if this entry do not have explicit value. */
public String mEntryValue;
/** The flag kind of this entry value. */
public BEnumEntryFlagKind mEntryFlagKind;
/** The sign kind of this entry value. */
public BEnumEntrySignKind mEntrySignKind;
/** The comment of this entry. null if no comment. */
public String mEntryComment;
}
@@ -44,8 +89,8 @@ public class EnumsHelper {
public BEnum() {
mEnumName = null;
mEnumComment = null;
mCanUnsigned = true;
mUseFlags = false;
mIsUnsigned = true;
mIsFlag = false;
mEntries = new Vector<BEnumEntry>();
}
@@ -53,12 +98,48 @@ public class EnumsHelper {
public String mEnumName;
/** The comment of this enum. null if no comment. */
public String mEnumComment;
/** True if this enum can use unsigned integer as its underlying type. */
public boolean mCanUnsigned;
/** True if this enum will use flags feature (supporting OR, AND, operators). */
public boolean mUseFlags;
/** True if this enum should use unsigned integer as its underlying type, otherwise false. */
public boolean mIsUnsigned;
/** True if this enum shoule have flags feature (supporting OR, AND, operators), otherwise false. */
public boolean mIsFlag;
/** The list to store entries of this enum. */
public Vector<BEnumEntry> mEntries;
/**
* Update some properties located in this class according to existing entries.
*/
public void updateByEntries() {
// If there is at least one negative entry, the enum should be signed,
// Otherwise, it is unsigned.
// For unknown entries, ignore them.
boolean has_negative = false;
for (BEnumEntry entry : this.mEntries) {
if (entry.mEntrySignKind == BEnumEntrySignKind.Negative) {
has_negative = true;
}
}
this.mIsUnsigned = !has_negative;
// For flag kind, if there is "Must Flag" entry, the enum should be a flag enum.
// Then, if "May Flag" entry is more than "Not Flag", the enum would be a flag enum.
// Otherwise, it is not flag.
boolean has_must_flag = false;
int cnt_may_flag = 0, cnt_not_flag = 0;
for (BEnumEntry entry : this.mEntries) {
switch (entry.mEntryFlagKind) {
case NotFlag -> ++cnt_not_flag;
case MayFlag -> ++cnt_may_flag;
case MustFlag -> has_must_flag = true;
}
}
if (has_must_flag) {
this.mIsFlag = true;
} else if (cnt_may_flag > cnt_not_flag) {
this.mIsFlag = true;
} else {
this.mIsFlag = false;
}
}
}
/**

View File

@@ -59,6 +59,8 @@ public class EnumsWalker extends CKEnumsParserBaseListener {
List<TerminalNode> allNames = ctx.CKGENERIC_ID();
mCurrentEnum.mEnumName = allNames.get(allNames.size() - 1).getText();
// update self and add into list
mCurrentEnum.updateByEntries();
mCurrentProg.mEnums.add(mCurrentEnum);
mCurrentEnum = null;
}
@@ -75,6 +77,14 @@ public class EnumsWalker extends CKEnumsParserBaseListener {
// get entry name
mCurrentEntry.mEntryName = ctx.CKGENERIC_ID().getText();
// if its value is null, we manually fill 2 kinds
if (mCurrentEntry.mEntryValue == null) {
// the sign kind is unknown because it relys on other value (+1)
mCurrentEntry.mEntrySignKind = EnumsHelper.BEnumEntrySignKind.Unknown;
// because it just adds one from previous member, it should not belong to a flag enum
mCurrentEntry.mEntryFlagKind = EnumsHelper.BEnumEntryFlagKind.NotFlag;
}
mCurrentEnum.mEntries.add(mCurrentEntry);
mCurrentEntry = null;
}
@@ -85,34 +95,42 @@ public class EnumsWalker extends CKEnumsParserBaseListener {
List<TerminalNode> nums = ctx.CKGENERIC_NUM();
switch (nums.size()) {
case 1: {
// set value
TerminalNode node = nums.get(0);
mCurrentEntry.mEntryValue = node.getText();
case 1: {
// value is immediate number
TerminalNode node = nums.get(0);
String num = node.getText();
mCurrentEntry.mEntryValue = num;
// check whether this enum can be unsigned
if (CommonHelper.isNegativeNumber(node.getText())) {
mCurrentEnum.mCanUnsigned = false;
// check whether this enum can be unsigned
if (CommonHelper.isNegativeNumber(num)) {
mCurrentEntry.mEntrySignKind = EnumsHelper.BEnumEntrySignKind.Negative;
} else {
mCurrentEntry.mEntrySignKind = EnumsHelper.BEnumEntrySignKind.Positive;
}
// if the number is in hex form, this entry may belong to flag enum
if (CommonHelper.isHexNumber(num)) {
mCurrentEntry.mEntryFlagKind = EnumsHelper.BEnumEntryFlagKind.MayFlag;
} else {
mCurrentEntry.mEntryFlagKind = EnumsHelper.BEnumEntryFlagKind.NotFlag;
}
break;
}
// if the number is in hex form, this enum MIGHT have flags feature
if (CommonHelper.isHexNumber(node.getText())) {
mCurrentEnum.mUseFlags = true;
case 2: {
// value is bitwise operation
TerminalNode num = nums.get(0), offset = nums.get(1);
mCurrentEntry.mEntryValue = String.format("%s << %s", num.getText(), offset.getText());
// << operator appears.
// it shoud be unsigned.
mCurrentEntry.mEntrySignKind = EnumsHelper.BEnumEntrySignKind.Positive;
// and it must belong to flag enum
mCurrentEntry.mEntryFlagKind = EnumsHelper.BEnumEntryFlagKind.MustFlag;
break;
}
break;
}
case 2: {
// set value
TerminalNode num = nums.get(0), offset = nums.get(1);
mCurrentEntry.mEntryValue = String.format("%s << %s", num.getText(), offset.getText());
// << operator appears. this enum must have flags feature
mCurrentEnum.mUseFlags = true;
break;
}
default:
throw new IllegalArgumentException("Unexpected value: " + nums.size());
default:
throw new IllegalArgumentException("Unexpected value: " + nums.size());
}
}
@@ -123,9 +141,19 @@ public class EnumsWalker extends CKEnumsParserBaseListener {
mCurrentEntry.mEntryValue = ctx.CKGENERIC_ID().stream().map(value -> value.getText())
.collect(Collectors.joining(" | "));
// | operator appears. this enum must have flags feature
mCurrentEnum.mUseFlags = true;
if (ctx.CKGENERIC_ID().size() > 1) {
// If there is more than one ID, it means | operator appears.
// It should be unsigned.
mCurrentEntry.mEntrySignKind = EnumsHelper.BEnumEntrySignKind.Positive;
// And it must belong to flag enum.
mCurrentEntry.mEntryFlagKind = EnumsHelper.BEnumEntryFlagKind.MustFlag;
} else {
// Otherwise it just refer other member.
// The sign of its value is unclear.
mCurrentEntry.mEntrySignKind = EnumsHelper.BEnumEntrySignKind.Unknown;
// And it may belong to flag enum because it refers other memeber.
mCurrentEntry.mEntryFlagKind = EnumsHelper.BEnumEntryFlagKind.MayFlag;
}
}
}

View File

@@ -6,10 +6,28 @@ import com.google.gson.GsonBuilder;
public class JsonWriter {
private static String writeBEnumEntryFlagKind(EnumsHelper.BEnumEntryFlagKind kind) {
return switch (kind) {
case NotFlag -> "not-flag";
case MayFlag -> "may-flag";
case MustFlag -> "must-flag";
};
}
private static String writeBEnumEntrySignKind(EnumsHelper.BEnumEntrySignKind kind) {
return switch (kind) {
case Positive -> "positive";
case Negative -> "negative";
case Unknown -> "unknown";
};
}
private static JsonObject writeBEnumEntry(EnumsHelper.BEnumEntry enumEntry) {
JsonObject data = new JsonObject();
data.addProperty("name", enumEntry.mEntryName);
data.addProperty("value", enumEntry.mEntryValue);
data.addProperty("flag_kind", writeBEnumEntryFlagKind(enumEntry.mEntryFlagKind));
data.addProperty("sign_kind", writeBEnumEntrySignKind(enumEntry.mEntrySignKind));
data.addProperty("comment", enumEntry.mEntryComment);
// Export hierarchy if possible
@@ -30,9 +48,8 @@ public class JsonWriter {
JsonObject data = new JsonObject();
data.addProperty("name", benum.mEnumName);
data.addProperty("comment", benum.mEnumComment);
data.addProperty("can_unsigned", benum.mCanUnsigned);
data.addProperty("use_flags", benum.mUseFlags);
data.addProperty("use_flags", benum.mUseFlags);
data.addProperty("is_unsigned", benum.mIsUnsigned);
data.addProperty("is_flag", benum.mIsFlag);
JsonArray entries = new JsonArray();
for (EnumsHelper.BEnumEntry enumEntry : benum.mEntries) {

View File

@@ -1,6 +1,47 @@
import json
import typing
import utils
import enum
class BEnumEntryFlagKind(enum.StrEnum):
"""
The kind of enum entry value.
This kind indicates whether this enum entry belong to a flag enum.
"""
NotFlag = "not-flag"
"""
This enum entry can not belong to a flag enum.
Because its value is ordinary.
"""
MayFlag = "may-flag"
"""
This enum entry may belong to a flag enum.
Because its value is in HEX format, and refering other members.
"""
MustFlag = "must-flag"
"""
This enum entry must belong to a flag enum.
Because its value use bitwise operation.
"""
class BEnumEntrySignKind(enum.StrEnum):
"""
The kind of enum entry value.
This kind indicates the sign of this enum entry value.
"""
Positive = "positive"
"""The value of this enum entry is positive number or zero."""
Negative = "negative"
"""he value of this enum entry is negative number."""
Unknown = "unknown"
"""
The value of this enum entry is unknown.
This is may be caused by that it refer other memeber.
"""
class BEnumEntry:
@@ -10,14 +51,25 @@ class BEnumEntry:
"""The name of this entry."""
__entry_value: str | None
"""The value of this entry. None if this entry do not have explicit value."""
__entry_flag_kind: BEnumEntryFlagKind
"""The flag kind of this entry value."""
__entry_sign_kind: BEnumEntrySignKind
"""The sign kind of this entry value."""
__entry_comment: str | None
"""The comment of this entry. None if no comment."""
def __init__(
self, entry_name: str, entry_value: str | None, entry_comment: str | None
self,
entry_name: str,
entry_value: str | None,
entry_flag_kind: BEnumEntryFlagKind,
entry_sign_kind: BEnumEntrySignKind,
entry_comment: str | None,
):
self.__entry_name = entry_name
self.__entry_value = entry_value
self.__entry_flag_kind = entry_flag_kind
self.__entry_sign_kind = entry_sign_kind
self.__entry_comment = entry_comment
def get_entry_name(self) -> str:
@@ -37,6 +89,8 @@ class BEnumEntry:
return BEnumEntry(
data["name"],
data.get("value", None),
BEnumEntryFlagKind(data.get("flag_kind")),
BEnumEntrySignKind(data.get("sign_kind")),
data.get("comment", None),
)
@@ -58,10 +112,12 @@ class BHierarchyEnumEntry(BEnumEntry):
self,
entry_name: str,
entry_value: str | None,
entry_flag_kind: BEnumEntryFlagKind,
entry_sign_kind: BEnumEntrySignKind,
entry_comment: str | None,
hierarchy: list[str],
):
super().__init__(entry_name, entry_value, entry_comment)
super().__init__(entry_name, entry_value, entry_flag_kind, entry_sign_kind, entry_comment)
self.__hierarchy = hierarchy
def iter_hierarchy(self, benum: "BEnum") -> typing.Iterator["BHierarchyEnumEntry"]:
@@ -75,6 +131,8 @@ class BHierarchyEnumEntry(BEnumEntry):
return BHierarchyEnumEntry(
data["name"],
data.get("value", None),
BEnumEntryFlagKind(data.get("flag_kind")),
BEnumEntrySignKind(data.get("sign_kind")),
data.get("comment", None),
data["hierarchy"],
)
@@ -87,9 +145,9 @@ class BEnum:
"""The name of this enum."""
__enum_comment: str | None
"""The comment of this enum. None if no comment."""
__can_unsigned: bool
__is_unsigned: bool
"""True if this enum can use unsigned integer as its underlying type."""
__use_flags: bool
__is_flag: bool
"""True if this enum will use flags feature (supporting OR, AND, operators)."""
__entries: list[BEnumEntry]
"""The list to store entries of this enum."""
@@ -101,14 +159,14 @@ class BEnum:
self,
enum_name: str,
enum_comment: str | None,
can_unsigned: bool,
use_flags: bool,
is_unsigned: bool,
is_flag: bool,
entries: list[BEnumEntry],
):
self.__enum_name = enum_name
self.__enum_comment = enum_comment
self.__can_unsigned = can_unsigned
self.__use_flags = use_flags
self.__is_unsigned = is_unsigned
self.__is_flag = is_flag
self.__entries = entries
self.__entries_map = {e.get_entry_name(): e for e in entries}
@@ -120,13 +178,13 @@ class BEnum:
"""Get the comment of this enum. None if no comment."""
return self.__enum_comment
def get_can_unsigned(self) -> bool:
def is_unsigned(self) -> bool:
"""True if this enum can use unsigned integer as its underlying type."""
return self.__can_unsigned
return self.__is_unsigned
def get_use_flags(self) -> bool:
def is_flag(self) -> bool:
"""True if this enum will use flags feature (supporting OR, AND, operators)."""
return self.__use_flags
return self.__is_flag
def iter_entries(self) -> typing.Iterator[BEnumEntry]:
"""Get the iterator of entries of this enum."""
@@ -140,8 +198,8 @@ class BEnum:
return BEnum(
data["name"],
data.get("comment", None),
data["can_unsigned"],
data["use_flags"],
data["is_unsigned"],
data["is_flag"],
list(map(lambda i: BEnum.__create_entry_by_content(i), data["entries"])),
)

View File

@@ -11,6 +11,7 @@ def main():
render.render_cpp_enum("CKERROR.hpp", ckerror)
render.render_py_enum("CKERROR.py", ckerror)
render.render_cs_enum("CKERROR.cs", ckerror)
render.render_rs_enum("CKERROR.rs", ckerror)
render.render_cpp_ckerror_docstring("CKERROR.docstring.hpp", "CKERROR.docstring.cpp", ckerror)
render.render_py_enum_docstring("CKERROR.docstring.py", ckerror)
render.render_cs_enum_docstring("CKERROR.docstring.cs", ckerror)

View File

@@ -65,6 +65,43 @@ class RenderUtils:
"""
return RenderUtils.REGEX_PY_TO_LITERAL_NUMBER.sub("", numstr, 1)
REGEX_CS_TO_LITERAL_NUMBER: typing.ClassVar[re.Pattern] = re.compile("[lL]+$")
@staticmethod
def to_cs_num_literal(numstr: str) -> str:
"""
Convert given string into C# number literal style.
Number literal declaration in C# is slightly different with C#.
C# support U but do not support L.
So this function actually just remove "L" suffix.
This function is only served for C# code generation.
:param numstr: The captured number.
:return: The C# style number string.
"""
return RenderUtils.REGEX_CS_TO_LITERAL_NUMBER.sub("", numstr, 1)
@staticmethod
def to_rs_num_literal(numstr: str) -> str:
"""
Convert given string into Rust number literal style.
Number literal declaration in Rust is slightly different with C++.
C++ support U and L but Rust use another complete suffix mode to decide the type of numeric literal (u32, i32 and etc).
However, Rust can properly deduce the correct type of number literal,
so we just need simply remove any suffix.
This function is only served for C# code generation.
:param numstr: The captured number.
:return: The Rust style number string.
"""
# We reuse existing function
return RenderUtils.to_py_num_literal(numstr)
REGEX_PY_EXT_HUMANRDABLE_ENTRY_NAME: typing.ClassVar[re.Pattern] = re.compile("^[a-zA-Z0-9]+_")
@staticmethod

View File

@@ -1,11 +1,16 @@
{%- for benum in payload.iter_enums() %}
{%- if benum.get_enum_comment() is not none %}
{{ benum.get_enum_comment() | block_comment('/// ') }}
{%- endif %} {%- if benum.get_use_flags() %}
{%- endif %} {%- if benum.is_flag() %}
[Flags]{%- endif %}
public enum {{ benum.get_enum_name() }} : {% if benum.get_can_unsigned() -%} uint {%- else -%} int {%- endif %} {
public enum {{ benum.get_enum_name() }} : {% if benum.is_unsigned() -%} uint {%- else -%} int {%- endif %} {
{%- for entry in benum.iter_entries() %}
{{ entry.get_entry_name() }} {%- if entry.get_entry_value() is not none %} = {{ entry.get_entry_value() }} {%- endif %}, {%- if entry.get_entry_comment() is not none %} /// {{ entry.get_entry_comment() | line_comment }} {%- endif %}
{%- if entry.get_entry_comment() is not none %}
/// <summary>
/// {{ entry.get_entry_comment() | line_comment }}
/// </summary>
{%- endif %}
{{ entry.get_entry_name() }} {%- if entry.get_entry_value() is not none %} = {{ utils.to_cs_num_literal(entry.get_entry_value()) }} {%- endif %},
{%- endfor %}
};
{%- endfor %}

View File

@@ -4,7 +4,7 @@
{{ benum.get_enum_comment() | block_comment(' * ') }}
*/
{%- endif %}
enum class {{ benum.get_enum_name() }} : {% if benum.get_can_unsigned() -%} CKDWORD {%- else -%} CKINT {%- endif %} {
enum class {{ benum.get_enum_name() }} : {% if benum.is_unsigned() -%} CKDWORD {%- else -%} CKINT {%- endif %} {
{%- for entry in benum.iter_entries() %}
{{ entry.get_entry_name() }} {%- if entry.get_entry_value() is not none %} = {{ entry.get_entry_value() }} {%- endif %}, {%- if entry.get_entry_comment() is not none %} /**< {{ entry.get_entry_comment() | line_comment }} */ {%- endif %}
{%- endfor %}

View File

@@ -0,0 +1,37 @@
{%- for benum in payload.iter_enums() %}
{%- if benum.get_enum_comment() is not none %}
{{ benum.get_enum_comment() | block_comment('/// ') }}
{%- endif %}
{%- if not benum.is_flag() %}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr({% if benum.is_unsigned() -%} u32 {%- else -%} i32 {%- endif %})]
#[non_exhaustive]
#[rustfmt::skip]
#[allow(non_camel_case_types)]
pub enum {{ benum.get_enum_name() }} {
{%- for entry in benum.iter_entries() %}
{%- if entry.get_entry_comment() is not none %}
/// {{ entry.get_entry_comment() | line_comment }}
{%- endif %}
{{ entry.get_entry_name() }} {%- if entry.get_entry_value() is not none %} = {{ utils.to_py_num_literal(entry.get_entry_value()) }} {%- endif %},
{%- endfor %}
}
{%- else %}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(transparent)]
#[rustfmt::skip]
#[allow(non_camel_case_types)]
pub struct {{ benum.get_enum_name() }}({% if benum.is_unsigned() -%} u32 {%- else -%} i32 {%- endif %});
bitflags! {
impl {{ benum.get_enum_name() }}: {% if benum.is_unsigned() -%} u32 {%- else -%} i32 {%- endif %} {
{%- for entry in benum.iter_entries() %}
{%- if entry.get_entry_comment() is not none %}
/// {{ entry.get_entry_comment() | line_comment }}
{%- endif %}
const {{ entry.get_entry_name() }} {%- if entry.get_entry_value() is not none %} = {{ utils.to_py_num_literal(entry.get_entry_value()) }} {%- endif %};
{%- endfor %}
}
}
{%- endif %}
{%- endfor %}

View File

@@ -1107,7 +1107,7 @@ bool BMCamera_SetFrontPlane(BMPARAM_OBJECT_DECL(bmfile, objid), BMPARAM_IN(LibCm
bool BMCamera_GetBackPlane(BMPARAM_OBJECT_DECL(bmfile, objid), BMPARAM_OUT(LibCmo::CKFLOAT, out_val)) {
auto obj = CheckCKCamera(bmfile, objid);
if (obj == nullptr) return false;
BMPARAM_OUT_ASSIGN(out_val, obj->GetFrontPlane());
BMPARAM_OUT_ASSIGN(out_val, obj->GetBackPlane());
return true;
}
bool BMCamera_SetBackPlane(BMPARAM_OBJECT_DECL(bmfile, objid), BMPARAM_IN(LibCmo::CKFLOAT, val)) {
@@ -1119,7 +1119,7 @@ bool BMCamera_SetBackPlane(BMPARAM_OBJECT_DECL(bmfile, objid), BMPARAM_IN(LibCmo
bool BMCamera_GetFov(BMPARAM_OBJECT_DECL(bmfile, objid), BMPARAM_OUT(LibCmo::CKFLOAT, out_val)) {
auto obj = CheckCKCamera(bmfile, objid);
if (obj == nullptr) return false;
BMPARAM_OUT_ASSIGN(out_val, obj->GetFrontPlane());
BMPARAM_OUT_ASSIGN(out_val, obj->GetFov());
return true;
}
bool BMCamera_SetFov(BMPARAM_OBJECT_DECL(bmfile, objid), BMPARAM_IN(LibCmo::CKFLOAT, val)) {

View File

@@ -178,13 +178,15 @@ namespace BMap {
// BMFile only provide limited type visiting, we must make sure it provided ID also is existed in out stored list.
// so we check its type here. if type is not matched, we reset it to nullptr.
if (obj != nullptr) {
using LibCmo::CK2::CK_CLASSID;
switch (obj->GetClassID()) {
case LibCmo::CK2::CK_CLASSID::CKCID_GROUP:
case LibCmo::CK2::CK_CLASSID::CKCID_3DOBJECT:
case LibCmo::CK2::CK_CLASSID::CKCID_MESH:
case LibCmo::CK2::CK_CLASSID::CKCID_MATERIAL:
case LibCmo::CK2::CK_CLASSID::CKCID_TEXTURE:
case LibCmo::CK2::CK_CLASSID::CKCID_TARGETLIGHT:
case CK_CLASSID::CKCID_GROUP:
case CK_CLASSID::CKCID_3DOBJECT:
case CK_CLASSID::CKCID_MESH:
case CK_CLASSID::CKCID_MATERIAL:
case CK_CLASSID::CKCID_TEXTURE:
case CK_CLASSID::CKCID_TARGETLIGHT:
case CK_CLASSID::CKCID_TARGETCAMERA:
break; // okey. do nothing
default:
// this object should not be exposed to outside, reset it to nullptr

View File

@@ -31,6 +31,8 @@ target_compile_definitions(BMap
PRIVATE
BMAP_EXPORTING
)
# Remove any possible prefix (such as `lib` on Linux)
set_target_properties(BMap PROPERTIES PREFIX "")
# Install binary and headers
install(TARGETS BMap

View File

@@ -5,10 +5,11 @@
#include "Rule.hpp"
#include <VTAll.hpp>
#include <yycc.hpp>
#include <yycc/carton/termcolor.hpp>
#include <yycc/string/op.hpp>
#include <yycc/patch/stream.hpp>
#include <yycc/windows/console.hpp>
#include <yycc/carton/termcolor.hpp>
#include <yycc/carton/ironpad.hpp>
#include <iostream>
#include <optional>
@@ -101,14 +102,16 @@ static void CheckRules(BMapInspector::Cli::Args& args, BMapInspector::Map::Level
BMapInspector::Reporter::Reporter reporter;
// Get rule collection
BMapInspector::Rule::Ruleset ruleset;
BMapInspector::Rule::RuleCollection rule_collection;
// Show rule infos
std::cout << strop::printf(u8"Total %" PRIuSIZET " rule(s) are loaded.", ruleset.GetRuleCount()) << std::endl
std::cout << strop::printf(u8"Total %" PRIuSIZET " rule(s) are loaded.", rule_collection.GetRuleCount()) << std::endl
<< u8"Check may take few minutes. Please do not close this console..." << std::endl;
// Check rules one by one
for (auto* rule : ruleset.GetRules()) {
for (auto* rule : rule_collection.GetRules()) {
reporter.EnterRule(rule->GetRuleName());
rule->Check(reporter, level);
reporter.LeaveRule();
}
// Show report conclusion

View File

@@ -11,15 +11,18 @@ PRIVATE
Map.cpp
Rule.cpp
# Rules
Rule/Shared.cpp
Rule/GpRules.cpp
Rule/ChirsRules.cpp
Rule/YYCRules.cpp
Rule/ZZQRules.cpp
Rule/BBugRules.cpp
Rule/SOneRules.cpp
Rule/SSBRules.cpp
Rule/LXRules.cpp
Ruleset/Shared/Utility.cpp
Ruleset/Shared/Name.cpp
Ruleset/Shared/Sector.cpp
Ruleset/Shared/DupCmp.cpp
Ruleset/GpRules.cpp
Ruleset/ChirsRules.cpp
Ruleset/YYCRules.cpp
Ruleset/ZZQRules.cpp
Ruleset/BBugRules.cpp
Ruleset/SOneRules.cpp
Ruleset/SSBRules.cpp
Ruleset/LXRules.cpp
)
# Setup headers
target_sources(BMapInspector
@@ -33,15 +36,18 @@ FILES
Map.hpp
Rule.hpp
# Rules
Rule/Shared.hpp
Rule/GpRules.hpp
Rule/ChirsRules.hpp
Rule/YYCRules.hpp
Rule/ZZQRules.hpp
Rule/BBugRules.hpp
Rule/SOneRules.hpp
Rule/SSBRules.hpp
Rule/LXRules.hpp
Ruleset/Shared/Utility.hpp
Ruleset/Shared/Name.hpp
Ruleset/Shared/Sector.hpp
Ruleset/Shared/DupCmp.hpp
Ruleset/GpRules.hpp
Ruleset/ChirsRules.hpp
Ruleset/YYCRules.hpp
Ruleset/ZZQRules.hpp
Ruleset/BBugRules.hpp
Ruleset/SOneRules.hpp
Ruleset/SSBRules.hpp
Ruleset/LXRules.hpp
)
# Setup header infomation
target_include_directories(BMapInspector

View File

@@ -1,54 +1,70 @@
#include "Reporter.hpp"
#include <yycc/string/op.hpp>
#include <cstdarg>
#include <stdexcept>
using BMapInspector::Utils::ReportLevel;
namespace strop = yycc::string::op;
namespace BMapInspector::Reporter {
#pragma region Reporter
Reporter::Reporter() {}
Reporter::Reporter() : current_rule(std::nullopt), reports() {}
Reporter::~Reporter() {}
void Reporter::AddReport(Utils::ReportLevel level, const std::u8string_view &rule, const std::u8string_view &content) {
this->reports.emplace_back(Report{
.level = level,
.rule = std::u8string(rule),
.content = std::u8string(content),
});
void Reporter::EnterRule(const std::u8string_view &rule) {
if (this->current_rule.has_value()) throw std::logic_error("can not enter rule multiple times");
else this->current_rule = std::u8string(rule);
}
void Reporter::WriteInfo(const std::u8string_view &rule, const std::u8string_view &content) {
this->AddReport(Utils::ReportLevel::Info, rule, content);
void Reporter::LeaveRule() {
if (this->current_rule.has_value()) this->current_rule = std::nullopt;
else throw std::logic_error("can not leave rule without any existing rule");
}
void Reporter::FormatInfo(const std::u8string_view &rule, const char8_t *fmt, ...) {
void Reporter::AddReport(ReportLevel level, const std::u8string_view &content) {
if (this->current_rule.has_value()) {
this->reports.emplace_back(Report{
.level = level,
.rule = std::u8string(this->current_rule.value()),
.content = std::u8string(content),
});
} else {
throw std::logic_error("can not add report without any rule scope");
}
}
void Reporter::WriteInfo(const std::u8string_view &content) {
this->AddReport(ReportLevel::Info, content);
}
void Reporter::FormatInfo(const char8_t *fmt, ...) {
va_list argptr;
va_start(argptr, fmt);
this->WriteInfo(rule, strop::vprintf(fmt, argptr));
this->WriteInfo(strop::vprintf(fmt, argptr));
va_end(argptr);
}
void Reporter::WriteWarning(const std::u8string_view &rule, const std::u8string_view &content) {
this->AddReport(Utils::ReportLevel::Warning, rule, content);
void Reporter::WriteWarning(const std::u8string_view &content) {
this->AddReport(ReportLevel::Warning, content);
}
void Reporter::FormatWarning(const std::u8string_view &rule, const char8_t *fmt, ...) {
void Reporter::FormatWarning(const char8_t *fmt, ...) {
va_list argptr;
va_start(argptr, fmt);
this->WriteWarning(rule, strop::vprintf(fmt, argptr));
this->WriteWarning(strop::vprintf(fmt, argptr));
va_end(argptr);
}
void Reporter::WriteError(const std::u8string_view &rule, const std::u8string_view &content) {
this->AddReport(Utils::ReportLevel::Error, rule, content);
void Reporter::WriteError(const std::u8string_view &content) {
this->AddReport(ReportLevel::Error, content);
}
void Reporter::FormatError(const std::u8string_view &rule, const char8_t *fmt, ...) {
void Reporter::FormatError(const char8_t *fmt, ...) {
va_list argptr;
va_start(argptr, fmt);
this->WriteError(rule, strop::vprintf(fmt, argptr));
this->WriteError(strop::vprintf(fmt, argptr));
va_end(argptr);
}
@@ -56,13 +72,13 @@ namespace BMapInspector::Reporter {
ReporterDigest digest{.cnt_err = 0, .cnt_warn = 0, .cnt_info = 0};
for (const auto &report : this->reports) {
switch (report.level) {
case Utils::ReportLevel::Error:
case ReportLevel::Error:
++digest.cnt_err;
break;
case Utils::ReportLevel::Warning:
case ReportLevel::Warning:
++digest.cnt_warn;
break;
case Utils::ReportLevel::Info:
case ReportLevel::Info:
++digest.cnt_info;
break;
}

View File

@@ -5,6 +5,7 @@
#include <string>
#include <string_view>
#include <vector>
#include <optional>
namespace BMapInspector::Reporter {
@@ -26,22 +27,27 @@ namespace BMapInspector::Reporter {
~Reporter();
YYCC_DEFAULT_COPY_MOVE(Reporter)
public:
void EnterRule(const std::u8string_view& rule);
void LeaveRule();
private:
void AddReport(Utils::ReportLevel level, const std::u8string_view& rule, const std::u8string_view& content);
void AddReport(Utils::ReportLevel level, const std::u8string_view& content);
public:
void WriteInfo(const std::u8string_view& rule, const std::u8string_view& content);
void FormatInfo(const std::u8string_view& rule, const char8_t* fmt, ...);
void WriteWarning(const std::u8string_view& rule, const std::u8string_view& content);
void FormatWarning(const std::u8string_view& rule, const char8_t* fmt, ...);
void WriteError(const std::u8string_view& rule, const std::u8string_view& content);
void FormatError(const std::u8string_view& rule, const char8_t* fmt, ...);
void WriteInfo(const std::u8string_view& content);
void FormatInfo(const char8_t* fmt, ...);
void WriteWarning(const std::u8string_view& content);
void FormatWarning(const char8_t* fmt, ...);
void WriteError(const std::u8string_view& content);
void FormatError(const char8_t* fmt, ...);
public:
ReporterDigest GetDigest() const;
const std::vector<Report>& GetReports() const;
private:
std::optional<std::u8string> current_rule;
std::vector<Report> reports;
};

View File

@@ -1,13 +1,13 @@
#include "Rule.hpp"
#include "Rule/GpRules.hpp"
#include "Rule/ChirsRules.hpp"
#include "Rule/YYCRules.hpp"
#include "Rule/BBugRules.hpp"
#include "Rule/ZZQRules.hpp"
#include "Rule/SOneRules.hpp"
#include "Rule/SSBRules.hpp"
#include "Rule/LXRules.hpp"
#include "Ruleset/GpRules.hpp"
#include "Ruleset/ChirsRules.hpp"
#include "Ruleset/YYCRules.hpp"
#include "Ruleset/BBugRules.hpp"
#include "Ruleset/ZZQRules.hpp"
#include "Ruleset/SOneRules.hpp"
#include "Ruleset/SSBRules.hpp"
#include "Ruleset/LXRules.hpp"
namespace BMapInspector::Rule {
@@ -19,38 +19,46 @@ namespace BMapInspector::Rule {
#pragma endregion
#pragma region Ruleset
#pragma region RuleCollection
Ruleset::Ruleset() : rules() {
RuleCollection::RuleCollection() : rules() {
// Add rule into list.
//rules.emplace_back(new GpRule1());
//rules.emplace_back(new GpRule2());
//rules.emplace_back(new Gp3Rule());
//rules.emplace_back(new Chirs1Rule());
rules.emplace_back(new YYCRule1());
rules.emplace_back(new YYCRule2());
rules.emplace_back(new BBugRule1());
rules.emplace_back(new SOneRule1());
rules.emplace_back(new SSBRule1());
rules.emplace_back(new LXRule1());
rules.emplace_back(new Ruleset::GpRule1());
rules.emplace_back(new Ruleset::GpRule2());
rules.emplace_back(new Ruleset::ChirsRule1());
rules.emplace_back(new Ruleset::YYCRule1());
rules.emplace_back(new Ruleset::YYCRule2());
rules.emplace_back(new Ruleset::YYCRule3());
rules.emplace_back(new Ruleset::YYCRule4());
rules.emplace_back(new Ruleset::YYCRule5());
rules.emplace_back(new Ruleset::YYCRule6());
rules.emplace_back(new Ruleset::BBugRule1());
rules.emplace_back(new Ruleset::BBugRule2());
rules.emplace_back(new Ruleset::BBugRule3());
rules.emplace_back(new Ruleset::ZZQRule1());
rules.emplace_back(new Ruleset::ZZQRule2());
rules.emplace_back(new Ruleset::ZZQRule3());
rules.emplace_back(new Ruleset::SOneRule1());
rules.emplace_back(new Ruleset::SSBRule1());
rules.emplace_back(new Ruleset::LXRule1());
// Add more rules...
}
Ruleset::~Ruleset() {
RuleCollection::~RuleCollection() {
// Free rule from list.
for (const auto* rule : this->rules) {
delete rule;
}
}
size_t Ruleset::GetRuleCount() const {
size_t RuleCollection::GetRuleCount() const {
return this->rules.size();
}
const std::vector<IRule*>& Ruleset::GetRules() const {
const std::vector<IRule*>& RuleCollection::GetRules() const {
return this->rules;
}
#pragma endregion
} // namespace BMapInspector::Ruleset
} // namespace BMapInspector::Rule

View File

@@ -10,6 +10,9 @@
namespace BMapInspector::Rule {
/**
* @brief The interface of a rule.
*/
class IRule {
public:
IRule();
@@ -21,18 +24,21 @@ namespace BMapInspector::Rule {
virtual void Check(Reporter::Reporter& reporter, Map::Level& level) const = 0;
};
class Ruleset {
/**
* @brief A collection of rules.
*/
class RuleCollection {
public:
Ruleset();
~Ruleset();
YYCC_DELETE_COPY_MOVE(Ruleset)
RuleCollection();
~RuleCollection();
YYCC_DELETE_COPY_MOVE(RuleCollection)
public:
size_t GetRuleCount() const;
const std::vector<IRule *> &GetRules() const;
const std::vector<IRule*>& GetRules() const;
private:
std::vector<IRule *> rules;
std::vector<IRule*> rules;
};
} // namespace BMapInspector::Ruleset
} // namespace BMapInspector::Rule

View File

@@ -1,30 +0,0 @@
#include "BBugRules.hpp"
#include "Shared.hpp"
namespace L = LibCmo;
namespace C = LibCmo::CK2;
namespace O = LibCmo::CK2::ObjImpls;
namespace BMapInspector::Rule {
#pragma region BBug Rule 1
constexpr char8_t BBUG1[] = u8"BBUG1";
BBugRule1::BBugRule1() : IRule() {}
BBugRule1::~BBugRule1() {}
std::u8string_view BBugRule1::GetRuleName() const {
return BBUG1;
}
void BBugRule1::Check(Reporter::Reporter& reporter, Map::Level& level) const {
if (!level.GetTargetLights().empty()) {
reporter.WriteInfo(BBUG1, u8"Using light in map is not suggested.");
}
}
#pragma endregion
} // namespace BMapInspector::Rule

View File

@@ -1,22 +0,0 @@
#pragma once
#include "../Rule.hpp"
namespace BMapInspector::Rule {
/**
* @brief BBug Rule 1
* @details
* Using light in map is not suggested.
*/
class BBugRule1 : public IRule {
public:
BBugRule1();
virtual ~BBugRule1();
YYCC_DELETE_COPY_MOVE(BBugRule1)
public:
std::u8string_view GetRuleName() const override;
void Check(Reporter::Reporter& reporter, Map::Level& level) const override;
};
}

View File

@@ -1,18 +0,0 @@
#include "ChirsRules.hpp"
namespace BMapInspector::Rule {
Chirs1Rule::Chirs1Rule() : IRule() {}
Chirs1Rule::~Chirs1Rule() {}
std::u8string_view Chirs1Rule::GetRuleName() const {
return u8"CHIRS1";
}
void Chirs1Rule::Check(Reporter::Reporter& reporter, Map::Level& level) const {
// Report error if there is some material named Laterne_Verlauf
// but its texture is not pointed to Laterne_Verlauf texture.
// Report error if some materials' texture is Laterne_Verlauf,
// but its name is not Laterne_Verlauf.
// Report error if there is multiple Laterne_Verlauf material.
}
} // namespace BMapInspector::Rule

View File

@@ -1,53 +0,0 @@
#include "GpRules.hpp"
namespace BMapInspector::Rule {
#pragma region GP1 Rule
GpRule1::GpRule1() : IRule() {}
GpRule1::~GpRule1() {}
std::u8string_view GpRule1::GetRuleName() const {
return u8"GP1";
}
void GpRule1::Check(Reporter::Reporter& reporter, Map::Level& level) const {}
#pragma endregion
#pragma region GP2 Rule
constexpr char8_t GP2[] = u8"GP2";
GpRule2::GpRule2() : IRule() {}
GpRule2::~GpRule2() {}
std::u8string_view GpRule2::GetRuleName() const {
return GP2;
}
void GpRule2::Check(Reporter::Reporter& reporter, Map::Level& level) const {
}
#pragma endregion
#pragma region GP3 Rule
//
// Gp3Rule::Gp3Rule() : IRule() {}
//
// Gp3Rule::~Gp3Rule() {}
//
// std::u8string_view Gp3Rule::GetRuleName() const {
// return u8"GP3";
// }
//
// void Gp3Rule::Check(Reporter::Reporter& reporter, Map::Level& level) const {
// // TODO: Mesh hash is not implemented.
// }
//
//#pragma endregion
} // namespace BMapInspector::Rule

View File

@@ -1,63 +0,0 @@
#pragma once
#include "../Rule.hpp"
namespace BMapInspector::Rule {
// Reference: https://tieba.baidu.com/p/3182981807
/**
* @brief Gamepiaynmo Rule 1
* @details
* The most comprehensive group checker inspired from Ballance Blender Plugin.
*/
class GpRule1 : public IRule {
public:
GpRule1();
virtual ~GpRule1();
YYCC_DELETE_COPY_MOVE(GpRule1)
public:
std::u8string_view GetRuleName() const override;
void Check(Reporter::Reporter& reporter, Map::Level& level) const override;
};
/**
* @brief Gamepiaynmo Rule 2
* @details
* Every Ballance group should not have any groups with same name.
*/
class GpRule2 : public IRule {
public:
GpRule2();
virtual ~GpRule2();
YYCC_DELETE_COPY_MOVE(GpRule2)
public:
std::u8string_view GetRuleName() const override;
void Check(Reporter::Reporter& reporter, Map::Level& level) const override;
};
///**
// * @brief Gamepiaynmo Rule 2
// * @details
// * This rule make sure that one Ballance element must be grouped into only one sector group.
// * Multiple grouping and none grouping will throw error.
// */
///**
// * @brief Gamepiaynmo Rule 3
// * @details
// * This rule make sure that all Ballance element is grouped into correct element group.
// * This rule will check the mesh of PH and guess which element it is.
// */
//class Gp3Rule : public IRule {
//public:
// Gp3Rule();
// virtual ~Gp3Rule();
// YYCC_DELETE_COPY_MOVE(Gp3Rule)
//public:
// std::u8string_view GetRuleName() const override;
// void Check(Reporter::Reporter& reporter, Map::Level& level) const override;
//};
}

View File

@@ -1,39 +0,0 @@
#include "SOneRules.hpp"
#include "Shared.hpp"
namespace L = LibCmo;
namespace C = LibCmo::CK2;
namespace O = LibCmo::CK2::ObjImpls;
namespace BMapInspector::Rule {
#pragma region SOne Rule 1
constexpr char8_t SONE1[] = u8"SONE1";
SOneRule1::SOneRule1() : IRule() {}
SOneRule1::~SOneRule1() {}
std::u8string_view SOneRule1::GetRuleName() const {
return SONE1;
}
void SOneRule1::Check(Reporter::Reporter& reporter, Map::Level& level) const {
auto* ctx = level.GetCKContext();
auto physicalized_3dobjects = Shared::FetchPhysicalized3dObjects(ctx);
for (auto* physicalized_3dobject : physicalized_3dobjects) {
auto* mesh = physicalized_3dobject->GetCurrentMesh();
if (mesh == nullptr) {
reporter.FormatError(
SONE1,
u8R"(Object "%s" is grouped into physicalization group, but it doesn't have any associated mesh. This will cause itself and following objects can not be physicalized.)",
Shared::RenderObjectName(physicalized_3dobject));
}
}
}
#pragma endregion
} // namespace BMapInspector::Rule

View File

@@ -1,110 +0,0 @@
#pragma once
#include <VTAll.hpp>
#include <vector>
#include <array>
namespace BMapInspector::Rule::Shared {
namespace L = LibCmo;
namespace C = LibCmo::CK2;
namespace O = LibCmo::CK2::ObjImpls;
#pragma region Constant Values
namespace GroupNames {
// clang-format off
constexpr char8_t PHYS_FLOORS[] = u8"Phys_Floors";
constexpr char8_t PHYS_FLOORRAILS[] = u8"Phys_FloorRails";
constexpr char8_t PHYS_FLOORSTOPPER[] = u8"Phys_FloorStopper";
constexpr std::array ALL_PH{
u8"P_Extra_Life",
u8"P_Extra_Point",
u8"P_Trafo_Paper",
u8"P_Trafo_Stone",
u8"P_Trafo_Wood",
u8"P_Ball_Paper",
u8"P_Ball_Stone",
u8"P_Ball_Wood",
u8"P_Box",
u8"P_Dome",
u8"P_Modul_01",
u8"P_Modul_03",
u8"P_Modul_08",
u8"P_Modul_17",
u8"P_Modul_18",
u8"P_Modul_19",
u8"P_Modul_25",
u8"P_Modul_26",
u8"P_Modul_29",
u8"P_Modul_30",
u8"P_Modul_34",
u8"P_Modul_37",
u8"P_Modul_41",
u8"PS_Levelstart",
u8"PE_Levelende",
u8"PC_Checkpoints",
u8"PR_Resetpoints",
};
// clang-format on
} // namespace GroupNames
namespace TextureNames {
// clang-format off
constexpr char8_t RAIL_ENVIRONMENT[] = u8"Rail_Environment.bmp";
// clang-format on
} // namespace TextureNames
#pragma endregion
#pragma region Check Functions
/**
* @brief Check whether given 2 float point values are equal with given tolerance.
* @param lhs
* @param rhs
* @param tolerance
* @return
*/
bool FPEqual(L::CKFLOAT lhs, L::CKFLOAT rhs, L::CKFLOAT tolerance);
/**
* @brief
* @param[in] ctx Can not be nullptr.
* @param[in] name Can not be nullptr.
* @return Found pointer to CKGroup, otherwise nullptr.
*/
O::CKGroup* FetchGroup(C::CKContext* ctx, L::CKSTRING name);
std::vector<O::CK3dObject*> FetchPhysicalized3dObjects(C::CKContext* ctx);
/**
* @brief Check whether given CKTexture has the given file name (case-insensitive).
* @param[in] tex Can not be nullptr.
* @param[in] name Can not be nullptr.
* @return True if it is, otherwise false.
*/
bool CheckTextureFileName(O::CKTexture* tex, L::CKSTRING name);
/**
* @brief
* @param[in] group Can not be nullptr.
* @return All objects is the child class of CK3dEntity.
*/
std::vector<O::CK3dObject*> Iter3dObjects(O::CKGroup* group);
/**
* @brief
* @param[in] mesh Can not be nullptr.
* @return All nullptr reference are removed.
*/
std::vector<O::CKMaterial*> IterMaterial(O::CKMesh* mesh);
/**
* @brief
* @param[in] obj Can not be nullptr.
* @return
*/
const char8_t* RenderObjectName(O::CKObject* obj);
#pragma endregion
} // namespace BMapInspector::Rule::Shared

View File

@@ -1,132 +0,0 @@
#include "YYCRules.hpp"
#include "Shared.hpp"
#include <vector>
#include <set>
#include <algorithm>
namespace L = LibCmo;
namespace C = LibCmo::CK2;
namespace O = LibCmo::CK2::ObjImpls;
namespace BMapInspector::Rule {
#pragma region YYC Rule 1
constexpr char8_t YYC1[] = u8"YYC1";
YYCRule1::YYCRule1() : IRule() {}
YYCRule1::~YYCRule1() {}
std::u8string_view YYCRule1::GetRuleName() const {
return YYC1;
}
void YYCRule1::Check(Reporter::Reporter& reporter, Map::Level& level) const {
auto* ctx = level.GetCKContext();
// We get "Phys_FloorRails" group first.
auto* phys_floorrails = Shared::FetchGroup(ctx, Shared::GroupNames::PHYS_FLOORRAILS);
if (phys_floorrails == nullptr) return;
// Create container holding smooth meshes
std::set<O::CKMesh*> smooth_meshes;
// We iterate all object grouped into it.
auto group_3dobjects = Shared::Iter3dObjects(phys_floorrails);
for (auto* group_3dobject : group_3dobjects) {
// Then we iterate their current meshes
auto* mesh = group_3dobject->GetCurrentMesh();
if (mesh == nullptr) continue;
// Iterate all meshes
auto mtls = Shared::IterMaterial(mesh);
for (auto* mtl : mtls) {
// Check whether all texture referred by this mesh are "Rail_Environment".
auto texture = mtl->GetTexture();
if (texture == nullptr) continue;
if (!Shared::CheckTextureFileName(texture, Shared::TextureNames::RAIL_ENVIRONMENT)) {
// No, this is not rail texture, throw error.
reporter.FormatError(
YYC1,
u8R"(Object "%s" is grouped into Phys_FloorRails, but its texture "%s" (referred by mesh "%s" and material "%s") seems not the rail texture. This will cause some parts of this object be smooth unexpectly.)",
Shared::RenderObjectName(group_3dobject),
Shared::RenderObjectName(texture),
Shared::RenderObjectName(mesh),
Shared::RenderObjectName(mtl));
}
}
// Record this mesh into set.
smooth_meshes.emplace(mesh);
}
// Now we make sure that these smooth mesh is not referred by any other object.
// We iterate all 3d object first
auto all_3dobject = level.Get3dObjects();
for (auto* obj : all_3dobject) {
// Then we get its current mesh
auto* mesh = obj->GetCurrentMesh();
if (mesh == nullptr) continue;
// Check whether its mesh is in smooth mesh,
// and itself is not in "Phys_FloorRails" group
if (!obj->IsInGroup(phys_floorrails) && smooth_meshes.contains(mesh)) {
// Report error.
reporter.FormatError(
YYC1,
u8R"(Object "%s" is not grouped into Phys_FloorRails, but some objects grouped into Phys_FloorRails refer its mesh "%s". This will cause this object be smooth unexpectly.)",
Shared::RenderObjectName(obj),
Shared::RenderObjectName(mesh));
}
}
}
#pragma endregion
#pragma region YYC Rule 2
constexpr char8_t YYC2[] = u8"YYC2";
YYCRule2::YYCRule2() : IRule() {}
YYCRule2::~YYCRule2() {}
std::u8string_view YYCRule2::GetRuleName() const {
return YYC2;
}
void YYCRule2::Check(Reporter::Reporter& reporter, Map::Level& level) const {
auto* ctx = level.GetCKContext();
auto physicalized_3dobjects = Shared::FetchPhysicalized3dObjects(ctx);
// Iterate all physicalized 3dobject
for (auto* physicalized_3dobject : physicalized_3dobjects) {
// Get its mesh
auto* mesh = physicalized_3dobject->GetCurrentMesh();
if (mesh == nullptr) continue;
// Create a bool vector with vertex count and false init value.
std::vector<bool> used_vertex(mesh->GetVertexCount(), false);
// Iterate all face and set their vertex as used.
auto* face_indices = mesh->GetFaceIndices();
for (L::CKDWORD face_idx = 0; face_idx < mesh->GetFaceCount(); ++face_idx) {
used_vertex[face_indices[face_idx * 3]] = true;
used_vertex[face_indices[face_idx * 3 + 1]] = true;
used_vertex[face_indices[face_idx * 3 + 2]] = true;
}
// Check whether there is unused vertex
auto has_unused_vertex = std::any_of(used_vertex.begin(), used_vertex.end(), [](bool v) { return v == false; });
// If there is unused vertex, report error
if (has_unused_vertex) {
reporter.FormatError(
YYC2,
u8R"(Object "%s" is grouped into physicalization groups, and its referred mesh "%s" has isolated vertex. This will cause it can not be physicalized.)",
Shared::RenderObjectName(physicalized_3dobject),
Shared::RenderObjectName(mesh));
}
}
}
#pragma endregion
} // namespace BMapInspector::Rule

View File

@@ -1,40 +0,0 @@
#pragma once
#include "../Rule.hpp"
namespace BMapInspector::Rule {
/**
* @brief YYC12345 Rule 1
* @details
* The object grouped into "Phys_FloorRails" should only be rails, otherwise their meshes' UV will be smooth.
* Additionally, these smooth UV meshes will also affect those objects refering them.
*/
class YYCRule1 : public IRule {
public:
YYCRule1();
virtual ~YYCRule1();
YYCC_DELETE_COPY_MOVE(YYCRule1)
public:
std::u8string_view GetRuleName() const override;
void Check(Reporter::Reporter& reporter, Map::Level& level) const override;
};
/**
* @brief YYC12345 Rule 2
* @details
* The object grouped into physicalization group should not have isolated vertex,
* otherwise it will fail to be physicalized.
*/
class YYCRule2 : public IRule {
public:
YYCRule2();
virtual ~YYCRule2();
YYCC_DELETE_COPY_MOVE(YYCRule2)
public:
std::u8string_view GetRuleName() const override;
void Check(Reporter::Reporter& reporter, Map::Level& level) const override;
};
}

View File

@@ -1,6 +0,0 @@
#pragma once
#include "../Rule.hpp"
namespace BMapInspector::Rule {
}

View File

@@ -0,0 +1,64 @@
#include "BBugRules.hpp"
namespace L = LibCmo;
namespace C = LibCmo::CK2;
namespace O = LibCmo::CK2::ObjImpls;
namespace BMapInspector::Ruleset {
#pragma region BBug Rule 1
BBugRule1::BBugRule1() : Rule::IRule() {}
BBugRule1::~BBugRule1() {}
std::u8string_view BBugRule1::GetRuleName() const {
return u8"BBUG1";
}
void BBugRule1::Check(Reporter::Reporter& reporter, Map::Level& level) const {
if (!level.GetTargetLights().empty()) {
reporter.WriteInfo(u8"Using light in map is not suggested.");
}
}
#pragma endregion
#pragma region BBug Rule 2
BBugRule2::BBugRule2() : Rule::IRule() {}
BBugRule2::~BBugRule2() {}
std::u8string_view BBugRule2::GetRuleName() const {
return u8"BBUG2";
}
void BBugRule2::Check(Reporter::Reporter& reporter, Map::Level& level) const {
if (!level.GetTargetCameras().empty()) {
reporter.WriteInfo(u8"Using camera in map is not suggested.");
}
}
#pragma endregion
#pragma region BBug Rule 3
BBugRule3::BBugRule3() : Rule::IRule() {}
BBugRule3::~BBugRule3() {}
std::u8string_view BBugRule3::GetRuleName() const {
return u8"BBUG3";
}
void BBugRule3::Check(Reporter::Reporter& reporter, Map::Level& level) const {
// TODO:
// This rule is complex and can be done by Ballance Blender Plugin.
// So we are not urgently to implement it in there.
// Just make a rule placeholder in there and may finish it in future.
}
#pragma endregion
} // namespace BMapInspector::Ruleset

View File

@@ -0,0 +1,54 @@
#pragma once
#include "../Rule.hpp"
namespace BMapInspector::Ruleset {
/**
* @brief BBug Rule 1
* @details
* Using light in map is not suggested.
*/
class BBugRule1 : public Rule::IRule {
public:
BBugRule1();
virtual ~BBugRule1();
YYCC_DELETE_COPY_MOVE(BBugRule1)
public:
std::u8string_view GetRuleName() const override;
void Check(Reporter::Reporter& reporter, Map::Level& level) const override;
};
/**
* @brief BBug Rule 2
* @details
* Using camera in map is not suggested.
*/
class BBugRule2 : public Rule::IRule {
public:
BBugRule2();
virtual ~BBugRule2();
YYCC_DELETE_COPY_MOVE(BBugRule2)
public:
std::u8string_view GetRuleName() const override;
void Check(Reporter::Reporter& reporter, Map::Level& level) const override;
};
/**
* @brief BBug Rule 3
* @details
* Check whether the parameters of all materials is same with Ballance vanilla settings.
*/
class BBugRule3 : public Rule::IRule {
public:
BBugRule3();
virtual ~BBugRule3();
YYCC_DELETE_COPY_MOVE(BBugRule3)
public:
std::u8string_view GetRuleName() const override;
void Check(Reporter::Reporter& reporter, Map::Level& level) const override;
};
}

View File

@@ -0,0 +1,80 @@
#include "ChirsRules.hpp"
#include "Shared/Utility.hpp"
#include "Shared/Name.hpp"
namespace L = LibCmo;
namespace C = LibCmo::CK2;
namespace O = LibCmo::CK2::ObjImpls;
namespace BMapInspector::Ruleset {
#pragma region Chirs Rule 1
// Reference: https://tieba.baidu.com/p/5913556704
ChirsRule1::ChirsRule1() : Rule::IRule() {}
ChirsRule1::~ChirsRule1() {}
std::u8string_view ChirsRule1::GetRuleName() const {
return u8"CHIRS1";
}
void ChirsRule1::Check(Reporter::Reporter& reporter, Map::Level& level) const {
constexpr char8_t MTL_LATERNE_VERLAUF[] = u8"Laterne_Verlauf";
auto* ctx = level.GetCKContext();
// Fetch Laterne_Verlauf first
auto* latern = Shared::Utility::FetchMaterial(ctx, MTL_LATERNE_VERLAUF);
if (latern == nullptr) return;
// Report warning if this material's texture is not Laterne_Verlauf.tga
auto* latern_tex = latern->GetTexture();
if (latern_tex == nullptr) {
reporter.FormatWarning(
u8"Find a material named %s but it doesn't have associated texture. "
u8"It occupies the magic material %s which affect the ray of latern in game. Please confirm this is your intention.",
Shared::Utility::QuoteText(MTL_LATERNE_VERLAUF).c_str(),
Shared::Utility::QuoteText(MTL_LATERNE_VERLAUF).c_str());
} else {
if (!Shared::Utility::CheckTextureFileName(latern_tex, Shared::Name::Texture::LATERNE_VERLAUF)) {
reporter.FormatWarning(
u8"Find a material named %s but its texture is not %s. "
u8"It occupies the magic material %s which affect the ray of latern in game. Please confirm this is your intention.",
Shared::Utility::QuoteText(MTL_LATERNE_VERLAUF).c_str(),
Shared::Utility::QuoteText(Shared::Name::Texture::LATERNE_VERLAUF).c_str(),
Shared::Utility::QuoteText(MTL_LATERNE_VERLAUF).c_str());
}
}
// Report warning if there is multiple Laterne_Verlauf material.
auto next_latern = ctx->GetObjectByNameAndClass(MTL_LATERNE_VERLAUF, C::CK_CLASSID::CKCID_MATERIAL, latern);
if (next_latern != nullptr) {
reporter.FormatWarning(u8"There are multiple materials named %s. This will cause the disappearance of some latern's rays.",
Shared::Utility::QuoteText(MTL_LATERNE_VERLAUF).c_str());
}
// Report warning if some materials' texture is Laterne_Verlauf,
// but its name is not Laterne_Verlauf.
for (auto* other_mtl : level.GetMaterials()) {
if (C::CKStrEqual(other_mtl->GetName(), MTL_LATERNE_VERLAUF)) continue;
auto other_mtl_tex = other_mtl->GetTexture();
if (other_mtl_tex == nullptr) continue;
if (Shared::Utility::CheckTextureFileName(other_mtl_tex, Shared::Name::Texture::LATERNE_VERLAUF)) {
reporter.FormatWarning(
u8"Find material %s referring texture %s, but its name is not %s. "
u8"Please confirm the usage of this material. If it is used as %s, please rename it into %s to have correct latern ray.",
Shared::Utility::QuoteObjectName(other_mtl).c_str(),
Shared::Utility::QuoteText(Shared::Name::Texture::LATERNE_VERLAUF).c_str(),
Shared::Utility::QuoteText(MTL_LATERNE_VERLAUF).c_str(),
Shared::Utility::QuoteText(MTL_LATERNE_VERLAUF).c_str(),
Shared::Utility::QuoteText(MTL_LATERNE_VERLAUF).c_str());
}
}
}
#pragma endregion
} // namespace BMapInspector::Ruleset

View File

@@ -1,21 +1,19 @@
#pragma once
#include "../Rule.hpp"
namespace BMapInspector::Rule {
// Reference: https://tieba.baidu.com/p/5913556704
namespace BMapInspector::Ruleset {
/**
* @brief Chirs241097 Rule 1
* @brief chirs241097 Rule 1
* @details
* This rule will make sure that there is only 1 texture named Laterne_Verlauf in map,
* which represent the ray of latern.
*/
class Chirs1Rule : public IRule {
class ChirsRule1 : public Rule::IRule {
public:
Chirs1Rule();
virtual ~Chirs1Rule();
YYCC_DELETE_COPY_MOVE(Chirs1Rule)
ChirsRule1();
virtual ~ChirsRule1();
YYCC_DELETE_COPY_MOVE(ChirsRule1)
public:
std::u8string_view GetRuleName() const override;

View File

@@ -0,0 +1,139 @@
#include "GpRules.hpp"
#include "Shared/Utility.hpp"
#include "Shared/Sector.hpp"
#include <set>
namespace L = LibCmo;
namespace C = LibCmo::CK2;
namespace O = LibCmo::CK2::ObjImpls;
namespace BMapInspector::Ruleset {
#pragma region GP1 Rule
// Reference: https://tieba.baidu.com/p/3182981807
GpRule1::GpRule1() : Rule::IRule() {}
GpRule1::~GpRule1() {}
std::u8string_view GpRule1::GetRuleName() const {
return u8"GP1";
}
void GpRule1::Check(Reporter::Reporter& reporter, Map::Level& level) const {
// TODO:
// This rule is complex and can be done by Ballance Blender Plugin.
// So we are not urgently to implement it in there.
// Just make a rule placeholder in there and may finish it in future.
}
#pragma endregion
#pragma region GP2 Rule
GpRule2::GpRule2() : Rule::IRule() {}
GpRule2::~GpRule2() {}
std::u8string_view GpRule2::GetRuleName() const {
return u8"GP2";
}
void GpRule2::Check(Reporter::Reporter& reporter, Map::Level& level) const {
auto* ctx = level.GetCKContext();
Shared::Sector::SectorNameBuilder builder;
// We need collect all group names first,
// becuase in following code we need frequent visit them
std::set<std::u8string> group_names;
for (auto* group : level.GetGroups()) {
auto group_name = group->GetName();
if (group_name != nullptr) {
group_names.emplace(std::u8string(group_name));
}
}
// Check the sector count of this game.
L::CKDWORD sector_count;
for (sector_count = Shared::Sector::MIN_SECTOR; sector_count <= Shared::Sector::MAX_SECTOR; ++sector_count) {
// Build name first with special treat for sector 9
if (sector_count != 9) {
auto sector_name = builder.get_name(sector_count);
if (!group_names.contains(sector_name)) {
if (sector_count == Shared::Sector::MIN_SECTOR) {
reporter.WriteError(u8"Can not find any reasonable sector group in your map.");
return;
} else {
break;
}
}
} else {
auto sector_names = builder.get_sector9_names();
bool has_legacy_sector = group_names.contains(sector_names.legacy_name);
bool has_intuitive_sector = group_names.contains(sector_names.intuitive_name);
if (!has_legacy_sector && !has_intuitive_sector) {
break;
}
if (has_legacy_sector && has_intuitive_sector) {
reporter.FormatError(u8"Found %s and %s at the same map. This is not allowed.",
Shared::Utility::QuoteText(sector_names.legacy_name).c_str(),
Shared::Utility::QuoteText(sector_names.intuitive_name).c_str());
return;
}
}
}
// Now sector_count is the first sector which can not find,
// so we need minus one on it.
--sector_count;
// Report sector count info.
reporter.FormatInfo(u8"Your map has %" PRIuCKDWORD " sector(s).", sector_count);
// Report special warning for map which only contain 1 sector.
if (sector_count == 1) {
reporter.WriteWarning(u8"Your map only have one sector. "
u8"This is okey but not suggested because it will cause mosaic issue on the flames of checkpoint. "
u8"Consider adding another sector to resolve this issue.");
}
// Report warning for sector greater than 8.
if (sector_count > 8) {
reporter.WriteWarning(u8"You are creating a map with more than 8 sectors. "
u8"This will cause vanilla Ballance freezed when loading it. "
u8"Please make sure that all players of your map have properly set 999 sector loader up.");
}
// If there is sector 9, check its kind and report wanring if it is intuitive kind.
if (sector_count > 8) {
auto sector_names = builder.get_sector9_names();
if (group_names.contains(sector_names.intuitive_name)) {
reporter.FormatWarning(u8"You are using intuitive sector name, %s, for sector 9. "
u8"This is only accepted by new 999 sector loader.",
Shared::Utility::QuoteText(sector_names.intuitive_name).c_str());
}
}
// We continue check following sectors to make sure that all sector is successive.
for (L::CKDWORD i = sector_count + 1; i <= Shared::Sector::MAX_SECTOR; ++i) {
if (i != 9) {
auto sector_name = builder.get_name(i);
if (group_names.contains(sector_name)) {
reporter.FormatError(u8"Found group %s unexpected. "
u8"Please check whether sector groups are successive in your map.",
Shared::Utility::QuoteText(sector_name).c_str());
}
} else {
auto sector_names = builder.get_sector9_names();
bool has_legacy_sector = group_names.contains(sector_names.legacy_name);
bool has_intuitive_sector = group_names.contains(sector_names.intuitive_name);
if (has_legacy_sector || has_intuitive_sector) {
reporter.FormatError(u8"Found group %s or %s unexpected. "
u8"Please check whether sector groups are successive in your map.",
Shared::Utility::QuoteText(sector_names.legacy_name).c_str(),
Shared::Utility::QuoteText(sector_names.intuitive_name).c_str());
}
}
}
}
#pragma endregion
} // namespace BMapInspector::Ruleset

View File

@@ -0,0 +1,44 @@
#pragma once
#include "../Rule.hpp"
namespace BMapInspector::Ruleset {
/**
* @brief Gamepiaynmo Rule 1
* @details
* The most comprehensive group checker inspired from Ballance Blender Plugin.
*/
class GpRule1 : public Rule::IRule {
public:
GpRule1();
virtual ~GpRule1();
YYCC_DELETE_COPY_MOVE(GpRule1)
public:
std::u8string_view GetRuleName() const override;
void Check(Reporter::Reporter& reporter, Map::Level& level) const override;
};
/**
* @brief Gamepiaynmo Rule 2
* @details
* This rule will:
* \li Show how many sector located in given map.
* \li Check whether there is sector group.
* \li Check whether use intuitive sector name for sector 9.
* \li Warn for sector count is equal to 1. It will cause mosaic issue on the flames of checkpoint.
* \li Warn for sector count greater than 8. It will cause vanilla game freezed without 999 sector loader.
* \li Check whether sector group is successive.
*/
class GpRule2 : public Rule::IRule {
public:
GpRule2();
virtual ~GpRule2();
YYCC_DELETE_COPY_MOVE(GpRule2)
public:
std::u8string_view GetRuleName() const override;
void Check(Reporter::Reporter& reporter, Map::Level& level) const override;
};
}

View File

@@ -1,23 +1,22 @@
#include "LXRules.hpp"
#include "Shared.hpp"
#include "Shared/Utility.hpp"
#include "Shared/Name.hpp"
#include <set>
namespace L = LibCmo;
namespace C = LibCmo::CK2;
namespace O = LibCmo::CK2::ObjImpls;
namespace BMapInspector::Rule {
namespace BMapInspector::Ruleset {
#pragma region LX Rule 1
constexpr char8_t LX1[] = u8"LX1";
LXRule1::LXRule1() : IRule() {}
LXRule1::LXRule1() : Rule::IRule() {}
LXRule1::~LXRule1() {}
std::u8string_view LXRule1::GetRuleName() const {
return LX1;
return u8"LX1";
}
void LXRule1::Check(Reporter::Reporter& reporter, Map::Level& level) const {
@@ -25,10 +24,10 @@ namespace BMapInspector::Rule {
// First we fetch all Ballance element and push them into set.
std::set<O::CK3dObject*> elements;
for (auto* group_name : Shared::GroupNames::ALL_PH) {
auto* group = Shared::FetchGroup(ctx, group_name);
for (auto* group_name : Shared::Name::Group::ALL_PH) {
auto* group = Shared::Utility::FetchGroup(ctx, group_name);
if (group == nullptr) continue;
auto group_objects = Shared::Iter3dObjects(group);
auto group_objects = Shared::Utility::Iter3dObjects(group);
for (auto* group_object : group_objects) {
elements.emplace(group_object);
}
@@ -49,7 +48,7 @@ namespace BMapInspector::Rule {
// because we do not want to duplicatedly process it.
if (mesh_insert_rv.second) {
// Iterate all meshes
auto mtls = Shared::IterMaterial(mesh);
auto mtls = Shared::Utility::IterMaterial(mesh);
for (auto* mtl : mtls) {
// Add into material set
auto mtl_insert_rv = element_materials.emplace(mtl);
@@ -76,23 +75,21 @@ namespace BMapInspector::Rule {
if (mesh == nullptr) continue;
// And check mesh
if (element_meshes.contains(mesh)) {
reporter.FormatError(
LX1,
u8R"(Object "%s" used mesh "%s" is already used by a Ballance element. This will cause this object can not be rendered correctly in level.)",
Shared::RenderObjectName(other_object),
Shared::RenderObjectName(mesh));
reporter.FormatError(u8"Object %s used mesh %s is already used by a Ballance element. "
u8"This will cause this object can not be rendered correctly in level.",
Shared::Utility::QuoteObjectName(other_object).c_str(),
Shared::Utility::QuoteObjectName(mesh).c_str());
} else {
// If not, check material.
// Iterate all meshes
auto mtls = Shared::IterMaterial(mesh);
auto mtls = Shared::Utility::IterMaterial(mesh);
for (auto* mtl : mtls) {
if (element_materials.contains(mtl)) {
reporter.FormatError(
LX1,
u8R"(Object "%s" used material "%s" (referred by mesh "%s") is already used by a Ballance element. This will cause this object can not be rendered correctly in level.)",
Shared::RenderObjectName(other_object),
Shared::RenderObjectName(mtl),
Shared::RenderObjectName(mesh));
reporter.FormatError(u8"Object %s used material %s (referred by mesh %s) is already used by a Ballance element. "
u8"This will cause this object can not be rendered correctly in level.",
Shared::Utility::QuoteObjectName(other_object).c_str(),
Shared::Utility::QuoteObjectName(mtl).c_str(),
Shared::Utility::QuoteObjectName(mesh).c_str());
} else {
// Still not, check texture.
// Fetch texture
@@ -101,12 +98,12 @@ namespace BMapInspector::Rule {
// And check it
if (element_textures.contains(texture)) {
reporter.FormatError(
LX1,
u8R"(Object "%s" used texture "%s" (referred by mesh "%s" and material "%s") is already used by a Ballance element. This will cause this object can not be rendered correctly in level.)",
Shared::RenderObjectName(other_object),
Shared::RenderObjectName(texture),
Shared::RenderObjectName(mesh),
Shared::RenderObjectName(mtl));
u8"Object %s used texture %s (referred by mesh %s and material %s) is already used by a Ballance element. "
u8"This will cause this object can not be rendered correctly in level.",
Shared::Utility::QuoteObjectName(other_object).c_str(),
Shared::Utility::QuoteObjectName(texture).c_str(),
Shared::Utility::QuoteObjectName(mesh).c_str(),
Shared::Utility::QuoteObjectName(mtl).c_str());
}
}
}
@@ -116,4 +113,4 @@ namespace BMapInspector::Rule {
#pragma endregion
} // namespace BMapInspector::Rule
} // namespace BMapInspector::Ruleset

View File

@@ -1,14 +1,14 @@
#pragma once
#include "../Rule.hpp"
namespace BMapInspector::Rule {
namespace BMapInspector::Ruleset {
/**
* @brief LengXi Rule 1
* @details
* All meshes, materials and textures used by Ballance elements should not be used by any other objects.
*/
class LXRule1 : public IRule {
class LXRule1 : public Rule::IRule {
public:
LXRule1();
virtual ~LXRule1();

View File

@@ -0,0 +1,36 @@
#include "SOneRules.hpp"
#include "Shared/Utility.hpp"
namespace L = LibCmo;
namespace C = LibCmo::CK2;
namespace O = LibCmo::CK2::ObjImpls;
namespace BMapInspector::Ruleset {
#pragma region SOne Rule 1
SOneRule1::SOneRule1() : Rule::IRule() {}
SOneRule1::~SOneRule1() {}
std::u8string_view SOneRule1::GetRuleName() const {
return u8"SONE1";
}
void SOneRule1::Check(Reporter::Reporter& reporter, Map::Level& level) const {
auto* ctx = level.GetCKContext();
auto physicalized_3dobjects = Shared::Utility::FetchPhysicalized3dObjects(ctx);
for (auto* physicalized_3dobject : physicalized_3dobjects) {
auto* mesh = physicalized_3dobject->GetCurrentMesh();
if (mesh == nullptr) {
reporter.FormatError(u8"Object %s is grouped into physicalization group, but it doesn't have any associated mesh. "
u8"This will cause itself and following objects can not be physicalized.",
Shared::Utility::QuoteObjectName(physicalized_3dobject).c_str());
}
}
}
#pragma endregion
} // namespace BMapInspector::Ruleset

Some files were not shown because too many files have changed in this diff Show More