Skip to content

Commit

Permalink
Merge branch 'Tencent:master' into master
Browse files Browse the repository at this point in the history
  • Loading branch information
ArnoChenFx authored Dec 3, 2024
2 parents 2706e2f + 8815721 commit 5d72b62
Show file tree
Hide file tree
Showing 12 changed files with 218 additions and 79 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -9,18 +9,29 @@ import { FOR, default as t, IF, ENDIF, ELSE } from "./tte.mjs"
import * as il2cpp_snippets from "./il2cpp_snippets.mjs"

function defineValueType(valueTypeInfo) {
// TODO 会存在一个 IsEnum 且 IsGenericParameter 的类型,signature为空,先过滤处理,晚点彻查。
// TODO 会存在一个 IsEnum 且 IsGenericParameter 的类型,signature为空,先过滤处理,晚点彻查。
if (!valueTypeInfo.Signature) return ''
var fieldSignatures = il2cpp_snippets.listToJsArray(valueTypeInfo.FieldSignatures);
return t`// ${valueTypeInfo.CsName}
struct ${valueTypeInfo.Signature}
{
${FOR(il2cpp_snippets.listToJsArray(valueTypeInfo.FieldSignatures), (s, i) => t`
${IF(fieldSignatures.length == 0)}
union
{
struct
{
};
uint8_t __padding[1];
};
${ELSE()}
${FOR(fieldSignatures, (s, i) => t`
${IF(il2cpp_snippets.isNullableStruct(valueTypeInfo.Signature) && i == valueTypeInfo.NullableHasValuePosition)}
${il2cpp_snippets.SToCPPType(s)} hasValue;
${ELSE()}
${il2cpp_snippets.SToCPPType(s)} p${i};
${ENDIF()}
`)}
${ENDIF()}
};
`;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -95,10 +95,14 @@ static BindingMode FilterBigStructAndPointerOfPointer(MemberInfo memberInfo)
{
return BindingMode.DontBinding;
}
if (ptype.IsByRef || ptype.IsPointer || ptype == typeof(System.IntPtr) || ptype == typeof(System.UIntPtr))
if (ptype.IsByRef || ptype.IsPointer)
{
return BindingMode.DontBinding;
}
if (ptype == typeof(System.IntPtr) || ptype == typeof(System.UIntPtr))
{
return BindingMode.SlowBinding;
}
}
}

Expand Down
10 changes: 9 additions & 1 deletion unity/Assets/core/upm/Runtime/Resources/puerts/websocketpp.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,12 @@ class WebSocket extends EventTarget {
}

get readyState() {
if (this._readyState === WebSocket.OPEN) {
const [statue, message] = this._raw.statue();
if (statue != 0) {
this._fail(`${message}[${statue}]`);
}
}
return this._readyState;
}

Expand Down Expand Up @@ -130,7 +136,9 @@ class WebSocket extends EventTarget {
close(code, data) {
try {
this._raw.close(code, data);
} catch(e) {}
} catch(e) {
this.dispatchEvent({type:'error', data: e.message}); //dispatchEvent immediately
}
this._cleanup();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -547,7 +547,7 @@ internal int RegisterType(

// extensionMethods
// 因为内存问题与crash问题移入宏中
#if PUERTS_REFLECT_ALL_EXTENSION || UNITY_EDITOR
#if (PUERTS_REFLECT_ALL_EXTENSION || UNITY_EDITOR) && !PUERTS_DISABLE_REFLECT_EXTENSION
// #if UNITY_EDITOR && !PUERTS_REFLECT_ALL_EXTENSION && !PUERTS_IL2CPP_OPTIMIZATION
// if (!UnityEditor.EditorApplication.isPlaying)
// #endif
Expand Down
59 changes: 59 additions & 0 deletions unity/cli/test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,64 @@ function collectCSFilesAndMakeCompileConfig(dir, workdir, excludeGenerator) {
return [definitions, linkPuerTS, linkPuerTSCommonJS, linkUnitTests, linkGenerators].join('\n');
}

function compareVersions(version1, version2) {
const v1Parts = version1.split('.').map(Number);
const v2Parts = version2.split('.').map(Number);

for (let i = 0; i < Math.max(v1Parts.length, v2Parts.length); i++) {
const v1 = v1Parts[i] || 0;
const v2 = v2Parts[i] || 0;

if (v1 < v2) {
return -1;
}
if (v1 > v2) {
return 1;
}
}

return 0;
}

function selectSdk(workdir) {
const sdk_list = exec('dotnet --list-sdks');
if (sdk_list.code == 0) {
const sdkVersions = sdk_list.stdout
.split('\n') // 按行分割
.filter(line => line.trim() !== '' && /^\d+\.\d+\.\d+/.test(line))
.map(line => line.split(' ')[0])
.filter((value, index, self) => self.indexOf(value) === index);
//console.log(sdkVersions);

let selectedVersion

for (var i = 0; i < sdkVersions.length; ++i) {
if(compareVersions(sdkVersions[i], '9.0.0') < 0) {
if(!selectedVersion || compareVersions(selectedVersion, sdkVersions[i]) < 0) {
selectedVersion = sdkVersions[i];
}
}
}

if (selectedVersion) {
console.log(`selected sdk ${selectedVersion}`)

const global_cfg =

writeFileSync(
join(workdir, 'global.json'),
JSON.stringify({
"sdk": {
"version": selectedVersion
}
})
);
return;
}
}
throw new Error('can not find sdk less than 9.0.0');
}

async function runTest(cwd, copyConfig, runInReflection, filter = '') {
if (!existsSync(`${cwd}/Src/Helloworld.cs`)) {
console.error("[Puer] Cannot find UnitTest Src");
Expand All @@ -76,6 +134,7 @@ async function runTest(cwd, copyConfig, runInReflection, filter = '') {
rm("-rf", join(cwd, 'Src/StaticWrapper'));

mkdir("-p", workdir);
selectSdk(workdir);
exec(`dotnet new nunit`, { cwd: workdir });
rm('-rf', join(workdir, 'UnitTest1.cs'));
rm('-rf', join(workdir, 'Usings.cs'));
Expand Down
24 changes: 21 additions & 3 deletions unity/native_src/Inc/DataTransfer.h
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,24 @@ struct TScriptStructTraits<FPlane>
}
};

template <>
struct TScriptStructTraits<FMatrix>
{
static UScriptStruct* Get()
{
return GetScriptStructInCoreUObject(TEXT("Matrix"));
}
};

template <>
struct TScriptStructTraits<FIntVector4>
{
static UScriptStruct* Get()
{
return GetScriptStructInCoreUObject(TEXT("IntVector4"));
}
};

template <class...>
using ToVoid = void;

Expand Down Expand Up @@ -319,7 +337,7 @@ class JSENV_API DataTransfer
static v8::Local<v8::Value> FindOrAddCData(
v8::Isolate* Isolate, v8::Local<v8::Context> Context, const void* TypeId, const void* Ptr, bool PassByPointer);

static bool IsInstanceOf(v8::Isolate* Isolate, const void* TypeId, v8::Local<v8::Object> JsObject);
static bool IsInstanceOf(v8::Isolate* Isolate, const void* TypeId, v8::Local<v8::Value> JsObject);

static v8::Local<v8::Value> UnRef(v8::Isolate* Isolate, const v8::Local<v8::Value>& Value);

Expand Down Expand Up @@ -347,12 +365,12 @@ class JSENV_API DataTransfer
v8::Isolate* Isolate, v8::Local<v8::Context> Context, UScriptStruct* ScriptStruct, void* Ptr, bool PassByPointer);

template <typename T>
static bool IsInstanceOf(v8::Isolate* Isolate, v8::Local<v8::Object> JsObject)
static bool IsInstanceOf(v8::Isolate* Isolate, v8::Local<v8::Value> JsObject)
{
return IsInstanceOf(Isolate, TScriptStructTraits<T>::Get(), JsObject);
}

static bool IsInstanceOf(v8::Isolate* Isolate, UStruct* Struct, v8::Local<v8::Object> JsObject);
static bool IsInstanceOf(v8::Isolate* Isolate, UStruct* Struct, v8::Local<v8::Value> JsObject);

static FString ToFString(v8::Isolate* Isolate, v8::Local<v8::Value> Value);

Expand Down
8 changes: 4 additions & 4 deletions unity/native_src/Src/DataTransfer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,9 @@ v8::Local<v8::Value> DataTransfer::FindOrAddCData(
Isolate, Context, TypeId, const_cast<void*>(Ptr), PassByPointer);
}

bool DataTransfer::IsInstanceOf(v8::Isolate* Isolate, const void* TypeId, v8::Local<v8::Object> JsObject)
bool DataTransfer::IsInstanceOf(v8::Isolate* Isolate, const void* TypeId, v8::Local<v8::Value> JsObject)
{
return IsolateData<ICppObjectMapper>(Isolate)->IsInstanceOfCppObject(Isolate, TypeId, JsObject);
return JsObject->IsObject() && IsolateData<ICppObjectMapper>(Isolate)->IsInstanceOfCppObject(Isolate, TypeId, JsObject.As<v8::Object>());
}

v8::Local<v8::Value> DataTransfer::UnRef(v8::Isolate* Isolate, const v8::Local<v8::Value>& Value)
Expand Down Expand Up @@ -64,9 +64,9 @@ v8::Local<v8::Value> DataTransfer::FindOrAddStruct(
return FV8Utils::IsolateData<IObjectMapper>(Isolate)->FindOrAddStruct(Isolate, Context, ScriptStruct, Ptr, PassByPointer);
}

bool DataTransfer::IsInstanceOf(v8::Isolate* Isolate, UStruct* Struct, v8::Local<v8::Object> JsObject)
bool DataTransfer::IsInstanceOf(v8::Isolate* Isolate, UStruct* Struct, v8::Local<v8::Value> JsObject)
{
return FV8Utils::IsolateData<IObjectMapper>(Isolate)->IsInstanceOf(Struct, JsObject);
return JsObject->IsObject() && FV8Utils::IsolateData<IObjectMapper>(Isolate)->IsInstanceOf(Struct, JsObject.As<v8::Object>());
}

void DataTransfer::ThrowException(v8::Isolate* Isolate, const char* Message)
Expand Down
3 changes: 3 additions & 0 deletions unity/test/Src/Cases/WebsocketTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,9 @@ public async Task SmokeTest()
con.addEventListener('open', (ev) => {
console.log(`on open`);
con.send('puerts websocket');
if (con.readyState != WebSocket.OPEN) {
throw new Error('invalid readyState');
}
});
con.addEventListener('message', (ev) => {
console.log(`on message: ${ev.data}`);
Expand Down
9 changes: 5 additions & 4 deletions unreal/Puerts/Source/JsEnv/Private/DataTransfer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,10 @@ v8::Local<v8::Value> DataTransfer::FindOrAddCData(
Isolate, Context, TypeId, const_cast<void*>(Ptr), PassByPointer);
}

bool DataTransfer::IsInstanceOf(v8::Isolate* Isolate, const void* TypeId, v8::Local<v8::Object> JsObject)
bool DataTransfer::IsInstanceOf(v8::Isolate* Isolate, const void* TypeId, v8::Local<v8::Value> JsObject)
{
return IsolateData<ICppObjectMapper>(Isolate)->IsInstanceOfCppObject(Isolate, TypeId, JsObject);
return JsObject->IsObject() &&
IsolateData<ICppObjectMapper>(Isolate)->IsInstanceOfCppObject(Isolate, TypeId, JsObject.As<v8::Object>());
}

v8::Local<v8::Value> DataTransfer::UnRef(v8::Isolate* Isolate, const v8::Local<v8::Value>& Value)
Expand Down Expand Up @@ -64,9 +65,9 @@ v8::Local<v8::Value> DataTransfer::FindOrAddStruct(
return FV8Utils::IsolateData<IObjectMapper>(Isolate)->FindOrAddStruct(Isolate, Context, ScriptStruct, Ptr, PassByPointer);
}

bool DataTransfer::IsInstanceOf(v8::Isolate* Isolate, UStruct* Struct, v8::Local<v8::Object> JsObject)
bool DataTransfer::IsInstanceOf(v8::Isolate* Isolate, UStruct* Struct, v8::Local<v8::Value> JsObject)
{
return FV8Utils::IsolateData<IObjectMapper>(Isolate)->IsInstanceOf(Struct, JsObject);
return JsObject->IsObject() && FV8Utils::IsolateData<IObjectMapper>(Isolate)->IsInstanceOf(Struct, JsObject.As<v8::Object>());
}

void DataTransfer::ThrowException(v8::Isolate* Isolate, const char* Message)
Expand Down
55 changes: 46 additions & 9 deletions unreal/Puerts/Source/JsEnv/Private/WebSocketImpl.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,9 @@ class V8WebSocketClientImpl

void Close(const v8::FunctionCallbackInfo<v8::Value>& Info);

void Close(websocketpp::close::status::value const code, std::string const& reason);
void Statue(const v8::FunctionCallbackInfo<v8::Value>& Info);

void CloseImmediately(websocketpp::close::status::value const code, std::string const& reason);

void PollOne();

Expand Down Expand Up @@ -143,7 +145,7 @@ class V8WebSocketClientImpl
static void OnGarbageCollectedWithFree(const v8::WeakCallbackInfo<V8WebSocketClientImpl>& Data)
{
// UE_LOG(LogTemp, Warning, TEXT(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> auto gc %p"), Data.GetParameter());
Data.GetParameter()->Close(websocketpp::close::status::normal, "");
Data.GetParameter()->CloseImmediately(websocketpp::close::status::normal, "");
delete Data.GetParameter();
}

Expand All @@ -158,7 +160,9 @@ V8WebSocketClientImpl::V8WebSocketClientImpl(v8::Isolate* InIsolate, v8::Local<v
websocketpp::lib::shared_ptr<puerts_asio::ssl::context> on_tls_init(websocketpp::connection_hdl)
{
auto ctx = websocketpp::lib::make_shared<puerts_asio::ssl::context>(websocketpp::lib::puerts_asio::ssl::context::sslv23);
ctx->set_verify_mode(puerts_asio::ssl::verify_none);

websocketpp::lib::error_code ec;
ctx->set_verify_mode(puerts_asio::ssl::verify_none, ec);
return ctx;
}
#endif
Expand All @@ -185,7 +189,7 @@ void V8WebSocketClientImpl::Connect(const v8::FunctionCallbackInfo<v8::Value>& I
if (ec)
{
std::stringstream ss;
ss << "could not create connection because: " << ec.message() << std::endl;
ss << "could not create connection because: " << ec.message() << "[" << ec.value() << "]" << std::endl;
FV8Utils::ThrowException(Isolate, ss.str().c_str());
return;
}
Expand Down Expand Up @@ -242,7 +246,7 @@ void V8WebSocketClientImpl::Send(const v8::FunctionCallbackInfo<v8::Value>& Info
if (ec)
{
std::stringstream ss;
ss << "could not create connection because: " << ec.message() << std::endl;
ss << "could send because: " << ec.message() << "[" << ec.value() << "]" << std::endl;
FV8Utils::ThrowException(Isolate, ss.str().c_str());
}
}
Expand Down Expand Up @@ -293,14 +297,40 @@ void V8WebSocketClientImpl::Close(const v8::FunctionCallbackInfo<v8::Value>& Inf
reason = *v8::String::Utf8Value(InIsolate, Info[1]);
}

Close(code, reason);
if (!Handle.expired())
{
websocketpp::lib::error_code ec;
Client.close(Handle, code, reason, ec);
if (ec)
{
std::stringstream ss;
ss << "close fail: " << ec.message() << "[" << ec.value() << "]" << std::endl;
FV8Utils::ThrowException(Isolate, ss.str().c_str());
}
}
Cleanup();
}

void V8WebSocketClientImpl::Statue(const v8::FunctionCallbackInfo<v8::Value>& Info)
{
websocketpp::lib::error_code ec;
Client.ping(Handle, "", ec);
auto isolate = Info.GetIsolate();
auto context = isolate->GetCurrentContext();
auto res = v8::Array::New(isolate);

res->Set(context, 0, v8::Int32::New(isolate, ec.value())).Check();
res->Set(context, 1,
v8::String::NewFromUtf8(isolate, ec.message().c_str(), v8::NewStringType::kNormal, ec.message().size()).ToLocalChecked());
Info.GetReturnValue().Set(res);
}

void V8WebSocketClientImpl::Close(websocketpp::close::status::value const code, std::string const& reason)
void V8WebSocketClientImpl::CloseImmediately(websocketpp::close::status::value const code, std::string const& reason)
{
if (!Handle.expired())
{
Client.close(Handle, code, reason);
websocketpp::lib::error_code ec;
Client.close(Handle, code, reason, ec);
}
Cleanup();
}
Expand Down Expand Up @@ -390,7 +420,7 @@ void V8WebSocketClientImpl::OnFail(wspp_connection_hdl InHandle)
// must not raise exception in js, recommend just push a pending msg and process later.
Handles[ON_FAIL].Get(Isolate)->Call(GContext.Get(Isolate), v8::Undefined(Isolate), 1, args);
}
Close(websocketpp::close::status::abnormal_close, "");
CloseImmediately(websocketpp::close::status::abnormal_close, "");
}

} // namespace PUERTS_NAMESPACE
Expand Down Expand Up @@ -430,6 +460,13 @@ void InitWebsocketPPWrap(v8::Local<v8::Context> Context)
->Close(Info);
}));

WSTemplate->PrototypeTemplate()->Set(v8::String::NewFromUtf8(Isolate, "statue").ToLocalChecked(),
v8::FunctionTemplate::New(Isolate,
[](const v8::FunctionCallbackInfo<v8::Value>& Info) {
static_cast<PUERTS_NAMESPACE::V8WebSocketClientImpl*>(Info.Holder()->GetAlignedPointerFromInternalField(0))
->Statue(Info);
}));

WSTemplate->PrototypeTemplate()->Set(v8::String::NewFromUtf8(Isolate, "poll").ToLocalChecked(),
v8::FunctionTemplate::New(Isolate,
[](const v8::FunctionCallbackInfo<v8::Value>& Info)
Expand Down
Loading

0 comments on commit 5d72b62

Please sign in to comment.