“初始化俯视角工程,带puerts,未编过”

This commit is contained in:
2024-12-01 02:11:25 +08:00
parent 04698dd585
commit 850d76173c
1491 changed files with 271579 additions and 0 deletions
@@ -0,0 +1,28 @@
/*
* Tencent is pleased to support the open source community by making Puerts available.
* Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.
* Puerts is licensed under the BSD 3-Clause License, except for the third-party components listed in the file 'LICENSE' which may be subject to their corresponding license terms.
* This file is subject to the terms and conditions defined in file 'LICENSE', which is part of this source code package.
*/
(function () {
"use strict";
let argList = [];
let argMap = {};
puerts.argv = {
getByIndex : function(index) {
return argList[index]
},
getByName : function(name) {
return argMap[name];
},
add : function(name, value) {
argList.push(value);
argMap[name] = value;
}
}
}());
@@ -0,0 +1,311 @@
/*
* Tencent is pleased to support the open source community by making Puerts available.
* Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.
* Puerts is licensed under the BSD 3-Clause License, except for the third-party components listed in the file 'LICENSE' which may be subject to their corresponding license terms.
* This file is subject to the terms and conditions defined in file 'LICENSE', which is part of this source code package.
*/
var global = global || (function () { return this; }());
(function (global) {
"use strict";
let sendRequestSync = puerts.sendRequestSync;
function getClassInfo(className) {
let classInfo = sendRequestSync('getClassInfo', className);
return JSON.parse(classInfo);
}
function ref(x) {
return {value:x};
}
function unref(r) {
return r.value;
}
function ret(o) {
return o.ReturnValue;
}
function retWithWrap(o){
return wrapUObject(o.ReturnValue);
}
function retWithAsyncWrap(o){
return wrapUObject(o.ReturnValue, true);
}
function id(x) {
return x;
}
function makeArgumentUnpack(paramInfo) {
if (paramInfo.isOut && paramInfo.isUObject) {
return x => ref(wrapUObject(x));
} else if(paramInfo.isOut) {
return ref;
} else if (paramInfo.isUObject) {
return wrapUObject;
} else {
return id;
}
}
function wrapCallback(functionInfo, callback) {
let paramsInfo = functionInfo.parameters;
paramsInfo.forEach( paramInfo => paramInfo.unpack = makeArgumentUnpack(paramInfo));
return (argsObj) => {
let args = paramsInfo.map(paramInfo => paramInfo.unpack(argsObj[paramInfo.name]));
callback.apply(null, args);
};
}
let registerCallbacks = Object.create(null);
var allocedCallbackId = 0;
function registerCallback(callback) {
let callbackId = allocedCallbackId++;
registerCallbacks[callbackId] = callback;
return callbackId;
}
function unregisterCallback(callbackId) {
registerCallbacks[callbackId] = undefined;
}
let wrapGenerators = Object.create(null);
class Delegate {
constructor(objectId, propertyName, propertyType) {
this.objectId = objectId;
this.propertyName = propertyName;
this.propertyType = propertyType;
}
Bind(func) {
if (typeof func !== 'function') {
throw new Error('function needed!');
}
this.Unbind();
let callbackId = registerCallback(wrapCallback(this.propertyType, func));
sendRequestSync('bindDelegate', this.objectId + '#' + this.propertyName + '#' + callbackId);
this.bindedCallbackId = callbackId;
}
Unbind() {
if (this.bindedCallbackId) {
sendRequestSync('unbindDelegate', this.bindedCallbackId);
unregisterCallback(this.bindedCallbackId);
this.bindedCallbackId = undefined;
}
}
}
class MulticastDelegate {
constructor(objectId, propertyName, propertyType) {
this.objectId = objectId;
this.propertyName = propertyName;
this.propertyType = propertyType;
}
Add(func) {
if (typeof func !== 'function') {
throw new Error('function needed!');
}
let callbackId = registerCallback(wrapCallback(this.propertyType, func));
sendRequestSync('bindDelegate', this.objectId + '#' + this.propertyName + '#' + callbackId);
return callbackId;
}
Remove(callbackId) {
sendRequestSync('unbindDelegate', callbackId);
unregisterCallback(callbackId);
}
}
let pendingAsyncCall = [];
function getWrapGenerator(className, optClassInfo) {
if (!(className in wrapGenerators)) {
let classInfo = optClassInfo || getClassInfo(className);
wrapGenerators[className] = (objectId, isClass, isAsync) => {
let target = {$functions: classInfo.functions, $id:objectId, toJSON:() => objectId, $toAsync:() => getWrapGenerator(className, optClassInfo)(objectId, true, true)};
if (!isClass) {
for (var propertyName in classInfo.delegates) {
target[propertyName] = new Delegate(objectId, propertyName, classInfo.delegates[propertyName]);
}
for (var propertyName in classInfo.multicasts) {
target[propertyName] = new MulticastDelegate(objectId, propertyName, classInfo.multicasts[propertyName]);
}
} else {
target["StaticClass"] = () => classInfo.pathName;
}
return new Proxy(target, {
get: function(cfg, name) {
if (!(name in cfg)) {
let functionInfo = cfg.$functions[name];
let id = cfg.$id
//之前抛异常不太适合,传统js是duck typing,有时会通过是否有某函数判断能力。
//比如,promise里resolve传入的对象,thenable对象是通过是否有then函数来决定的,
//所以异步返回,resolve传入wrap的uobject时,会抛无then函数的异常;
if (!functionInfo) return;
let paramsInfo = functionInfo.parameters;
let r = functionInfo.isUObject ? (isAsync ? retWithAsyncWrap : retWithWrap) : ret;
cfg[name] = isAsync ? function() {
let argsObj = {};
paramsInfo.forEach((paramInfo, idx) => argsObj[paramInfo.name] = paramInfo.isOut ? arguments[idx].value : arguments[idx]);
let argsString = JSON.stringify(argsObj);
let outterArgs = arguments;
return new Promise(function(resolve, reject) {
let args = id + '#' + name + '#' + argsString;
pendingAsyncCall.push({args: args.length + 'A' + args, resolve: res => {
paramsInfo.forEach((paramInfo, idx) => {
if(paramInfo.isOut) {
outterArgs[idx].value = paramInfo.isUObject ? wrapUObject(res[paramInfo.name]) :res[paramInfo.name];
}
});
resolve(r(res));
}, reject: reject});
});
} : function() {
let argsObj = {};
paramsInfo.forEach((paramInfo, idx) => argsObj[paramInfo.name] = paramInfo.isOut ? arguments[idx].value : arguments[idx]);
let argsString = JSON.stringify(argsObj);
//puerts.console.log('id:' + id + ',method:' + name + ',args:' + argsString);
let res = JSON.parse(sendRequestSync('callUObjectMethod', id + '#' + name + '#' + argsString));
paramsInfo.forEach((paramInfo, idx) => {
if(paramInfo.isOut) {
arguments[idx].value = paramInfo.isUObject ? wrapUObject(res[paramInfo.name]) :res[paramInfo.name];
}
});
return r(res);
}
}
return cfg[name];
},
set: function(cfg, name, value) {
throw new Error('set not allow for ' + name);
}
});
};
}
return wrapGenerators[className];
}
function wrapUObject(objectId, isAsync) {
if (objectId === "0000000000000000") return null;
let className = objectId.substring(objectId.indexOf('-') + 1);
return getWrapGenerator(className)(objectId, false, isAsync);
}
let UE = new Proxy(Object.create(null), {
get: function(classWrapers, name) {
if (!(name in classWrapers)) {
let classInfo = getClassInfo(name);
classWrapers[name] = getWrapGenerator(name, classInfo)(classInfo.pathName, true);
}
return classWrapers[name];
}
});
puerts.registerRequestHandler('invokeCallback', (msg, onFinished) => {
let split = msg.indexOf('#');
let callbackId = msg.substring(0, split);
let cb = registerCallbacks[callbackId];
if (cb) {
cb(JSON.parse(msg.substring(split + 1)));
onFinished("");
} else {
onFinished(undefined, "no callback " + callbackId);
}
});
puerts.registerRequestHandler('onCallbackRelease', callbackId => {
registerCallbacks[callbackId] = undefined;
});
var mainObject = undefined;
function getMainObject() {
if (!mainObject) {
mainObject = wrapUObject(sendRequestSync('getMainObjectId', ''));
}
return mainObject;
}
function getProperties(obj, ...fields) {
let args = (typeof obj === 'string') ? obj : obj.toJSON();
if (fields.length > 0) {
args += ("#" + fields.join('#'));
}
return JSON.parse(sendRequestSync('getProperties', args));
}
function getPropertiesAsync(obj, ...fields) {
let args = (typeof obj === 'string') ? obj : obj.toJSON();
if (fields.length > 0) {
args += ("#" + fields.join('#'));
}
return new Promise(function(resolve, reject) {
pendingAsyncCall.push({args: args.length + 'C' + args, resolve: resolve, reject: reject});
});
}
function setProperties(obj, properties) {
let objectId = (typeof obj === 'string') ? obj : obj.toJSON();
sendRequestSync('setProperties', objectId + '#' +JSON.stringify(properties));
}
function setPropertiesAsync(obj, properties) {
let objectId = (typeof obj === 'string') ? obj : obj.toJSON();
let args = objectId + '#' +JSON.stringify(properties);
return new Promise(function(resolve, reject) {
pendingAsyncCall.push({args: args.length + 'B' + args, resolve: resolve, reject: reject});
});
}
function flushAsyncCall(trace) {
if (pendingAsyncCall.length == 0) return 0;
let sliceCalls = pendingAsyncCall;
let batchArgs = sliceCalls.map(x =>x.args).join('');
if (trace) {
puerts.console.log(sliceCalls.map(x =>x.args).join('\n'))
}
pendingAsyncCall = [];
let batchResult = sendRequestSync('batchCall', batchArgs);
let callIndex = 0;
let split1 = 0;
let split2;
while((split2 = batchResult.indexOf('#', split1)) >= 0) {
let len = parseInt(batchResult.slice(split1, split2));
let result = batchResult.substr(split2 + 1, len);
if (result.startsWith('#')) {
let r = result.substr(1);
if (r == '') {
sliceCalls[callIndex].resolve();
} else {
sliceCalls[callIndex].resolve(JSON.parse(result.substr(1)));
}
} else {
sliceCalls[callIndex].reject(new Error(result));
}
++callIndex;
split1 = split2 + 1 + len;
}
return sliceCalls.length
}
puerts.getMainObject = getMainObject;
puerts.getProperties = getProperties;
puerts.getPropertiesAsync = getPropertiesAsync;
puerts.setProperties = setProperties;
puerts.setPropertiesAsync = setPropertiesAsync;
puerts.flushAsyncCall = flushAsyncCall;
puerts.$ref = ref;
puerts.$unref = unref;
puerts.$async = x => x.$toAsync();
puerts.registerBuildinModule('ue', UE);
}(global));
@@ -0,0 +1,101 @@
/*
* Tencent is pleased to support the open source community by making Puerts available.
* Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.
* Puerts is licensed under the BSD 3-Clause License, except for the third-party components listed in the file 'LICENSE' which may be subject to their corresponding license terms.
* This file is subject to the terms and conditions defined in file 'LICENSE', which is part of this source code package.
*/
(function () {
"use strict";
let events = Object.create(null);
let eventsCount = 0;
function checkListener(listener) {
if (typeof listener !== 'function') {
throw new Error('listener expect a function');
}
}
function on(type, listener, prepend) {
checkListener(listener);
let existing = events[type];
if (existing === undefined) {
events[type] = listener;
++eventsCount;
} else {
if (typeof existing === 'function') {
events[type] = prepend ? [listener, existing] : [existing, listener];
} else if (prepend) {
existing.unshift(listener);
} else {
existing.push(listener);
}
}
}
function off(type, listener) {
checkListener(listener);
const list = events[type];
if (list === undefined)
return;
if (list === listener) {
if (--eventsCount === 0)
events = Object.create(null);
else {
events[type] = undefined;
}
} else if (typeof list !== 'function') {
for (var i = list.length - 1; i >= 0; i--) {
if (list[i] === listener) { //found
if (i === 0)
list.shift();
else {
spliceOne(list, i);
}
if (list.length === 1)
events[type] = list[0];
break;
}
}
}
}
function emit(type, ...args) {
const listener = events[type];
if (listener === undefined)
return false;
if (typeof listener === 'function') {
Reflect.apply(listener, this, args);
} else {
const len = listener.length;
const listeners = arrayClone(listener, len);
for (var i = 0; i < len; ++i)
Reflect.apply(listeners[i], this, args);
}
return true;
}
function arrayClone(arr, n) {
const copy = new Array(n);
for (var i = 0; i < n; ++i)
copy[i] = arr[i];
return copy;
}
function spliceOne(list, index) {
for (; index + 1 < list.length; index++)
list[index] = list[index + 1];
list.pop();
}
puerts.on = on;
puerts.off = off;
puerts.emit = emit;
}());
@@ -0,0 +1 @@
//createInspector(8080)
@@ -0,0 +1,99 @@
var global = global || (function () { return this; }());
(function (global) {
"use strict";
let puerts = global.puerts
let dispatchProtocolMessage = global.__tgjsDispatchProtocolMessage
global.__tgjsDispatchProtocolMessage = undefined;
let setInspectorCallback = global.__tgjsSetInspectorCallback
global.__tgjsSetInspectorCallback = undefined;
const parsedScript = new Map();
let contextInfo
const pendingCommnand = new Map();
function messageHandler(str) {
let msg = JSON.parse(str);
if (msg.method === "Debugger.scriptParsed") {
parsedScript.set(msg.params.scriptId, msg.params.url);
parsedScript.set(msg.params.url, msg.params.scriptId);
} else if ( msg.method === "Runtime.executionContextCreated") {
contextInfo = msg.params.context;
} else if (typeof msg.id === "number") {
if (msg.result && pendingCommnand.has(msg.id)) {
const resolve = pendingCommnand.get(msg.id);
pendingCommnand.delete(msg.id);
resolve(msg.result);
} else {
console.error("unexpect inspector message:" + str);
}
}
//if ( msg.method != "Runtime.consoleAPICalled") {
// console.error("<--", str);
//}
};
let commandId = 0;
function sendCommand(method, params) {
return new Promise((resolve, reject) => {
commandId++;
pendingCommnand.set(commandId, resolve);
//console.error("-->", JSON.stringify({"id":commandId,"method":method,"params":params}));
dispatchProtocolMessage(JSON.stringify({"id":commandId,"method":method,"params":params}));
});
}
let inited = false;
async function enableDebugger() {
if (inited) return;
inited = true;
setInspectorCallback(messageHandler);
await sendCommand("Runtime.enable", {});
await sendCommand("Debugger.enable", {"maxScriptsCacheSize":10000000});
//await sendCommand("Debugger.setPauseOnExceptions",{"state":"none"});
//await sendCommand("Debugger.setAsyncCallStackDepth",{"maxDepth":32});
//await sendCommand("Profiler.enable",{});
//await sendCommand("Runtime.getIsolateId",{});
//await sendCommand("Debugger.setBlackboxPatterns",{"patterns":[]});
//await sendCommand("Runtime.runIfWaitingForDebugger");
}
async function reload(moduleName, url, source) {
await enableDebugger();
let scriptId
if (parsedScript.has(url)) {
scriptId = parsedScript.get(url)
} else {
let win_url = url.replace(/\//g, '\\');
if (parsedScript.has(win_url)) {
scriptId = parsedScript.get(win_url)
}
}
if (scriptId) {
if (typeof source === "string") {
let orgSourceInfo = await sendCommand("Debugger.getScriptSource", {scriptId:"" + scriptId});
source = ("(function (exports, require, module, __filename, __dirname) { " + source + "\n});");
if (orgSourceInfo.scriptSource == source) {
console.log(`source not changed, skip ${url}`);
return;
}
let m = puerts.getModuleByUrl(url);
puerts.emit('HMR.prepare', moduleName, m, url);
let res = await sendCommand("Debugger.setScriptSource", {scriptId:"" + scriptId,scriptSource:source});
puerts.emit('HMR.finish', moduleName, m, url);
//puerts.forceReload(url);
}
} else {
console.warn(`can not find scriptId for ${url}`)
}
};
puerts.__reload = reload;
}(global));
@@ -0,0 +1,29 @@
/*
* Tencent is pleased to support the open source community by making Puerts available.
* Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.
* Puerts is licensed under the BSD 3-Clause License, except for the third-party components listed in the file 'LICENSE' which may be subject to their corresponding license terms.
* This file is subject to the terms and conditions defined in file 'LICENSE', which is part of this source code package.
*/
let puerts = require("puerts");
let loadedModules = Object.create(null);
puerts.registerRequestHandler('requestModuleMethod', (data, onFinished) => {
let split = data.indexOf('#');
let split2 = data.indexOf('#', split + 1);
let moduleName = data.substring(0, split);
let moduleMethodName = data.substring(split + 1, split2);
let invokeArgs = data.substring(split2 + 1);
let module = loadedModules[moduleName];
if (!module) {
module = require(moduleName);
loadedModules[moduleName] = module;
}
let method = module[moduleMethodName];
let args = JSON.parse(invokeArgs);
let result = method.apply(module, args);
onFinished(undefined, JSON.stringify(result));
});
console.log("jit_skeleton.js loaded!!");
@@ -0,0 +1,25 @@
/*
* Tencent is pleased to support the open source community by making Puerts available.
* Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.
* Puerts is licensed under the BSD 3-Clause License, except for the third-party components listed in the file 'LICENSE' which may be subject to their corresponding license terms.
* This file is subject to the terms and conditions defined in file 'LICENSE', which is part of this source code package.
*/
var global = global || (function () { return this; }());
(function (global) {
"use strict";
let requestJitModuleMethod = global.__tgjsRequestJitModuleMethod;
global.__tgjsRequestJitModuleMethod = undefined;
puerts.requestJitModuleMethod = function(moduleName, methodName, callback, ... args) {
let data = moduleName + "#" + methodName + "#" + JSON.stringify(args);
requestJitModuleMethod(data, (err, result) => {
if (err) {
callback(err);
} else {
callback(undefined, JSON.parse(result));
}
});
}
}(global));
@@ -0,0 +1,56 @@
/*
* Tencent is pleased to support the open source community by making Puerts available.
* Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.
* Puerts is licensed under the BSD 3-Clause License, except for the third-party components listed in the file 'LICENSE' which may be subject to their corresponding license terms.
* This file is subject to the terms and conditions defined in file 'LICENSE', which is part of this source code package.
*/
var global = global || (function () { return this; }());
(function (global) {
"use strict";
let levels = ['log', 'info', 'warn', 'error']
let sendRequestSync = puerts.sendRequestSync;
let tgjsLog = global.__tgjsLog || function(nlevel, msg) {
sendRequestSync(levels[nlevel], msg);
}
global.__tgjsLog = undefined;
const console_org = global.console;
var console = {}
function log(level, args) {
tgjsLog(level, Array.prototype.map.call(args, x => {
try {
return x+'';
} catch (err){
return err;
}
}).join(','));
}
console.log = function() {
if (console_org) console_org.log.apply(null, Array.prototype.slice.call(arguments));
log(0, arguments);
}
console.info = function() {
if (console_org) console_org.info.apply(null, Array.prototype.slice.call(arguments));
log(1, arguments);
}
console.warn = function() {
if (console_org) console_org.warn.apply(null, Array.prototype.slice.call(arguments));
log(2, arguments);
}
console.error = function() {
if (console_org) console_org.error.apply(null, Array.prototype.slice.call(arguments));
log(3, arguments);
}
global.puerts.console = console;
global.console = console;
}(global));
@@ -0,0 +1,90 @@
/*
* Tencent is pleased to support the open source community by making Puerts available.
* Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.
* Puerts is licensed under the BSD 3-Clause License, except for the third-party components listed in the file 'LICENSE' which may be subject to their corresponding license terms.
* This file is subject to the terms and conditions defined in file 'LICENSE', which is part of this source code package.
*/
var global = global || (function () { return this; }());
(function (global) {
"use strict";
let puerts = global.puerts = global.puerts || {};
let sendMessage = global.prompt;
puerts.sendRawMessage = function(msg) {
return sendMessage(msg);
}
//TODO:支持多参数,多参数自动用#连接
puerts.sendRequestSync = function(cmd, ...args) {
var req = cmd + "#" + args.join('#');
let ret = sendMessage(req); //oneway ret === "", normal reply === "#msg", error === "info"
if (ret) {
var err;
var rpy;
if (!ret.startsWith('#')) {
err = new Error(ret);
} else {
rpy = ret.substring(1);
}
if (err) throw err;
return rpy;
}
}
let requestHandlers = Object.create(null);
puerts.registerRequestHandler = function(cmd, callback) {
requestHandlers[cmd] = callback;
}
function sendReply(replyId, reply, err) {
let errMsg = err ? (typeof err == 'string' ? err : err.message) : ''
if (replyId) {
puerts.sendRequestSync('onReply', replyId + '#' + (errMsg ? errMsg : ('#' + reply)));
}
}
function handleMessage(cmd, data, replyId) {
let handler = requestHandlers[cmd];
if (!handler) {
return sendReply(replyId, null, "can not find handler for " + cmd);
}
if (replyId) {
handler(data, (err, reply) => sendReply(replyId, reply, err));
} else {
handler(data);
}
}
var lastPollTime = new Date();
setInterval(() => {
let now = new Date();
//puerts.console.log('interval:' + (now - lastPollTime));
lastPollTime = now;
let msg = puerts.sendRequestSync('pollRequest');
let cmd, replyId
if (msg) {
try {
//puerts.console.log('msg:' + msg);
let firstSplit = msg.indexOf('#');
let secondSplit = msg.indexOf('#', firstSplit + 1);
replyId = msg.substring(0, firstSplit);
cmd = msg.substring(firstSplit + 1, secondSplit);
let data = msg.substring(secondSplit + 1);
//puerts.console.warn(replyId);
//puerts.console.log(cmd);
//puerts.console.log(data);
handleMessage(cmd, data, replyId);
} catch(e) {
if (replyId) {
sendReply(replyId, null, e.stack);
} else {
puerts.console.error("handle " + (cmd || "unknow") + " fail, info = " + e.stack);
}
}
}
}, 1);
}(global));
@@ -0,0 +1,250 @@
/*
* Tencent is pleased to support the open source community by making Puerts available.
* Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.
* Puerts is licensed under the BSD 3-Clause License, except for the third-party components listed in the file 'LICENSE' which may be subject to their corresponding license terms.
* This file is subject to the terms and conditions defined in file 'LICENSE', which is part of this source code package.
*/
var global = global || (function () { return this; }());
(function (global) {
"use strict";
let puerts = global.puerts = global.puerts || {};
let sendRequestSync = puerts.sendRequestSync;
function normalize(name) {
if ('./' === name.substr(0,2)) {
name = name.substr(2);
}
return name;
}
let evalScript = global.__tgjsEvalScript || function(script, debugPath) {
return eval(script);
}
global.__tgjsEvalScript = undefined;
let loadModule = global.__tgjsLoadModule;
global.__tgjsLoadModule = undefined;
let searchModule = global.__tgjsSearchModule;
global.__tgjsSearchModule = undefined;
let org_require = global.require;
let findModule = global.__tgjsFindModule;
global.__tgjsFindModule = undefined;
let tmpModuleStorage = [];
function addModule(m) {
for (var i = 0; i < tmpModuleStorage.length; i++) {
if (!tmpModuleStorage[i]) {
tmpModuleStorage[i] = m;
return i;
}
}
return tmpModuleStorage.push(m) - 1;
}
function getModuleBySID(id) {
return tmpModuleStorage[id];
}
let moduleCache = Object.create(null);
let buildinModule = Object.create(null);
function executeModule(fullPath, script, debugPath, sid, isESM, bytecode) {
sid = (typeof sid == 'undefined') ? 0 : sid;
let fullPathInJs = fullPath.replace(/\\/g, '\\\\');
let fullDirInJs = (fullPath.indexOf('/') != -1) ? fullPath.substring(0, fullPath.lastIndexOf("/")) : fullPath.substring(0, fullPath.lastIndexOf("\\")).replace(/\\/g, '\\\\');
let exports = {};
let module = puerts.getModuleBySID(sid);
module.exports = exports;
let wrapped = evalScript(
// Wrap the script in the same way NodeJS does it. It is important since IDEs (VSCode) will use this wrapper pattern
// to enable stepping through original source in-place.
(isESM || bytecode) ? script: "(function (exports, require, module, __filename, __dirname) { " + script + "\n});",
debugPath, isESM, fullPath, bytecode
)
if (isESM) return wrapped;
wrapped(exports, puerts.genRequire(fullDirInJs), module, fullPathInJs, fullDirInJs)
return module.exports;
}
function getESMMain(script) {
let packageConfigure = JSON.parse(script);
return (packageConfigure && packageConfigure.type === "module") ? packageConfigure.main : undefined;
}
function getSourceLengthFromBytecode(buf, isESM) {
let sourceHash = (new Uint32Array(buf))[2];
//console.log(`sourceHash:${sourceHash}`);
const kModuleFlagMask = (1 << 31);
const mask = isESM ? kModuleFlagMask : 0;
// Remove the mask to get the original length
const length = sourceHash & ~mask;
return length;
}
let baseString
function generateEmptyCode(length) {
if (baseString === undefined) {
baseString = " ".repeat(128*1024);
}
if (length <= baseString.length) {
return baseString.slice(0, length);
} else {
const fullString = baseString.repeat(Math.floor(length / baseString.length));
const remainingLength = length % baseString.length;
return fullString.concat(baseString.slice(0, remainingLength));
}
}
function genRequire(requiringDir, outerIsESM) {
let localModuleCache = Object.create(null);
function require(moduleName) {
if (org_require) {
try {
return org_require(moduleName);
} catch (e) {}
}
moduleName = normalize(moduleName);
let forceReload = false;
if ((moduleName in localModuleCache)) {
let m = localModuleCache[moduleName];
if (!m.__forceReload) {
return localModuleCache[moduleName].exports;
} else {
forceReload = true;
}
}
if (moduleName in buildinModule) return buildinModule[moduleName];
let nativeModule = findModule(moduleName);
if (nativeModule) {
buildinModule[moduleName] = nativeModule;
return nativeModule;
}
let moduleInfo = searchModule(moduleName, requiringDir);
if (!moduleInfo) {
throw new Error(`can not find ${moduleName} in ${requiringDir}`);
}
let [fullPath, debugPath] = moduleInfo;
if(debugPath.startsWith("Pak: ")){
debugPath = fullPath
}
let key = fullPath;
if ((key in moduleCache) && !forceReload) {
localModuleCache[moduleName] = moduleCache[key];
return localModuleCache[moduleName].exports;
}
let m = {"exports":{}};
localModuleCache[moduleName] = m;
moduleCache[key] = m;
let sid = addModule(m);
let isESM = outerIsESM === true || fullPath.endsWith(".mjs") || fullPath.endsWith(".mbc");
if (fullPath.endsWith(".cjs") || fullPath.endsWith(".cbc")) isESM = false;
let script = isESM ? undefined : loadModule(fullPath);
let bytecode = undefined;
if (fullPath.endsWith(".mbc") || fullPath.endsWith(".cbc")) {
bytecode = script;
script = generateEmptyCode(getSourceLengthFromBytecode(bytecode));
}
try {
if (fullPath.endsWith(".json")) {
let packageConfigure = JSON.parse(script);
if (fullPath.endsWith("package.json")) {
isESM = packageConfigure.type === "module"
let url = packageConfigure.main || "index.js";
if (isESM) {
let packageExports = packageConfigure.exports && packageConfigure.exports["."];
if (packageExports)
url =
(packageExports["default"] && packageExports["default"]["require"]) ||
(packageExports["require"] && packageExports["require"]["default"]) ||
packageExports["require"];
if (!url) {
throw new Error("can not require a esm in cjs module!");
}
}
let fullDirInJs = (fullPath.indexOf('/') != -1) ? fullPath.substring(0, fullPath.lastIndexOf("/")) : fullPath.substring(0, fullPath.lastIndexOf("\\")).replace(/\\/g, '\\\\');
let tmpRequire = genRequire(fullDirInJs, isESM);
let r = tmpRequire(url);
m.exports = r;
} else {
m.exports = packageConfigure;
}
} else {
let r = executeModule(fullPath, script, debugPath, sid, isESM, bytecode);
if (isESM) {
m.exports = r;
}
}
} catch(e) {
localModuleCache[moduleName] = undefined;
moduleCache[key] = undefined;
throw e;
} finally {
tmpModuleStorage[sid] = undefined;
}
return m.exports;
}
return require;
}
function registerBuildinModule(name, module) {
buildinModule[name] = module;
}
function forceReload(reloadModuleKey) {
if (reloadModuleKey) {
reloadModuleKey = normalize(reloadModuleKey);
}
let reloaded = false;
for(var moduleKey in moduleCache) {
if (!reloadModuleKey || (reloadModuleKey == moduleKey)) {
moduleCache[moduleKey].__forceReload = true;
reloaded = true;
if (reloadModuleKey) break;
}
}
if (!reloaded && reloadModuleKey) {
console.warn(`reload not loaded module: ${reloadModuleKey}!`);
}
}
function getModuleByUrl(url) {
if (url) {
url = normalize(url);
return moduleCache[url];
}
}
registerBuildinModule("puerts", puerts)
puerts.genRequire = genRequire;
puerts.getESMMain = getESMMain;
puerts.__require = genRequire("");
global.require = puerts.__require;
puerts.getModuleBySID = getModuleBySID;
puerts.registerBuildinModule = registerBuildinModule;
puerts.loadModule = loadModule;
puerts.forceReload = forceReload;
puerts.getModuleByUrl = getModuleByUrl;
puerts.generateEmptyCode = generateEmptyCode;
}(global));
@@ -0,0 +1,51 @@
/*
* Tencent is pleased to support the open source community by making Puerts available.
* Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.
* Puerts is licensed under the BSD 3-Clause License, except for the third-party components listed in the file 'LICENSE' which may be subject to their corresponding license terms.
* This file is subject to the terms and conditions defined in file 'LICENSE', which is part of this source code package.
*/
var global = global || (function () { return this; }());
(function (global) {
"use strict";
function pathBasename(path) {
const regex = /^(.*[\/\\])?(.+)$/;
const match = path.match(regex);
return match ? match[2] : '';
}
function pathDirname(path) {
const regex = /^(.*[\/\\])?/;
const match = path.match(regex);
return match ? (match[1] || '.').replace(/[\/\\]$/, '') : '.';
}
const org_load = global.puerts.load;
const dll_ext = global.puerts.dll_ext;
const moduleCache = {};
function load(filepath) {
const iswin = dll_ext === '.dll';
const filename = pathBasename(filepath);
if (filepath && typeof filepath === 'string' && filename.indexOf('.') === -1) {
const prefix = iswin ? '' : 'lib';
filepath = `${pathDirname(filepath)}${iswin? '\\' : '/'}${prefix}${filename}${dll_ext}`;
}
if (!(filepath in moduleCache)) {
const module_name = org_load(filepath);
moduleCache[filepath] = new Proxy({__name : module_name}, {
get: function(classCache, className) {
if (!(className in classCache)) {
classCache[className] = puerts.loadCPPType(`${module_name}.${className}`);
}
return classCache[className];
}
});
}
return moduleCache[filepath];
}
global.puerts.load = load;
}(global));
@@ -0,0 +1,12 @@
/*
* Tencent is pleased to support the open source community by making Puerts available.
* Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.
* Puerts is licensed under the BSD 3-Clause License, except for the third-party components listed in the file 'LICENSE' which may be subject to their corresponding license terms.
* This file is subject to the terms and conditions defined in file 'LICENSE', which is part of this source code package.
*/
var global = global || (function () { return this; }());
(function (global) {
"use strict";
global.process = { env: { NODE_ENV: 'development' } };
}(global));
@@ -0,0 +1,83 @@
/*
* Tencent is pleased to support the open source community by making Puerts available.
* Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.
* Puerts is licensed under the BSD 3-Clause License, except for the third-party components listed in the file 'LICENSE' which may be subject to their corresponding license terms.
* This file is subject to the terms and conditions defined in file 'LICENSE', which is part of this source code package.
*/
var global = global || (function () { return this; }());
(function (global) {
"use strict";
const kPromiseRejectWithNoHandler = 0;
const kPromiseHandlerAddedAfterReject = 1;
const kPromiseRejectAfterResolved = 2;
const kPromiseResolveAfterResolved = 3;
global.__tgjsSetPromiseRejectCallback(promiseRejectHandler)
global.__tgjsSetPromiseRejectCallback = undefined;
const maybeUnhandledRejection = new WeakMap();
function promiseRejectHandler(type, promise, reason) {
switch (type) {
case kPromiseRejectWithNoHandler:
maybeUnhandledRejection.set(promise, {
reason,
}); //maybe unhandledRejection
Promise.resolve()
.then(() => Promise.resolve()) // run after all microtasks
.then(_ => unhandledRejection(promise, reason));
break;
case kPromiseHandlerAddedAfterReject:
handlerAddedAfterReject(promise);
break;
case kPromiseResolveAfterResolved:
console.error('kPromiseResolveAfterResolved', promise, reason);
break;
case kPromiseRejectAfterResolved:
console.error('kPromiseRejectAfterResolved', promise, reason);
break;
}
}
function unhandledRejection(promise, reason) {
const promiseInfo = maybeUnhandledRejection.get(promise);
if (promiseInfo === undefined) {
return;
}
if (!puerts.emit('unhandledRejection', promiseInfo.reason, promise)) {
unhandledRejectionWarning(reason);
}
}
function unhandledRejectionWarning(reason) {
try {
if (reason instanceof Error) {
console.warn('unhandledRejection', reason, reason.stack);
} else {
console.warn('unhandledRejection', reason);
}
} catch {}
}
function handlerAddedAfterReject(promise) {
const promiseInfo = maybeUnhandledRejection.get(promise);
if (promiseInfo !== undefined) { // cancel
maybeUnhandledRejection.delete(promise);
}
}
const org_setTimeout = setTimeout;
function setTimeout_p(handler, timeout, ...args) {
return org_setTimeout(() => handler(...args), timeout);
}
global.setTimeout = setTimeout_p;
const org_setInterval = setInterval;
function setInterval_p(handler, timeout, ...args) {
return org_setInterval(() => handler(...args), timeout);
}
global.setInterval = setInterval_p;
}(global));
@@ -0,0 +1,985 @@
/*
* Tencent is pleased to support the open source community by making Puerts available.
* Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.
* Puerts is licensed under the BSD 3-Clause License, except for the third-party components listed in the file 'LICENSE' which may be subject to their corresponding license terms.
* This file is subject to the terms and conditions defined in file 'LICENSE', which is part of this source code package.
*/
var global = global || (function () { return this; }());
(function (global) {
"use strict";
let loadUEType = global.puerts.loadUEType;
let loadCPPType = global.puerts.loadCPPType;
let cache = Object.create(null);
let UE = new Proxy(cache, {
get : function(classWrapers, name)
{
let value = classWrapers[name];
if (value === undefined)
{
value = loadUEType(name);
classWrapers[name] = value;
}
return value;
}
});
const TNAMESPACE = 0;
const TENUM = 1
const TBLUEPRINT = 2;
const TSTRUCT = 3
function createNamespaceOrClass(path, parentDir, nodeType) {
return new Proxy({__path: path, __parent:parentDir, __type:nodeType}, {
get: function(node, name) {
if (!(name in node)) {
if (name === '__parent' || name === '__path') return undefined;
if (node.__type == TENUM) { // auto load
node[name] = createNamespaceOrClass(name, node, TNAMESPACE);
blueprint_load(node[name]);
} else {
let newNodeType = node.__type;
if (newNodeType === TNAMESPACE) {
let path = `/${name}.${name}`
let c = node;
while (c && c.__path) {
path = `/${c.__path}${path}`
c = c.__parent;
}
const obj = UE.Object.Load(path, true);
if (obj) {
const typeName = obj.GetClass().GetName();
if (typeName === 'UserDefinedEnum') {
newNodeType = TENUM;
} else if (typeName === 'UserDefinedStruct') {
newNodeType = TSTRUCT;
} else {
newNodeType = TBLUEPRINT;
}
}
}
node[name] = createNamespaceOrClass(name, node, newNodeType);
}
}
return node[name];
}
});
}
cache["Game"] = createNamespaceOrClass("Game", undefined, TNAMESPACE);
puerts.registerBuildinModule('ue', UE);
global.UE = UE;
let CPP = new Proxy(cache, {
get: function(classWrapers, name) {
let value = classWrapers[name];
if (value === undefined)
{
value = loadCPPType(name);
classWrapers[name] = value;
}
return value;
}
});
puerts.registerBuildinModule('cpp', CPP);
global.CPP = CPP;
function ref(x) {
return [x];
}
function unref(r) {
return r[0];
}
function setref(x, val) {
x[0] = val;
}
cache.NewObject = global.__tgjsNewObject;
global.__tgjsNewObject = undefined;
cache.NewStruct = global.__tgjsNewStruct;
global.__tgjsNewStruct = undefined;
puerts.$ref = ref;
puerts.$unref = unref;
puerts.$set = setref;
puerts.merge = global.__tgjsMergeObject;
global.__tgjsMergeObject = undefined;
cache.FNameLiteral = global.__tgjsFNameToArrayBuffer;
global.__tgjsFNameToArrayBuffer = undefined;
let rawmakeclass = global.__tgjsMakeUClass
global.__tgjsMakeUClass = undefined;
puerts.setJsTakeRef = global.__tgjsSetJsTakeRef
global.__tgjsSetJsTakeRef = undefined
function defaultUeConstructor(){};
function makeUClass(cls) {
if (typeof cls === 'function' && !cls.hasOwnProperty('arguments')
&& typeof cls.StaticClass === 'function'
&& !cls.hasOwnProperty('StaticClass')) {
//let parentClass = Object.getPrototypeOf(cls.prototype).constructor;
let proto = cls.prototype;
let methods = Object.create(null);
let names = Object.getOwnPropertyNames(proto);
let ueConstructor = defaultUeConstructor;
for(var i = 0; i < names.length; ++i) {
let name = names[i];
let descriptor = Object.getOwnPropertyDescriptor(proto, name);
if (typeof descriptor.value === 'function' && name != "constructor") {
if (name === 'Constructor') {
ueConstructor = proto[name];
} else {
methods[name] = proto[name];
}
}
}
return rawmakeclass(ueConstructor, proto, `${cls.name}_C`, methods, cls.StaticClass());
} else {
throw new Error("invalid class");
}
}
puerts.makeUClass = makeUClass;
let UEClassToJSClass = global.__tgjsUEClassToJSClass;
global.__tgjsUEClassToJSClass = undefined;
function blueprint(path) {
console.warn('deprecated! use blueprint.tojs instead');
let ufield = UE.Field.Load(path, true);
if (ufield) {
let jsclass = UEClassToJSClass(ufield);
jsclass.__puerts_ufield = ufield;
return jsclass;
} else {
throw new Error("can not load type in " + path);
}
}
blueprint.tojs = UEClassToJSClass;
let __tgjsMixin = global.__tgjsMixin;
global.__tgjsMixin = undefined;
function mixin(to, mixinClass, config) {
config = config || {};
let mixinMethods = Object.create(null);
let names = Object.getOwnPropertyNames(mixinClass.prototype);
for(var i = 0; i < names.length; ++i) {
let name = names[i];
let descriptor = Object.getOwnPropertyDescriptor(mixinClass.prototype, name);
if (typeof descriptor.value === 'function' && name != "constructor") {
mixinMethods[name] = mixinClass.prototype[name];
}
}
let cls = __tgjsMixin(to.StaticClass(), mixinMethods, config.objectTakeByNative, config.inherit, config.noMixinedWarning);
let jsCls = UEClassToJSClass(cls);
Object.getOwnPropertyNames(mixinMethods).forEach(name => {
if (!jsCls.prototype.hasOwnProperty(name)) {
Object.defineProperty(
jsCls.prototype,
name,
Object.getOwnPropertyDescriptor(mixinMethods, name) ||
Object.create(null)
);
}
});
if (config.inherit) {
config.generatedClass = cls;
}
return jsCls;
}
blueprint.mixin = mixin;
function unmixin(to) {
__tgjsMixin(to.StaticClass(), {}, undefined, undefined, undefined, true);
}
blueprint.unmixin = unmixin;
function blueprint_load(cls) {
if (cls.__path) {
let c = cls
let path = `.${c.__path}`
c = c.__parent;
while (c && c.__path) {
path = `/${c.__path}${path}`
c = c.__parent;
}
let ufield = UE.Field.Load(path, true);
if (!ufield) {
throw new Error(`load ${path} fail!`);
}
let jsclass = UEClassToJSClass(ufield);
jsclass.__puerts_ufield = ufield;
if (cls.__parent) {
jsclass.__parent = cls.__parent;
jsclass.__name = cls.__path;
cls.__parent[cls.__path] = jsclass;
}
} else {
throw new Error("argument #0 is not a unload type");
}
}
blueprint.load = blueprint_load;
function blueprint_unload(cls) {
if (cls.__puerts_ufield) {
cls.__puerts_ufield = undefined;
if (cls.__parent) {
cls.__parent[cls.__name] = createNamespaceOrClass(cls.__name, cls.__parent);
}
}
}
blueprint.unload = blueprint_unload;
puerts.blueprint = blueprint;
const newContainer = global.__tgjsNewContainer;
global.__tgjsNewContainer = undefined;
function translateType(t) {
if (typeof t !== 'number') {
if (t.hasOwnProperty('__puerts_ufield')) {
return t.__puerts_ufield
} else {
return t.StaticClass();
}
} else {
return t;
}
}
function NewArray(t1) {
t1 = translateType(t1);
var ret = newContainer(0, t1);
if (!("[Symbol.iterator]" in ret)) {
ret.constructor.prototype[Symbol.iterator] = function*() {
let index = 0;
let num = this.Num();
while (index < num) {
yield this.Get(index);
index++;
}
}
}
return ret;
}
function NewSet(t1) {
t1 = translateType(t1);
var ret = newContainer(1, t1);
if (!("[Symbol.iterator]" in ret)) {
ret.constructor.prototype[Symbol.iterator] = function*() {
let index = 0;
let maxIndex = this.GetMaxIndex();
while (index < maxIndex) {
if (this.IsValidIndex(index)) {
yield this.Get(index);
}
index++;
}
}
}
return ret;
}
function NewMap(t1, t2) {
t1 = translateType(t1);
t2 = translateType(t2);
var ret = newContainer(2, t1, t2);
if (!("[Symbol.iterator]" in ret)) {
ret.constructor.prototype[Symbol.iterator] = function*() {
let index = 0;
let maxIndex = this.GetMaxIndex();
while (index < maxIndex) {
if (this.IsValidIndex(index)) {
let key = this.GetKey(index);
let value = this.Get(key);
yield [key, value];
}
index++;
}
}
}
return ret;
}
cache.BuiltinBool = 0;
cache.BuiltinByte = 1;
cache.BuiltinInt = 2;
cache.BuiltinFloat = 3;
cache.BuiltinDouble = 4;
cache.BuiltinInt64 = 5;
cache.BuiltinString = 6;
cache.BuiltinText = 7;
cache.BuiltinName = 8;
// call once to inject iterators to constructor
NewArray(cache.BuiltinInt);
NewSet(cache.BuiltinInt);
NewMap(cache.BuiltinInt, cache.BuiltinInt);
cache.NewArray = NewArray;
cache.NewSet = NewSet;
cache.NewMap = NewMap;
const FunctionFlags = {
FUNC_None : 0x00000000,
FUNC_Final : 0x00000001, // Function is final (prebindable, non-overridable function).
FUNC_RequiredAPI : 0x00000002, // Indicates this function is DLL exported/imported.
FUNC_BlueprintAuthorityOnly: 0x00000004, // Function will only run if the object has network authority
FUNC_BlueprintCosmetic : 0x00000008, // Function is cosmetic in nature and should not be invoked on dedicated servers
// FUNC_ : 0x00000010, // unused.
// FUNC_ : 0x00000020, // unused.
FUNC_Net : 0x00000040, // Function is network-replicated.
FUNC_NetReliable : 0x00000080, // Function should be sent reliably on the network.
FUNC_NetRequest : 0x00000100, // Function is sent to a net service
FUNC_Exec : 0x00000200, // Executable from command line.
FUNC_Native : 0x00000400, // Native function.
FUNC_Event : 0x00000800, // Event function.
FUNC_NetResponse : 0x00001000, // Function response from a net service
FUNC_Static : 0x00002000, // Static function.
FUNC_NetMulticast : 0x00004000, // Function is networked multicast Server -> All Clients
FUNC_UbergraphFunction : 0x00008000, // Function is used as the merge 'ubergraph' for a blueprint, only assigned when using the persistent 'ubergraph' frame
FUNC_MulticastDelegate : 0x00010000, // Function is a multi-cast delegate signature (also requires FUNC_Delegate to be set!)
FUNC_Public : 0x00020000, // Function is accessible in all classes (if overridden, parameters must remain unchanged).
FUNC_Private : 0x00040000, // Function is accessible only in the class it is defined in (cannot be overridden, but function name may be reused in subclasses. IOW: if overridden, parameters don't need to match, and Super.Func() cannot be accessed since it's private.)
FUNC_Protected : 0x00080000, // Function is accessible only in the class it is defined in and subclasses (if overridden, parameters much remain unchanged).
FUNC_Delegate : 0x00100000, // Function is delegate signature (either single-cast or multi-cast, depending on whether FUNC_MulticastDelegate is set.)
FUNC_NetServer : 0x00200000, // Function is executed on servers (set by replication code if passes check)
FUNC_HasOutParms : 0x00400000, // function has out (pass by reference) parameters
FUNC_HasDefaults : 0x00800000, // function has structs that contain defaults
FUNC_NetClient : 0x01000000, // function is executed on clients
FUNC_DLLImport : 0x02000000, // function is imported from a DLL
FUNC_BlueprintCallable : 0x04000000, // function can be called from blueprint code
FUNC_BlueprintEvent : 0x08000000, // function can be overridden/implemented from a blueprint
FUNC_BlueprintPure : 0x10000000, // function can be called from blueprint code, and is also pure (produces no side effects). If you set this, you should set FUNC_BlueprintCallable as well.
FUNC_EditorOnly : 0x20000000, // function can only be called from an editor scrippt.
FUNC_Const : 0x40000000, // function can be called from blueprint code, and only reads state (never writes state)
FUNC_NetValidate : 0x80000000, // function must supply a _Validate implementation
FUNC_AllFlags : 0xFFFFFFFF,
};
Object.freeze(FunctionFlags);
const FunctionExportFlags =
{
FUNCEXPORT_Final :0x00000001, // function declaration included "final" keyword. Used to differentiate between functions that have FUNC_Final only because they're private
// =0x00000002,
// =0x00000004,
FUNCEXPORT_RequiredAPI :0x00000008, // Function should be exported as a public API function
FUNCEXPORT_Inline :0x00000010, // export as an inline static C++ function
FUNCEXPORT_CppStatic :0x00000020, // Export as a real C++ static function, causing thunks to call via ClassName::FuncName instead of this->FuncName
FUNCEXPORT_CustomThunk :0x00000040, // Export no thunk function; the user will manually define a custom one
// =0x00000080,
// =0x00000100,
};
Object.freeze(FunctionExportFlags)
const ELifetimeCondition = {
"COND_InitialOnly" : 1 , // This property will only attempt to send on the initial bunch
"COND_OwnerOnly" : 2 , // This property will only send to the actor's owner
"COND_SkipOwner" : 3 , // This property send to every connection EXCEPT the owner
"COND_SimulatedOnly" : 4 , // This property will only send to simulated actors
"COND_AutonomousOnly" : 5 , // This property will only send to autonomous actors
"COND_SimulatedOrPhysics" : 6 , // This property will send to simulated OR bRepPhysics actors
"COND_InitialOrOwner" : 7 , // This property will send on the initial packet, or to the actors owner
"COND_Custom" : 8 , // This property has no particular condition, but wants the ability to toggle on/off via SetCustomIsActiveOverride
"COND_ReplayOrOwner" : 9 , // This property will only send to the replay connection, or to the actors owner
"COND_ReplayOnly" : 10 , // This property will only send to the replay connection
"COND_SimulatedOnlyNoReplay" : 11 , // This property will send to actors only, but not to replay connections
"COND_SimulatedOrPhysicsNoReplay" : 12 , // This property will send to simulated Or bRepPhysics actors, but not to replay connections
"COND_SkipReplay" : 13 , // This property will not send to the replay connection
"COND_Never" : 15 , // This property will never be replicated
}
Object.freeze(ELifetimeCondition);
const ClassFlags = {
CLASS_None: 0x00000000,
/** Class is abstract and can't be instantiated directly. */
CLASS_Abstract: 0x00000001,
/** Save object configuration only to Default INIs, never to local INIs. Must be combined with CLASS_Config */
CLASS_DefaultConfig: 0x00000002,
/** Load object configuration at construction time. */
CLASS_Config: 0x00000004,
/** This object type can't be saved; null it out at save time. */
CLASS_Transient: 0x00000008,
/** Successfully parsed. */
CLASS_Parsed: 0x00000010,
/** */
CLASS_MatchedSerializers: 0x00000020,
/** Indicates that the config settings for this class will be saved to Project/User*.ini (similar to CLASS_GlobalUserConfig) */
CLASS_ProjectUserConfig: 0x00000040,
/** Class is a native class - native interfaces will have CLASS_Native set, but not RF_MarkAsNative */
CLASS_Native: 0x00000080,
/** Don't export to C++ header. */
CLASS_NoExport: 0x00000100,
/** Do not allow users to create in the editor. */
CLASS_NotPlaceable: 0x00000200,
/** Handle object configuration on a per-object basis, rather than per-class. */
CLASS_PerObjectConfig: 0x00000400,
/** Whether SetUpRuntimeReplicationData still needs to be called for this class */
CLASS_ReplicationDataIsSetUp: 0x00000800,
/** Class can be constructed from editinline New button. */
CLASS_EditInlineNew: 0x00001000,
/** Display properties in the editor without using categories. */
CLASS_CollapseCategories: 0x00002000,
/** Class is an interface **/
CLASS_Interface: 0x00004000,
/** Do not export a constructor for this class, assuming it is in the cpptext **/
CLASS_CustomConstructor: 0x00008000,
/** all properties and functions in this class are const and should be exported as const */
CLASS_Const: 0x00010000,
/** Class flag indicating the class is having its layout changed, and therefore is not ready for a CDO to be created */
CLASS_LayoutChanging: 0x00020000,
/** Indicates that the class was created from blueprint source material */
CLASS_CompiledFromBlueprint: 0x00040000,
/** Indicates that only the bare minimum bits of this class should be DLL exported/imported */
CLASS_MinimalAPI: 0x00080000,
/** Indicates this class must be DLL exported/imported (along with all of it's members) */
CLASS_RequiredAPI: 0x00100000,
/** Indicates that references to this class default to instanced. Used to be subclasses of UComponent, but now can be any UObject */
CLASS_DefaultToInstanced: 0x00200000,
/** Indicates that the parent token stream has been merged with ours. */
CLASS_TokenStreamAssembled: 0x00400000,
/** Class has component properties. */
CLASS_HasInstancedReference: 0x00800000,
/** Don't show this class in the editor class browser or edit inline new menus. */
CLASS_Hidden: 0x01000000,
/** Don't save objects of this class when serializing */
CLASS_Deprecated: 0x02000000,
/** Class not shown in editor drop down for class selection */
CLASS_HideDropDown: 0x04000000,
/** Class settings are saved to <AppData>/..../Blah.ini (as opposed to CLASS_DefaultConfig) */
CLASS_GlobalUserConfig: 0x08000000,
/** Class was declared directly in C++ and has no boilerplate generated by UnrealHeaderTool */
CLASS_Intrinsic : 0x10000000,
/** Class has already been constructed (maybe in a previous DLL version before hot-reload). */
CLASS_Constructed: 0x20000000,
/** Indicates that object configuration will not check against ini base/defaults when serialized */
CLASS_ConfigDoNotCheckDefaults: 0x40000000,
/** Class has been consigned to oblivion as part of a blueprint recompile, and a newer version currently exists. */
CLASS_NewerVersionExists: 0x80000000,
}
const PropertyFlags =
{
CPF_None : 0,
CPF_Edit : 0x0000000000000001, ///< Property is user-settable in the editor.
CPF_ConstParm : 0x0000000000000002, ///< This is a constant function parameter
CPF_BlueprintVisible : 0x0000000000000004, ///< This property can be read by blueprint code
CPF_ExportObject : 0x0000000000000008, ///< Object can be exported with actor.
CPF_BlueprintReadOnly : 0x0000000000000010, ///< This property cannot be modified by blueprint code
CPF_Net : 0x0000000000000020, ///< Property is relevant to network replication.
CPF_EditFixedSize : 0x0000000000000040, ///< Indicates that elements of an array can be modified, but its size cannot be changed.
CPF_Parm : 0x0000000000000080, ///< Function/When call parameter.
CPF_OutParm : 0x0000000000000100, ///< Value is copied out after function call.
CPF_ZeroConstructor : 0x0000000000000200, ///< memset is fine for construction
CPF_ReturnParm : 0x0000000000000400, ///< Return value.
CPF_DisableEditOnTemplate : 0x0000000000000800, ///< Disable editing of this property on an archetype/sub-blueprint
//CPF_ : 0x0000000000001000, ///<
CPF_Transient : 0x0000000000002000, ///< Property is transient: shouldn't be saved or loaded, except for Blueprint CDOs.
CPF_Config : 0x0000000000004000, ///< Property should be loaded/saved as permanent profile.
//CPF_ : 0x0000000000008000, ///<
CPF_DisableEditOnInstance : 0x0000000000010000, ///< Disable editing on an instance of this class
CPF_EditConst : 0x0000000000020000, ///< Property is uneditable in the editor.
CPF_GlobalConfig : 0x0000000000040000, ///< Load config from base class, not subclass.
CPF_InstancedReference : 0x0000000000080000, ///< Property is a component references.
//CPF_ : 0x0000000000100000, ///<
CPF_DuplicateTransient : 0x0000000000200000, ///< Property should always be reset to the default value during any type of duplication (copy/paste, binary duplication, etc.)
//CPF_ : 0x0000000000400000, ///<
//CPF_ : 0x0000000000800000, ///<
CPF_SaveGame : 0x0000000001000000, ///< Property should be serialized for save games, this is only checked for game-specific archives with ArIsSaveGame
CPF_NoClear : 0x0000000002000000, ///< Hide clear (and browse) button.
//CPF_ : 0x0000000004000000, ///<
CPF_ReferenceParm : 0x0000000008000000, ///< Value is passed by reference; CPF_OutParam and CPF_Param should also be set.
CPF_BlueprintAssignable : 0x0000000010000000, ///< MC Delegates only. Property should be exposed for assigning in blueprint code
CPF_Deprecated : 0x0000000020000000, ///< Property is deprecated. Read it from an archive, but don't save it.
CPF_IsPlainOldData : 0x0000000040000000, ///< If this is set, then the property can be memcopied instead of CopyCompleteValue / CopySingleValue
CPF_RepSkip : 0x0000000080000000, ///< Not replicated. For non replicated properties in replicated structs
CPF_RepNotify : 0x0000000100000000, ///< Notify actors when a property is replicated
CPF_Interp : 0x0000000200000000, ///< interpolatable property for use with matinee
CPF_NonTransactional : 0x0000000400000000, ///< Property isn't transacted
CPF_EditorOnly : 0x0000000800000000, ///< Property should only be loaded in the editor
CPF_NoDestructor : 0x0000001000000000, ///< No destructor
//CPF_ : 0x0000002000000000, ///<
CPF_AutoWeak : 0x0000004000000000, ///< Only used for weak pointers, means the export type is autoweak
CPF_ContainsInstancedReference : 0x0000008000000000, ///< Property contains component references.
CPF_AssetRegistrySearchable : 0x0000010000000000, ///< asset instances will add properties with this flag to the asset registry automatically
CPF_SimpleDisplay : 0x0000020000000000, ///< The property is visible by default in the editor details view
CPF_AdvancedDisplay : 0x0000040000000000, ///< The property is advanced and not visible by default in the editor details view
CPF_Protected : 0x0000080000000000, ///< property is protected from the perspective of script
CPF_BlueprintCallable : 0x0000100000000000, ///< MC Delegates only. Property should be exposed for calling in blueprint code
CPF_BlueprintAuthorityOnly : 0x0000200000000000, ///< MC Delegates only. This delegate accepts (only in blueprint) only events with BlueprintAuthorityOnly.
CPF_TextExportTransient : 0x0000400000000000, ///< Property shouldn't be exported to text format (e.g. copy/paste)
CPF_NonPIEDuplicateTransient : 0x0000800000000000, ///< Property should only be copied in PIE
CPF_ExposeOnSpawn : 0x0001000000000000, ///< Property is exposed on spawn
CPF_PersistentInstance : 0x0002000000000000, ///< A object referenced by the property is duplicated like a component. (Each actor should have an own instance.)
CPF_UObjectWrapper : 0x0004000000000000, ///< Property was parsed as a wrapper class like TSubclassOf<T>, FScriptInterface etc., rather than a USomething*
CPF_HasGetValueTypeHash : 0x0008000000000000, ///< This property can generate a meaningful hash value.
CPF_NativeAccessSpecifierPublic : 0x0010000000000000, ///< Public native access specifier
CPF_NativeAccessSpecifierProtected : 0x0020000000000000, ///< Protected native access specifier
CPF_NativeAccessSpecifierPrivate : 0x0040000000000000, ///< Private native access specifier
CPF_SkipSerialization : 0x0080000000000000, ///< Property shouldn't be serialized, can still be exported to text
}
function dummyDecorator() {
return () => {};
}
cache.rpc = {
"FunctionFlags" : FunctionFlags,
"PropertyFlags" : PropertyFlags,
"ELifetimeCondition" : ELifetimeCondition,
"flags" : dummyDecorator,
"condition" : dummyDecorator
}
const MetaDataInst = '';
cache.uclass = {
// the class specifier
"ClassGroup": MetaDataInst,
"Within": MetaDataInst,
"BlueprintType": MetaDataInst,
"NotBlueprintType": MetaDataInst,
"Blueprintable": MetaDataInst,
"NotBlueprintable": MetaDataInst,
"MinimalAPI": MetaDataInst,
"customConstructor": MetaDataInst,
"Intrinsic": MetaDataInst,
"noexport": MetaDataInst,
"placeable": MetaDataInst,
"notplaceable": MetaDataInst,
"DefaultToInstanced": MetaDataInst,
"Const": MetaDataInst,
"Abstract": MetaDataInst,
"deprecated": MetaDataInst,
"Transient": MetaDataInst,
"nonTransient": MetaDataInst,
"config": MetaDataInst,
"perObjectConfig": MetaDataInst,
"configdonotcheckdefaults": MetaDataInst,
"defaultconfig": MetaDataInst,
"editinlinenew": MetaDataInst,
"noteditinlinenew": MetaDataInst,
"hidedropdown": MetaDataInst,
"showCategories": MetaDataInst,
"hideCategories": MetaDataInst,
"ComponentWrapperClass": MetaDataInst,
"showFunctions": MetaDataInst,
"hideFunctions": MetaDataInst,
"autoExpandCategories": MetaDataInst,
"autoCollapseCategories": MetaDataInst,
"dontAutoCollapseCategories": MetaDataInst,
"collapseCategories": MetaDataInst,
"dontCollapseCategories": MetaDataInst,
"AdvancedClassDisplay": MetaDataInst,
"ConversionRoot": MetaDataInst,
"Experimental": MetaDataInst,
"EarlyAccessPreview": MetaDataInst,
"SparseClassDataType": MetaDataInst,
"CustomThunkTemplates": MetaDataInst,
// decorator to add class specifier
"uclass": dummyDecorator,
// metadata of class
"ToolTip": MetaDataInst,
"ShortTooltip": MetaDataInst,
"DocumentationPolicy": MetaDataInst,
"BlueprintSpawnableComponent": MetaDataInst,
"ChildCanTick": MetaDataInst,
"ChildCannotTick": MetaDataInst,
"IgnoreCategoryKeywordsInSubclasses": MetaDataInst,
"DeprecatedNode": MetaDataInst,
"DeprecationMessage": MetaDataInst,
"DisplayName": MetaDataInst,
"ScriptName": MetaDataInst,
"IsBlueprintBase": MetaDataInst,
"KismetHideOverrides": MetaDataInst,
"ProhibitedInterfaces": MetaDataInst,
"RestrictedToClasses": MetaDataInst,
"ShowWorldContextPin": MetaDataInst,
"DontUseGenericSpawnObject": MetaDataInst,
"ExposedAsyncProxy": MetaDataInst,
"BlueprintThreadSafe": MetaDataInst,
"UsesHierarchy": MetaDataInst,
// decorator to add class metadata
"umeta": dummyDecorator
}
cache.ufunction = {
// the function specifier
"BlueprintImplementableEvent": MetaDataInst,
"BlueprintNativeEvent": MetaDataInst,
"SealedEvent": MetaDataInst,
"Exec": MetaDataInst,
"Server": MetaDataInst,
"Client": MetaDataInst,
"NetMulticast": MetaDataInst,
"Reliable": MetaDataInst,
"Unreliable": MetaDataInst,
"BlueprintPure": MetaDataInst,
"BlueprintCallable": MetaDataInst,
"BlueprintGetter": MetaDataInst,
"BlueprintSetter": MetaDataInst,
"BlueprintAuthorityOnly": MetaDataInst,
"BlueprintCosmetic": MetaDataInst,
"BlueprintInternalUseOnly": MetaDataInst,
"CallInEditor": MetaDataInst,
"CustomThunk": MetaDataInst,
"Category": MetaDataInst,
"WithValidation": MetaDataInst,
"ServiceRequest": MetaDataInst,
"ServiceResponse": MetaDataInst,
"Variadic": MetaDataInst,
"ReturnDisplayName": MetaDataInst,
"InternalUseParam": MetaDataInst,
// decorator to add function specifier
"ufunction": dummyDecorator,
// type of metadata specifier
"ToolTip": MetaDataInst,
"ShortTooltip": MetaDataInst,
"DocumentationPolicy": MetaDataInst,
"AdvancedDisplay": MetaDataInst,
"ArrayParm": MetaDataInst,
"ArrayTypeDependentParams": MetaDataInst,
"AutoCreateRefTerm": MetaDataInst,
"BlueprintProtected": MetaDataInst,
"CallableWithoutWorldContext": MetaDataInst,
"CommutativeAssociativeBinaryOperator": MetaDataInst,
"CompactNodeTitle": MetaDataInst,
"CustomStructureParam": MetaDataInst,
"DefaultToSelf": MetaDataInst,
"DeprecatedFunction": MetaDataInst,
"DeprecationMessage": MetaDataInst, //, (Commented out so as to avoid duplicate name with version in the Class section, but still show in the function section)
"ExpandEnumAsExecs": MetaDataInst,
"ExpandBoolAsExecs": MetaDataInst,
"DisplayName": MetaDataInst, //, (Commented out so as to avoid duplicate name with version in the Class section, but still show in the function section)
"ScriptName": MetaDataInst, // (Commented out so as to avoid duplicate name with version in the Class section, but still show in the function section)
"ScriptNoExport": MetaDataInst, //, (Commented out so as to avoid duplicate name with version in the Property section, but still show in the function section)
"ScriptMethod": MetaDataInst,
"ScriptMethodSelfReturn": MetaDataInst,
"ScriptOperator": MetaDataInst,
"ScriptConstant": MetaDataInst,
"ScriptConstantHost": MetaDataInst,
"HidePin": MetaDataInst,
"HideSpawnParms": MetaDataInst,
"Keywords": MetaDataInst,
"Latent": MetaDataInst,
"LatentInfo": MetaDataInst,
"MaterialParameterCollectionFunction": MetaDataInst,
"NativeBreakFunc": MetaDataInst,
"NativeMakeFunc": MetaDataInst,
"UnsafeDuringActorConstruction": MetaDataInst,
"WorldContext": MetaDataInst,
"BlueprintAutocast": MetaDataInst,
"NotBlueprintThreadSafe": MetaDataInst,
"DeterminesOutputType": MetaDataInst,
"DynamicOutputParam": MetaDataInst,
"DataTablePin": MetaDataInst,
"SetParam": MetaDataInst,
"MapParam": MetaDataInst,
"MapKeyParam": MetaDataInst,
"MapValueParam": MetaDataInst,
"AnimBlueprintFunction": MetaDataInst,
"ArrayParam": MetaDataInst,
// decorator to add function metadata
"umeta": dummyDecorator
}
cache.uproperty = {
// the specifiers
"Const": MetaDataInst,
"Config": MetaDataInst,
"GlobalConfig": MetaDataInst,
"Localized": MetaDataInst,
"Transient": MetaDataInst,
"DuplicateTransient": MetaDataInst,
"NonPIETransient": MetaDataInst,
"NonPIEDuplicateTransient": MetaDataInst,
"Export": MetaDataInst,
"NoClear": MetaDataInst,
"EditFixedSize": MetaDataInst,
"Replicated": MetaDataInst,
"ReplicatedUsing": MetaDataInst,
"NotReplicated": MetaDataInst,
"Interp": MetaDataInst,
"NonTransactional": MetaDataInst,
"Instanced": MetaDataInst,
"BlueprintAssignable": MetaDataInst,
"Category": MetaDataInst,
"SimpleDisplay": MetaDataInst,
"AdvancedDisplay": MetaDataInst,
"EditAnywhere": MetaDataInst,
"EditInstanceOnly": MetaDataInst,
"EditDefaultsOnly": MetaDataInst,
"VisibleAnywhere": MetaDataInst,
"VisibleInstanceOnly": MetaDataInst,
"VisibleDefaultsOnly": MetaDataInst,
"BlueprintReadOnly": MetaDataInst,
"BlueprintGetter": MetaDataInst,
"BlueprintReadWrite": MetaDataInst,
"BlueprintSetter": MetaDataInst,
"AssetRegistrySearchable": MetaDataInst,
"SaveGame": MetaDataInst,
"BlueprintCallable": MetaDataInst,
"BlueprintAuthorityOnly": MetaDataInst,
"TextExportTransient": MetaDataInst,
"SkipSerialization": MetaDataInst,
"HideSelfPin": MetaDataInst,
// decorator
"uproperty": dummyDecorator,
// specifier
"ToolTip": MetaDataInst,
"ShortTooltip": MetaDataInst,
"DocumentationPolicy": MetaDataInst,
"AllowAbstract": MetaDataInst,
"AllowAnyActor": MetaDataInst,
"AllowedClasses": MetaDataInst,
"AllowPreserveRatio": MetaDataInst,
"AllowPrivateAccess": MetaDataInst,
"ArrayClamp": MetaDataInst,
"AssetBundles": MetaDataInst,
"BlueprintBaseOnly": MetaDataInst,
"BlueprintCompilerGeneratedDefaults": MetaDataInst,
"ClampMin": MetaDataInst,
"ClampMax": MetaDataInst,
"ConfigHierarchyEditable": MetaDataInst,
"ContentDir": MetaDataInst,
"DeprecatedProperty": MetaDataInst,
"DeprecationMessage": MetaDataInst, //, (Commented out so as to avoid duplicate name with version in the Class section, but still show in the property section)
"DisplayName": MetaDataInst, // (Commented out so as to avoid duplicate name with version in the Class section, but still show in the property section)
"ScriptName": MetaDataInst, //, (Commented out so as to avoid duplicate name with version in the Class section, but still show in the property section)
"DisallowedClasses": MetaDataInst,
"DisplayAfter": MetaDataInst,
"DisplayPriority": MetaDataInst,
"DisplayThumbnail": MetaDataInst,
"EditCondition": MetaDataInst,
"EditFixedOrder": MetaDataInst,
"ExactClass": MetaDataInst,
"ExposeFunctionCategories": MetaDataInst,
"ExposeOnSpawn": MetaDataInst,
"FilePathFilter": MetaDataInst,
"RelativeToGameDir": MetaDataInst,
"ForceShowEngineContent": MetaDataInst,
"ForceShowPluginContent": MetaDataInst,
"HideAlphaChannel": MetaDataInst,
"HideInDetailPanel": MetaDataInst,
"HideViewOptions": MetaDataInst,
"IgnoreForMemberInitializationTest": MetaDataInst,
"InlineEditConditionToggle": MetaDataInst,
"LongPackageName": MetaDataInst,
"MakeEditWidget": MetaDataInst,
"MakeStructureDefaultValue": MetaDataInst,
"MetaClass": MetaDataInst,
"MustImplement": MetaDataInst,
"Multiple": MetaDataInst,
"MultiLine": MetaDataInst,
"PasswordField": MetaDataInst,
"NoElementDuplicate": MetaDataInst,
"NoResetToDefault": MetaDataInst,
"NoSpinbox": MetaDataInst,
"OnlyPlaceable": MetaDataInst,
"RelativePath": MetaDataInst,
"RelativeToGameContentDir": MetaDataInst,
"ScriptNoExport": MetaDataInst,
"ShowOnlyInnerProperties": MetaDataInst,
"ShowTreeView": MetaDataInst,
"SliderExponent": MetaDataInst,
"TitleProperty": MetaDataInst,
"UIMin": MetaDataInst,
"UIMax": MetaDataInst,
"Untracked": MetaDataInst,
"DevelopmentOnly": MetaDataInst,
"NeedsLatentFixup": MetaDataInst,
"LatentCallbackTarget": MetaDataInst,
"GetOptions": MetaDataInst,
"Bitmask": MetaDataInst,
"BitmaskEnum": MetaDataInst,
// decorator
"umeta": dummyDecorator,
"attach": dummyDecorator
}
cache.uparam =
{
// the specifiers
"Const": MetaDataInst,
"Ref": MetaDataInst,
"NotReplicated": MetaDataInst,
"DisplayName": MetaDataInst,
// decorator
"uparam": dummyDecorator,
// specifier
"ToolTip": MetaDataInst,
"ShortTooltip": MetaDataInst,
"DocumentationPolicy": MetaDataInst,
"AllowAbstract": MetaDataInst,
"AllowAnyActor": MetaDataInst,
"AllowedClasses": MetaDataInst,
"AllowPreserveRatio": MetaDataInst,
"AllowPrivateAccess": MetaDataInst,
"ArrayClamp": MetaDataInst,
"AssetBundles": MetaDataInst,
"BlueprintBaseOnly": MetaDataInst,
"BlueprintCompilerGeneratedDefaults": MetaDataInst,
"ClampMin": MetaDataInst,
"ClampMax": MetaDataInst,
"ConfigHierarchyEditable": MetaDataInst,
"ContentDir": MetaDataInst,
"DeprecatedProperty": MetaDataInst,
"DeprecationMessage": MetaDataInst, //, (Commented out so as to avoid duplicate name with version in the Class section, but still show in the property section)
"ScriptName": MetaDataInst, //, (Commented out so as to avoid duplicate name with version in the Class section, but still show in the property section)
"DisallowedClasses": MetaDataInst,
"DisplayAfter": MetaDataInst,
"DisplayPriority": MetaDataInst,
"DisplayThumbnail": MetaDataInst,
"EditCondition": MetaDataInst,
"EditFixedOrder": MetaDataInst,
"ExactClass": MetaDataInst,
"ExposeFunctionCategories": MetaDataInst,
"ExposeOnSpawn": MetaDataInst,
"FilePathFilter": MetaDataInst,
"RelativeToGameDir": MetaDataInst,
"ForceShowEngineContent": MetaDataInst,
"ForceShowPluginContent": MetaDataInst,
"HideAlphaChannel": MetaDataInst,
"HideInDetailPanel": MetaDataInst,
"HideViewOptions": MetaDataInst,
"IgnoreForMemberInitializationTest": MetaDataInst,
"InlineEditConditionToggle": MetaDataInst,
"LongPackageName": MetaDataInst,
"MakeEditWidget": MetaDataInst,
"MakeStructureDefaultValue": MetaDataInst,
"MetaClass": MetaDataInst,
"MustImplement": MetaDataInst,
"Multiple": MetaDataInst,
"MultiLine": MetaDataInst,
"PasswordField": MetaDataInst,
"NoElementDuplicate": MetaDataInst,
"NoResetToDefault": MetaDataInst,
"NoSpinbox": MetaDataInst,
"OnlyPlaceable": MetaDataInst,
"RelativePath": MetaDataInst,
"RelativeToGameContentDir": MetaDataInst,
"ScriptNoExport": MetaDataInst,
"ShowOnlyInnerProperties": MetaDataInst,
"ShowTreeView": MetaDataInst,
"SliderExponent": MetaDataInst,
"TitleProperty": MetaDataInst,
"UIMin": MetaDataInst,
"UIMax": MetaDataInst,
"Untracked": MetaDataInst,
"DevelopmentOnly": MetaDataInst,
"NeedsLatentFixup": MetaDataInst,
"LatentCallbackTarget": MetaDataInst,
"GetOptions": MetaDataInst,
"Bitmask": MetaDataInst,
"BitmaskEnum": MetaDataInst,
// decorator
"umeta": dummyDecorator,
}
cache.edit_on_instance = dummyDecorator;
cache.no_blueprint = dummyDecorator;
cache.set_flags = dummyDecorator;
cache.clear_flags = dummyDecorator;
cache.FunctionFlags = FunctionFlags;
cache.ClassFlags = ClassFlags;
cache.PropertyFlags = PropertyFlags;
cache.FunctionExportFlags = FunctionExportFlags;
puerts.toManualReleaseDelegate = (x) => x;
puerts.toDelegate = (o,k) => [o, k];
function mergePrototype(from, to, exclude) {
Object.getOwnPropertyNames(from).forEach(name => {
if (!(name in exclude)) {
Object.defineProperty(
to,
name,
Object.getOwnPropertyDescriptor(from, name) ||
Object.create(null)
);
}
});
}
puerts.__mergePrototype = mergePrototype
function removeListItem(list, item) {
var found = false;
for (var i = 0; i < list.length; ++i) {
if (!found) {
found = (list[i] === item);
}
if (found) {
list[i] = list[i + 1]; // array[length + 1] === undefined
}
}
if (found) {
list.pop();
}
}
puerts.__removeListItem = removeListItem
function genListApply(lst) {
return function(...args) {
const len = lst.length;
const list = lst.slice();
let ret
for (var i = 0; i < len; ++i) {
ret = Reflect.apply(list[i], this, args);
}
return ret;
}
}
puerts.__genListApply = genListApply
}(global));
@@ -0,0 +1,165 @@
/*
* Tencent is pleased to support the open source community by making Puerts available.
* Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.
* Puerts is licensed under the BSD 3-Clause License, except for the third-party components listed in the file 'LICENSE' which may be subject to their corresponding license terms.
* This file is subject to the terms and conditions defined in file 'LICENSE', which is part of this source code package.
*/
var global = global || (function () { return this; }());
(function (global) {
"use strict";
const Wasm3 = {}
const Wasm_NewMemory = global.__tgjsWasm_NewMemory
global.__tgjsWasm_NewMemory = undefined
const Wasm_MemoryGrowth = global.__tgjsWasm_MemoryGrowth
global.__tgjsWasm_MemoryGrowth = undefined
const Wasm_MemoryBuffer = global.__tgjsWasm_MemoryBuffer
global.__tgjsWasm_MemoryBuffer = undefined
class Wasm3Memory{
constructor({initial, maximum, _Seq}){
if(_Seq) {
this._Seq = _Seq
}else{
this._Seq = Wasm_NewMemory(initial, maximum)
}
}
grow(n){
Wasm_MemoryGrowth(this._Seq, n)
}
get buffer(){
return Wasm_MemoryBuffer(this._Seq)
}
}
Wasm3.Memory = Wasm3Memory;
const Wasm_TableGrow = global.__tgjsWasm_TableGrow;
global.__tgjsWasm_TableGrow = undefined;
const Wasm_TableSet = global.__tgjsWasm_TableSet;
global.__tgjsWasm_TableSet = undefined;
const Wasm_TableLen = global.__tgjsWasm_TableLen;
global.__tgjsWasm_TableLen = undefined;
class Wasm3Table {
grow(n) {
if (this._runtimeSeq && typeof this._moduleIndex === 'number') {
return Wasm_TableGrow(this._runtimeSeq, this._moduleIndex, n);
} else {
throw new Error("invalid table");
}
}
set(index, fn) {
if (this._runtimeSeq && typeof this._moduleIndex === 'number') {
return Wasm_TableSet(this._runtimeSeq, this._moduleIndex, index, fn);
} else {
throw new Error("invalid table");
}
}
get(index) {
throw new Error("not implemented in wasm3 version");
}
get length() {
if (this._runtimeSeq && typeof this._moduleIndex === 'number') {
return Wasm_TableLen(this._runtimeSeq, this._moduleIndex);
} else {
throw new Error("invalid table");
}
}
}
Wasm3.Table = Wasm3Table;
class Wasm3Module{
constructor(bufferSource){
this._bufferSouce = bufferSource;//bufferSource is arraybuffer or typedarray
}
}
Wasm3.Module = Wasm3Module
const Wasm_Instance = global.__tgjsWasm_Instance
global.__tgjsWasm_Instance = undefined
class Wasm3ModuleInstance{
constructor(InWasm3Module, importObject){
this.exports = {}
this._Seq = Wasm_Instance(InWasm3Module._bufferSouce, importObject, this.exports)
if (this.exports.__memoryExport) {
this.exports[this.exports.__memoryExport] = new Wasm3Memory({_Seq:this._Seq});
this.exports.__memoryExport = undefined;
}
if (this.exports.__tableExport && typeof this.exports.__moduleIndex === 'number') {
var tbl = new Wasm3Table();
tbl._runtimeSeq = this._Seq;
tbl._moduleIndex = this.exports.__moduleIndex;
this.exports[this.exports.__tableExport] = tbl;
this.exports.__tableExport = undefined;
this.exports.__moduleIndex = undefined;
} else {
for(var k in importObject) {
var tbl = importObject[k];
if (tbl instanceof Wasm3Table) {
tbl._runtimeSeq = this._Seq;
tbl._moduleIndex = this.exports.__moduleIndex;
break;
}
}
}
}
}
Wasm3.instantiate = function(bufferSource, importObject){
return new Promise((resolve, reject)=>{
const ins = new Wasm3ModuleInstance(new Wasm3Module(bufferSource), importObject)
resolve(ins)
})
}
Wasm3.Instance = Wasm3ModuleInstance;
const __tgjsWasm_OverrideWebAssembly = global.__tgjsWasm_OverrideWebAssembly
global.__tgjsWasm_OverrideWebAssembly = undefined
if(__tgjsWasm_OverrideWebAssembly()){
global.WebAssembly = Wasm3
}
/*setTimeout(()=>{
const ProjDir = require('ue').BlueprintPathsLibrary.ProjectDir();
global.WebAssembly.instantiate(require('ue').MHScriptIO.ReadFileAsArrayBuffer(`${ProjDir}/Content/JavaScript/wasm/test.wasm`), {
env:
{
ImportFunction_Int : function(intValue, floatValue, doubleValue){
console.log("ffffffffffffffffffffffffffffffffffffffffffff")
console.log(typeof intValue, intValue)
console.log(typeof floatValue, floatValue)
console.log(typeof doubleValue, doubleValue)
return 1
},
atan2 : function(x, y){
return Math.atan2(x, y)
}
}
}).then((inst)=>{
const e = inst.exports
console.log("kkkk", e.TestParam(1, 3, 4))
{
const a = new Date().getTime()
for(let i = 0; i < 1000000; ++i){
e.atan2_ue(0.1, 0.1)
}
const b = new Date().getTime()
console.log("ffffffffffffffffffff ue", b - a)
}
{
const a = new Date().getTime()
for(let i = 0; i < 1000000; ++i){
e.atan2_js(0.1, 0.1)
}
const b = new Date().getTime()
console.log("ffffffffffffffffffff ue", b - a)
}
})
}, 1)*/
}(global));
@@ -0,0 +1,144 @@
/*
* Tencent is pleased to support the open source community by making Puerts available.
* Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.
* Puerts is licensed under the BSD 3-Clause License, except for the third-party components listed in the file 'LICENSE' which may be subject to their corresponding license terms.
* This file is subject to the terms and conditions defined in file 'LICENSE', which is part of this source code package.
*/
var global = global || (function () { return this; }());
(function (global) {
const WebSocketPP = global.WebSocketPP;
//global.WebSocketPP = undefined;
class EventTarget {
constructor() {
this.listeners = {};
}
addEventListener(type, callback) {
if (!(type in this.listeners)) {
this.listeners[type] = [];
}
this.listeners[type].push(callback);
}
removeEventListener(type, callback) {
if (!(type in this.listeners)) {
return;
}
const stack = this.listeners[type];
for (let i = 0; i < stack.length; i++) {
if (stack[i] === callback) {
stack.splice(i, 1);
return;
}
}
}
dispatchEvent(ev) {
if (!(ev.type in this.listeners)) {
return true;
}
const stack = this.listeners[ev.type].slice();
for (let i = 0; i < stack.length; i++) {
stack[i].call(this, ev);
}
return !ev.defaultPrevented;
}
}
const readyStates = ['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED'];
const poll_ws_objects = [];
class WebSocket extends EventTarget {
constructor(url, protocols) {
super();
if (protocols) throw new Error('do not support protocols argument');
this._raw = new WebSocketPP(url);
this._url = url;
// !!do not raise exception in handles.
this._raw.setHandles(
()=> {
this._readyState = WebSocket.OPEN;
this._addPendingEvent({type:'open'});
},
(data) => {
this._addPendingEvent({type:'message', data:data, origin:this._url});
},
(code, reason) => {
this._cleanup();
this._addPendingEvent({type:'close', code:code, reason: reason});
},
() => {
this._addPendingEvent({type:'error'});
this._cleanup();
this._addPendingEvent({type:'close', code:1006, reason: ""});
});
this._readyState = WebSocket.CONNECTING;
this._tid = setInterval(() => this._poll(), 1);
this._pendingEvents = [];
}
get url() {
return this._url;
}
get readyState() {
return this._readyState;
}
send(data) {
if (this._readyState !== WebSocket.OPEN) {
throw new Error(`WebSocket is not open: readyState ${this._readyState} (${readyStates[this._readyState]})`);
}
this._raw.send(data);
}
_cleanup() {
this._readyState = WebSocket.CLOSING;
}
_addPendingEvent(ev) {
this._pendingEvents.push(ev);
}
_poll() {
if (this._pendingEvents.length === 0 && this._readyState != WebSocket.CLOSING) {
this._raw.poll();
}
const ev = this._pendingEvents.shift();
if (ev) this.dispatchEvent(ev);
if (this._pendingEvents.length === 0 && this._readyState == WebSocket.CLOSING) {
this._raw = undefined;
clearInterval(this._tid);
this._readyState = WebSocket.CLOSED;
}
}
close(code, data) {
try {
this._raw.close(code, data);
} catch(e) {}
this._cleanup();
}
}
for (let i = 0; i < readyStates.length; i++) {
Object.defineProperty(WebSocket, readyStates[i], {
enumerable: true,
value: i
});
Object.defineProperty(WebSocket.prototype, readyStates[i], {
enumerable: true,
value: i
});
}
global.WebSocket = WebSocket;
}(global));