godot-mota/docs/index.js

460 lines
315 KiB
JavaScript
Raw Normal View History

2020-09-06 09:56:14 +08:00
var Godot = (function() {
var _scriptDir = typeof document !== 'undefined' && document.currentScript ? document.currentScript.src : undefined;
return (
function(Godot) {
Godot = Godot || {};
2020-09-06 09:56:14 +08:00
var Module=typeof Godot!=="undefined"?Godot:{};var readyPromiseResolve,readyPromiseReject;Module["ready"]=new Promise(function(resolve,reject){readyPromiseResolve=resolve;readyPromiseReject=reject});var IDHandler=function(){var ids={};var size=0;this.has=function(id){return ids.hasOwnProperty(id)};this.add=function(obj){size+=1;var id=crypto.getRandomValues(new Int32Array(32))[0];ids[id]=obj;return id};this.get=function(id){return ids[id]};this.remove=function(id){size-=1;delete ids[id]};this.size=function(){return size};this.ids=ids};Module.IDHandler=new IDHandler;Module["copyToFS"]=function(path,buffer){var p=path.lastIndexOf("/");var dir="/";if(p>0){dir=path.slice(0,path.lastIndexOf("/"))}try{FS.stat(dir)}catch(e){if(e.errno!==ERRNO_CODES.ENOENT){throw e}FS.mkdirTree(dir)}FS.writeFile(path,new Uint8Array(buffer),{"flags":"wx+"})};Module.drop_handler=function(){var upload=[];var uploadPromises=[];var uploadCallback=null;function readFilePromise(entry,path){return new Promise(function(resolve,reject){entry.file(function(file){var reader=new FileReader;reader.onload=function(){var f={"path":file.relativePath||file.webkitRelativePath,"name":file.name,"type":file.type,"size":file.size,"data":reader.result};if(!f["path"])f["path"]=f["name"];upload.push(f);resolve()};reader.onerror=function(){console.log("Error reading file");reject()};reader.readAsArrayBuffer(file)},function(err){console.log("Error!");reject()})})}function readDirectoryPromise(entry){return new Promise(function(resolve,reject){var reader=entry.createReader();reader.readEntries(function(entries){for(var i=0;i<entries.length;i++){var ent=entries[i];if(ent.isDirectory){uploadPromises.push(readDirectoryPromise(ent))}else if(ent.isFile){uploadPromises.push(readFilePromise(ent))}}resolve()})})}function processUploadsPromises(resolve,reject){if(uploadPromises.length==0){resolve();return}uploadPromises.pop().then(function(){setTimeout(function(){processUploadsPromises(resolve,reject)},0)})}function dropFiles(files){var args=files||[];var argc=args.length;var argv=stackAlloc((argc+1)*4);for(var i=0;i<argc;i++){HEAP32[(argv>>2)+i]=allocateUTF8OnStack(args[i])}HEAP32[(argv>>2)+argc]=0;ccall("_drop_files_callback","void",["number","number"],[argv,argc])}return function(ev){ev.preventDefault();if(ev.dataTransfer.items){for(var i=0;i<ev.dataTransfer.items.length;i++){const item=ev.dataTransfer.items[i];var entry=null;if("getAsEntry"in item){entry=item.getAsEntry()}else if("webkitGetAsEntry"in item){entry=item.webkitGetAsEntry()}if(!entry){console.error("File upload not supported")}else if(entry.isDirectory){uploadPromises.push(readDirectoryPromise(entry))}else if(entry.isFile){uploadPromises.push(readFilePromise(entry))}else{console.error("Unrecognized entry...",entry)}}}else{console.error("File upload not supported")}uploadCallback=new Promise(processUploadsPromises).then(function(){const DROP="/tmp/drop-"+parseInt(Math.random()*Math.pow(2,31))+"/";var drops=[];var files=[];upload.forEach(elem=>{var path=elem["path"];Module["copyToFS"](DROP+path,elem["data"]);var idx=path.indexOf("/");if(idx==-1){drops.push(DROP+path)}else{var sub=path.substr(0,idx);idx=sub.indexOf("/");if(idx<0&&drops.indexOf(DROP+sub)==-1){drops.push(DROP+sub)}}files.push(DROP+path)});uploadPromises=[];upload=[];dropFiles(drops);var dirs=[DROP.substr(0,DROP.length-1)];files.forEach(function(file){FS.unlink(file);var dir=file.replace(DROP,"");var idx=dir.lastIndexOf("/");while(idx>0){dir=dir.substr(0,idx);if(dirs.indexOf(DROP+dir)==-1){dirs.push(DROP+dir)}idx=dir.lastIndexOf("/")}});dirs=dirs.sort(function(a,b){var al=(a.match(/\//g)||[]).length;var bl=(b.match(/\//g)||[]).length;if(al>bl)return-1;else if(al<bl)return 1;return 0});dirs.forEach(function(dir){FS.rmdir(dir)})})}}();var moduleOverrides={};var key;for(key in Module){if(Module.hasOwnProperty(key)){moduleOverrides[key]=Module[key]}}var arguments_=[];var thisProgram="./this.program";var quit_=function(status,toThrow){throw toThrow};var ENVIRONMENT_IS_WEB=false;var ENVIRONMENT_IS_WORKER=false;var ENVIRONMENT_IS_NODE=false;var ENVIRONMENT_IS_SH
2020-09-06 09:56:14 +08:00
return Godot.ready
}
);
})();
if (typeof exports === 'object' && typeof module === 'object')
module.exports = Godot;
else if (typeof define === 'function' && define['amd'])
define([], function() { return Godot; });
else if (typeof exports === 'object')
exports["Godot"] = Godot;
var Preloader = /** @constructor */ function() {
2020-09-06 09:56:14 +08:00
var DOWNLOAD_ATTEMPTS_MAX = 4;
var progressFunc = null;
var lastProgress = { loaded: 0, total: 0 };
2020-09-06 09:56:14 +08:00
var loadingFiles = {};
this.preloadedFiles = [];
2020-09-06 09:56:14 +08:00
function loadXHR(resolve, reject, file, tracker) {
var xhr = new XMLHttpRequest;
xhr.open('GET', file);
if (!file.endsWith('.js')) {
xhr.responseType = 'arraybuffer';
}
['loadstart', 'progress', 'load', 'error', 'abort'].forEach(function(ev) {
xhr.addEventListener(ev, onXHREvent.bind(xhr, resolve, reject, file, tracker));
});
xhr.send();
2020-09-06 09:56:14 +08:00
}
function onXHREvent(resolve, reject, file, tracker, ev) {
2020-09-06 09:56:14 +08:00
if (this.status >= 400) {
2020-09-06 09:56:14 +08:00
if (this.status < 500 || ++tracker[file].attempts >= DOWNLOAD_ATTEMPTS_MAX) {
reject(new Error("Failed loading file '" + file + "': " + this.statusText));
this.abort();
return;
} else {
setTimeout(loadXHR.bind(null, resolve, reject, file, tracker), 1000);
}
}
2020-09-06 09:56:14 +08:00
switch (ev.type) {
case 'loadstart':
if (tracker[file] === undefined) {
tracker[file] = {
total: ev.total,
loaded: ev.loaded,
attempts: 0,
final: false,
};
}
break;
2020-09-06 09:56:14 +08:00
case 'progress':
tracker[file].loaded = ev.loaded;
tracker[file].total = ev.total;
break;
2020-09-06 09:56:14 +08:00
case 'load':
tracker[file].final = true;
resolve(this);
break;
2020-09-06 09:56:14 +08:00
case 'error':
if (++tracker[file].attempts >= DOWNLOAD_ATTEMPTS_MAX) {
tracker[file].final = true;
reject(new Error("Failed loading file '" + file + "'"));
} else {
setTimeout(loadXHR.bind(null, resolve, reject, file, tracker), 1000);
}
break;
2020-09-06 09:56:14 +08:00
case 'abort':
tracker[file].final = true;
reject(new Error("Loading file '" + file + "' was aborted."));
break;
2020-09-06 09:56:14 +08:00
}
}
2020-09-06 09:56:14 +08:00
this.loadPromise = function(file) {
return new Promise(function(resolve, reject) {
loadXHR(resolve, reject, file, loadingFiles);
});
}
2020-09-06 09:56:14 +08:00
this.preload = function(pathOrBuffer, destPath) {
if (pathOrBuffer instanceof ArrayBuffer) {
pathOrBuffer = new Uint8Array(pathOrBuffer);
} else if (ArrayBuffer.isView(pathOrBuffer)) {
pathOrBuffer = new Uint8Array(pathOrBuffer.buffer);
}
if (pathOrBuffer instanceof Uint8Array) {
this.preloadedFiles.push({
path: destPath,
buffer: pathOrBuffer
});
return Promise.resolve();
} else if (typeof pathOrBuffer === 'string') {
var me = this;
return this.loadPromise(pathOrBuffer).then(function(xhr) {
me.preloadedFiles.push({
path: destPath || pathOrBuffer,
buffer: xhr.response
2020-09-06 09:56:14 +08:00
});
return Promise.resolve();
});
} else {
throw Promise.reject("Invalid object for preloading");
}
};
2020-09-06 09:56:14 +08:00
var animateProgress = function() {
2020-09-06 09:56:14 +08:00
var loaded = 0;
var total = 0;
var totalIsValid = true;
var progressIsFinal = true;
2020-09-06 09:56:14 +08:00
Object.keys(loadingFiles).forEach(function(file) {
const stat = loadingFiles[file];
if (!stat.final) {
progressIsFinal = false;
2020-09-06 09:56:14 +08:00
}
if (!totalIsValid || stat.total === 0) {
totalIsValid = false;
total = 0;
2020-09-06 09:56:14 +08:00
} else {
total += stat.total;
2020-09-06 09:56:14 +08:00
}
loaded += stat.loaded;
});
if (loaded !== lastProgress.loaded || total !== lastProgress.total) {
lastProgress.loaded = loaded;
lastProgress.total = total;
if (typeof progressFunc === 'function')
progressFunc(loaded, total);
2020-09-06 09:56:14 +08:00
}
if (!progressIsFinal)
requestAnimationFrame(animateProgress);
}
this.animateProgress = animateProgress; // Also exposed to start it.
2020-09-06 09:56:14 +08:00
this.setProgressFunc = function(callback) {
progressFunc = callback;
}
};
2020-09-06 09:56:14 +08:00
var Utils = {
2020-09-06 09:56:14 +08:00
createLocateRewrite: function(execName) {
function rw(path) {
if (path.endsWith('.worker.js')) {
return execName + '.worker.js';
} else if (path.endsWith('.js')) {
return execName + '.js';
} else if (path.endsWith('.wasm')) {
return execName + '.wasm';
2020-09-06 09:56:14 +08:00
}
}
return rw;
},
2020-09-06 09:56:14 +08:00
createInstantiatePromise: function(wasmLoader) {
function instantiateWasm(imports, onSuccess) {
wasmLoader.then(function(xhr) {
WebAssembly.instantiate(xhr.response, imports).then(function(result) {
onSuccess(result['instance'], result['module']);
});
});
wasmLoader = null;
return {};
2020-09-06 09:56:14 +08:00
};
return instantiateWasm;
},
2020-09-06 09:56:14 +08:00
findCanvas: function() {
var nodes = document.getElementsByTagName('canvas');
if (nodes.length && nodes[0] instanceof HTMLCanvasElement) {
return nodes[0];
}
throw new Error("No canvas found");
},
2020-09-06 09:56:14 +08:00
isWebGLAvailable: function(majorVersion = 1) {
2020-09-06 09:56:14 +08:00
var testContext = false;
try {
var testCanvas = document.createElement('canvas');
if (majorVersion === 1) {
testContext = testCanvas.getContext('webgl') || testCanvas.getContext('experimental-webgl');
} else if (majorVersion === 2) {
testContext = testCanvas.getContext('webgl2') || testCanvas.getContext('experimental-webgl2');
}
} catch (e) {}
return !!testContext;
}
};
2020-09-06 09:56:14 +08:00
Function('return this')()['Engine'] = (function() {
var preloader = new Preloader();
var wasmExt = '.wasm';
var unloadAfterInit = true;
var loadPath = '';
var loadPromise = null;
var initPromise = null;
var stderr = null;
var stdout = null;
var progressFunc = null;
function load(basePath) {
if (loadPromise == null) {
loadPath = basePath;
loadPromise = preloader.loadPromise(basePath + wasmExt);
preloader.setProgressFunc(progressFunc);
requestAnimationFrame(preloader.animateProgress);
}
return loadPromise;
};
2020-09-06 09:56:14 +08:00
function unload() {
loadPromise = null;
};
2020-09-06 09:56:14 +08:00
/** @constructor */
function Engine() {
this.canvas = null;
this.executableName = '';
this.rtenv = null;
this.customLocale = null;
this.resizeCanvasOnStart = false;
this.onExecute = null;
this.onExit = null;
};
2020-09-06 09:56:14 +08:00
Engine.prototype.init = /** @param {string=} basePath */ function(basePath) {
if (initPromise) {
return initPromise;
}
if (loadPromise == null) {
if (!basePath) {
initPromise = Promise.reject(new Error("A base path must be provided when calling `init` and the engine is not loaded."));
return initPromise;
}
load(basePath);
}
var config = {};
if (typeof stdout === 'function')
config.print = stdout;
if (typeof stderr === 'function')
config.printErr = stderr;
var me = this;
initPromise = new Promise(function(resolve, reject) {
config['locateFile'] = Utils.createLocateRewrite(loadPath);
config['instantiateWasm'] = Utils.createInstantiatePromise(loadPromise);
Godot(config).then(function(module) {
me.rtenv = module;
if (unloadAfterInit) {
unload();
2020-09-06 09:56:14 +08:00
}
resolve();
config = null;
});
});
return initPromise;
};
2020-09-06 09:56:14 +08:00
/** @type {function(string, string):Object} */
Engine.prototype.preloadFile = function(file, path) {
return preloader.preload(file, path);
};
2020-09-06 09:56:14 +08:00
/** @type {function(...string):Object} */
Engine.prototype.start = function() {
// Start from arguments.
var args = [];
for (var i = 0; i < arguments.length; i++) {
args.push(arguments[i]);
}
var me = this;
return me.init().then(function() {
if (!me.rtenv) {
return Promise.reject(new Error('The engine must be initialized before it can be started'));
}
2020-09-06 09:56:14 +08:00
if (!(me.canvas instanceof HTMLCanvasElement)) {
me.canvas = Utils.findCanvas();
}
2020-09-06 09:56:14 +08:00
// Canvas can grab focus on click, or key events won't work.
if (me.canvas.tabIndex < 0) {
me.canvas.tabIndex = 0;
}
2020-09-06 09:56:14 +08:00
// Disable right-click context menu.
me.canvas.addEventListener('contextmenu', function(ev) {
ev.preventDefault();
}, false);
2020-09-06 09:56:14 +08:00
// Until context restoration is implemented warn the user of context loss.
me.canvas.addEventListener('webglcontextlost', function(ev) {
alert("WebGL context lost, please reload the page");
ev.preventDefault();
}, false);
2020-09-06 09:56:14 +08:00
// Browser locale, or custom one if defined.
var locale = me.customLocale;
if (!locale) {
locale = navigator.languages ? navigator.languages[0] : navigator.language;
locale = locale.split('.')[0];
2020-09-06 09:56:14 +08:00
}
me.rtenv['locale'] = locale;
me.rtenv['canvas'] = me.canvas;
me.rtenv['thisProgram'] = me.executableName;
me.rtenv['resizeCanvasOnStart'] = me.resizeCanvasOnStart;
me.rtenv['noExitRuntime'] = true;
me.rtenv['onExecute'] = me.onExecute;
me.rtenv['onExit'] = function(code) {
if (me.onExit)
me.onExit(code);
me.rtenv = null;
}
return new Promise(function(resolve, reject) {
preloader.preloadedFiles.forEach(function(file) {
me.rtenv['copyToFS'](file.path, file.buffer);
});
preloader.preloadedFiles.length = 0; // Clear memory
me.rtenv['callMain'](args);
initPromise = null;
resolve();
});
});
2020-09-06 09:56:14 +08:00
};
Engine.prototype.startGame = function(execName, mainPack, extraArgs) {
// Start and init with execName as loadPath if not inited.
this.executableName = execName;
var me = this;
return Promise.all([
this.init(execName),
this.preloadFile(mainPack, mainPack)
]).then(function() {
var args = ['--main-pack', mainPack];
if (extraArgs)
args = args.concat(extraArgs);
return me.start.apply(me, args);
});
};
2020-09-06 09:56:14 +08:00
Engine.prototype.setWebAssemblyFilenameExtension = function(override) {
2020-09-06 09:56:14 +08:00
if (String(override).length === 0) {
throw new Error('Invalid WebAssembly filename extension override');
}
wasmExt = String(override);
2020-09-06 09:56:14 +08:00
};
Engine.prototype.setUnloadAfterInit = function(enabled) {
unloadAfterInit = enabled;
2020-09-06 09:56:14 +08:00
};
Engine.prototype.setCanvas = function(canvasElem) {
this.canvas = canvasElem;
};
2020-09-06 09:56:14 +08:00
Engine.prototype.setCanvasResizedOnStart = function(enabled) {
this.resizeCanvasOnStart = enabled;
};
2020-09-06 09:56:14 +08:00
Engine.prototype.setLocale = function(locale) {
this.customLocale = locale;
};
2020-09-06 09:56:14 +08:00
Engine.prototype.setExecutableName = function(newName) {
this.executableName = newName;
};
2020-09-06 09:56:14 +08:00
Engine.prototype.setProgressFunc = function(func) {
progressFunc = func;
};
2020-09-06 09:56:14 +08:00
Engine.prototype.setStdoutFunc = function(func) {
var print = function(text) {
if (arguments.length > 1) {
text = Array.prototype.slice.call(arguments).join(" ");
2020-09-06 09:56:14 +08:00
}
func(text);
};
if (this.rtenv)
this.rtenv.print = print;
stdout = print;
};
2020-09-06 09:56:14 +08:00
Engine.prototype.setStderrFunc = function(func) {
var printErr = function(text) {
if (arguments.length > 1)
text = Array.prototype.slice.call(arguments).join(" ");
func(text);
};
if (this.rtenv)
this.rtenv.printErr = printErr;
stderr = printErr;
};
2020-09-06 09:56:14 +08:00
Engine.prototype.setOnExecute = function(onExecute) {
if (this.rtenv)
this.rtenv.onExecute = onExecute;
this.onExecute = onExecute;
}
2020-09-06 09:56:14 +08:00
Engine.prototype.setOnExit = function(onExit) {
this.onExit = onExit;
}
2020-09-06 09:56:14 +08:00
Engine.prototype.copyToFS = function(path, buffer) {
if (this.rtenv == null) {
throw new Error("Engine must be inited before copying files");
2020-09-06 09:56:14 +08:00
}
this.rtenv['copyToFS'](path, buffer);
2020-09-06 09:56:14 +08:00
}
// Closure compiler exported engine methods.
/** @export */
Engine['isWebGLAvailable'] = Utils.isWebGLAvailable;
Engine['load'] = load;
Engine['unload'] = unload;
Engine.prototype['init'] = Engine.prototype.init;
Engine.prototype['preloadFile'] = Engine.prototype.preloadFile;
Engine.prototype['start'] = Engine.prototype.start;
Engine.prototype['startGame'] = Engine.prototype.startGame;
Engine.prototype['setWebAssemblyFilenameExtension'] = Engine.prototype.setWebAssemblyFilenameExtension;
Engine.prototype['setUnloadAfterInit'] = Engine.prototype.setUnloadAfterInit;
Engine.prototype['setCanvas'] = Engine.prototype.setCanvas;
Engine.prototype['setCanvasResizedOnStart'] = Engine.prototype.setCanvasResizedOnStart;
Engine.prototype['setLocale'] = Engine.prototype.setLocale;
Engine.prototype['setExecutableName'] = Engine.prototype.setExecutableName;
Engine.prototype['setProgressFunc'] = Engine.prototype.setProgressFunc;
Engine.prototype['setStdoutFunc'] = Engine.prototype.setStdoutFunc;
Engine.prototype['setStderrFunc'] = Engine.prototype.setStderrFunc;
Engine.prototype['setOnExecute'] = Engine.prototype.setOnExecute;
Engine.prototype['setOnExit'] = Engine.prototype.setOnExit;
Engine.prototype['copyToFS'] = Engine.prototype.copyToFS;
return Engine;
2020-09-06 09:56:14 +08:00
})();