diff --git a/frontend/resources/public/wasm/Makefile b/frontend/resources/public/wasm/Makefile index 5cc6b69bd1..8fc4eb217b 100644 --- a/frontend/resources/public/wasm/Makefile +++ b/frontend/resources/public/wasm/Makefile @@ -1,2 +1,3 @@ all: - clang -target wasm32 -Wl,--no-entry -Wl,--export-all -nostdlib -O3 add.c -o add.wasm + mkdir -p build + em++ -std=c++20 -O3 -sINCOMING_MODULE_JS_API=['print'] -sENVIRONMENT=web,node,worker -sFILESYSTEM=0 src/main.cpp -o build/main.js diff --git a/frontend/resources/public/wasm/NOTAS.md b/frontend/resources/public/wasm/NOTAS.md index 29e02fedf5..1110c5085c 100644 --- a/frontend/resources/public/wasm/NOTAS.md +++ b/frontend/resources/public/wasm/NOTAS.md @@ -1,5 +1,7 @@ # Notas +## TO DO + - [ ] Mover todo esto a algún otro sitio mejor que no sea `resources/public`. - [ ] Implementar tanto `clang-format` como `clang-tidy` para formatear el código. - [ ] Implementar algún sistema de testing (Catch2, Google Test, CppUnit, etc). @@ -11,6 +13,52 @@ Para compilar el código en C++ se puede usar la siguiente línea: g++ -std=c++20 src/main.cpp -o main ``` +## Emscripten + +### Instalación + +1. Clonar repositorio: + +```sh +git clone https://github.com/emscripten-core/emsdk.git +cd emsdk +``` + +2. Actualizar e instalar dependencias: + +```sh +git pull +./emsdk install latest +./emsdk activate latest +source ./emsdk_env.sh +``` + +3. Probar: + +:bulb: Ahora deberíamos tener disponibles herramientas como `emcc` (equivalente a +`gcc` o `clang`), `em++` (equivalente a `g++` o `clang++`), `emmake` +(equivalente a `make`) o `emcmake` (equivalente a `cmake`). + +Puedes compilar el proyecto con: + +```sh +emmake make +``` + +## WebAssembly + +### Memoria + +La memoria de WebAssembly se crea cuando se instancia el módulo de WebAssembly, aunque esta memoria puede crecer. Si no se pasa un `WebAssembly.Memory` al módulo en la instanciación, crea una memoria por defecto con el número de páginas que indique el módulo. + +:bulb: Para averiguar cuál es este valor por defecto podemos usar `wasm-objdump -x | grep 'pages:'`. + +La memoria de WebAssembly se reserva usando páginas (una página equivale a 64KB). + +El máximo de memoria que puede reservar un módulo de WebAssembly ahora mismo son 4GB (65536 páginas). + +:bulb: Ahora mismo existen dos _proposals_ para ampliar estos límites: [Memory64](https://github.com/WebAssembly/memory64) y [Multi-Memory](https://github.com/WebAssembly/multi-memory/blob/master/proposals/multi-memory/Overview.md) + ## Documentos - [C++ Core Guidelines](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#S-introduction) @@ -18,3 +66,7 @@ g++ -std=c++20 src/main.cpp -o main ## Recursos - [Compiling C to WebAssembly without Emscripten](https://surma.dev/things/c-to-webassembly/) +- [Emscripten: C/C++ compiler toolchain](https://emscripten.org/) +- [Emscripten: settings.js](https://github.com/emscripten-core/emscripten/blob/main/src/settings.js) +- [WABT: WebAssembly Binary Toolkit](https://github.com/WebAssembly/wabt) +- [Binaryen: Compiler Toolchain](https://github.com/WebAssembly/binaryen) diff --git a/frontend/resources/public/wasm/add.c b/frontend/resources/public/wasm/add.c deleted file mode 100644 index db7a8a6cd7..0000000000 --- a/frontend/resources/public/wasm/add.c +++ /dev/null @@ -1,19 +0,0 @@ -#include "int.h" - -#define MAX_OPERATIONS 2048 - -typedef struct _operations { - int32_t a, b, r; -} operations_t; - -operations_t operations[MAX_OPERATIONS]; - -int32_t add(int32_t a, int32_t b) { - return a + b; -} - -void compute() { - for (int32_t i = 0; i < MAX_OPERATIONS; i++) { - operations[i].r = add(operations[i].a, operations[i].b); - } -} diff --git a/frontend/resources/public/wasm/add.js b/frontend/resources/public/wasm/add.js deleted file mode 100644 index a87d16e251..0000000000 --- a/frontend/resources/public/wasm/add.js +++ /dev/null @@ -1,5 +0,0 @@ -function add(a, b) { - return a + b -} - -add(5, 5) diff --git a/frontend/resources/public/wasm/add.wasm b/frontend/resources/public/wasm/add.wasm deleted file mode 100755 index 9fe76a24da..0000000000 Binary files a/frontend/resources/public/wasm/add.wasm and /dev/null differ diff --git a/frontend/resources/public/wasm/build/main.js b/frontend/resources/public/wasm/build/main.js new file mode 100644 index 0000000000..0416d29db1 --- /dev/null +++ b/frontend/resources/public/wasm/build/main.js @@ -0,0 +1 @@ +var Module=typeof Module!="undefined"?Module:{};var moduleOverrides=Object.assign({},Module);var arguments_=[];var thisProgram="./this.program";var quit_=(status,toThrow)=>{throw toThrow};var ENVIRONMENT_IS_WEB=typeof window=="object";var ENVIRONMENT_IS_WORKER=typeof importScripts=="function";var ENVIRONMENT_IS_NODE=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string";var scriptDirectory="";function locateFile(path){return scriptDirectory+path}var read_,readAsync,readBinary,setWindowTitle;if(ENVIRONMENT_IS_NODE){var fs=require("fs");var nodePath=require("path");if(ENVIRONMENT_IS_WORKER){scriptDirectory=nodePath.dirname(scriptDirectory)+"/"}else{scriptDirectory=__dirname+"/"}read_=(filename,binary)=>{filename=isFileURI(filename)?new URL(filename):nodePath.normalize(filename);return fs.readFileSync(filename,binary?undefined:"utf8")};readBinary=filename=>{var ret=read_(filename,true);if(!ret.buffer){ret=new Uint8Array(ret)}return ret};readAsync=(filename,onload,onerror)=>{filename=isFileURI(filename)?new URL(filename):nodePath.normalize(filename);fs.readFile(filename,function(err,data){if(err)onerror(err);else onload(data.buffer)})};if(process.argv.length>1){thisProgram=process.argv[1].replace(/\\/g,"/")}arguments_=process.argv.slice(2);if(typeof module!="undefined"){module["exports"]=Module}process.on("uncaughtException",function(ex){if(ex!=="unwind"&&!(ex instanceof ExitStatus)&&!(ex.context instanceof ExitStatus)){throw ex}});var nodeMajor=process.versions.node.split(".")[0];if(nodeMajor<15){process.on("unhandledRejection",function(reason){throw reason})}quit_=(status,toThrow)=>{process.exitCode=status;throw toThrow};Module["inspect"]=function(){return"[Emscripten Module object]"}}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){if(ENVIRONMENT_IS_WORKER){scriptDirectory=self.location.href}else if(typeof document!="undefined"&&document.currentScript){scriptDirectory=document.currentScript.src}if(scriptDirectory.indexOf("blob:")!==0){scriptDirectory=scriptDirectory.substr(0,scriptDirectory.replace(/[?#].*/,"").lastIndexOf("/")+1)}else{scriptDirectory=""}{read_=url=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.send(null);return xhr.responseText};if(ENVIRONMENT_IS_WORKER){readBinary=url=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.responseType="arraybuffer";xhr.send(null);return new Uint8Array(xhr.response)}}readAsync=(url,onload,onerror)=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,true);xhr.responseType="arraybuffer";xhr.onload=()=>{if(xhr.status==200||xhr.status==0&&xhr.response){onload(xhr.response);return}onerror()};xhr.onerror=onerror;xhr.send(null)}}setWindowTitle=title=>document.title=title}else{}var out=Module["print"]||console.log.bind(console);var err=console.warn.bind(console);Object.assign(Module,moduleOverrides);moduleOverrides=null;var wasmBinary;var noExitRuntime=true;if(typeof WebAssembly!="object"){abort("no native wasm support detected")}var wasmMemory;var ABORT=false;var EXITSTATUS;var UTF8Decoder=typeof TextDecoder!="undefined"?new TextDecoder("utf8"):undefined;function UTF8ArrayToString(heapOrArray,idx,maxBytesToRead){var endIdx=idx+maxBytesToRead;var endPtr=idx;while(heapOrArray[endPtr]&&!(endPtr>=endIdx))++endPtr;if(endPtr-idx>16&&heapOrArray.buffer&&UTF8Decoder){return UTF8Decoder.decode(heapOrArray.subarray(idx,endPtr))}var str="";while(idx>10,56320|ch&1023)}}return str}function UTF8ToString(ptr,maxBytesToRead){return ptr?UTF8ArrayToString(HEAPU8,ptr,maxBytesToRead):""}function stringToUTF8Array(str,heap,outIdx,maxBytesToWrite){if(!(maxBytesToWrite>0))return 0;var startIdx=outIdx;var endIdx=outIdx+maxBytesToWrite-1;for(var i=0;i=55296&&u<=57343){var u1=str.charCodeAt(++i);u=65536+((u&1023)<<10)|u1&1023}if(u<=127){if(outIdx>=endIdx)break;heap[outIdx++]=u}else if(u<=2047){if(outIdx+1>=endIdx)break;heap[outIdx++]=192|u>>6;heap[outIdx++]=128|u&63}else if(u<=65535){if(outIdx+2>=endIdx)break;heap[outIdx++]=224|u>>12;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}else{if(outIdx+3>=endIdx)break;heap[outIdx++]=240|u>>18;heap[outIdx++]=128|u>>12&63;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}}heap[outIdx]=0;return outIdx-startIdx}function lengthBytesUTF8(str){var len=0;for(var i=0;i=55296&&c<=57343){len+=4;++i}else{len+=3}}return len}var HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAPF64;function updateMemoryViews(){var b=wasmMemory.buffer;Module["HEAP8"]=HEAP8=new Int8Array(b);Module["HEAP16"]=HEAP16=new Int16Array(b);Module["HEAP32"]=HEAP32=new Int32Array(b);Module["HEAPU8"]=HEAPU8=new Uint8Array(b);Module["HEAPU16"]=HEAPU16=new Uint16Array(b);Module["HEAPU32"]=HEAPU32=new Uint32Array(b);Module["HEAPF32"]=HEAPF32=new Float32Array(b);Module["HEAPF64"]=HEAPF64=new Float64Array(b)}var wasmTable;var __ATPRERUN__=[];var __ATINIT__=[];var __ATMAIN__=[];var __ATPOSTRUN__=[];var runtimeInitialized=false;var runtimeKeepaliveCounter=0;function keepRuntimeAlive(){return noExitRuntime||runtimeKeepaliveCounter>0}function preRun(){callRuntimeCallbacks(__ATPRERUN__)}function initRuntime(){runtimeInitialized=true;callRuntimeCallbacks(__ATINIT__)}function preMain(){callRuntimeCallbacks(__ATMAIN__)}function postRun(){callRuntimeCallbacks(__ATPOSTRUN__)}function addOnInit(cb){__ATINIT__.unshift(cb)}var runDependencies=0;var runDependencyWatcher=null;var dependenciesFulfilled=null;function addRunDependency(id){runDependencies++}function removeRunDependency(id){runDependencies--;if(runDependencies==0){if(runDependencyWatcher!==null){clearInterval(runDependencyWatcher);runDependencyWatcher=null}if(dependenciesFulfilled){var callback=dependenciesFulfilled;dependenciesFulfilled=null;callback()}}}function abort(what){what="Aborted("+what+")";err(what);ABORT=true;EXITSTATUS=1;what+=". Build with -sASSERTIONS for more info.";var e=new WebAssembly.RuntimeError(what);throw e}var dataURIPrefix="data:application/octet-stream;base64,";function isDataURI(filename){return filename.startsWith(dataURIPrefix)}function isFileURI(filename){return filename.startsWith("file://")}var wasmBinaryFile;wasmBinaryFile="main.wasm";if(!isDataURI(wasmBinaryFile)){wasmBinaryFile=locateFile(wasmBinaryFile)}function getBinary(file){try{if(file==wasmBinaryFile&&wasmBinary){return new Uint8Array(wasmBinary)}if(readBinary){return readBinary(file)}throw"both async and sync fetching of the wasm failed"}catch(err){abort(err)}}function getBinaryPromise(binaryFile){if(!wasmBinary&&(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER)){if(typeof fetch=="function"){return fetch(binaryFile,{credentials:"same-origin"}).then(function(response){if(!response["ok"]){throw"failed to load wasm binary file at '"+binaryFile+"'"}return response["arrayBuffer"]()}).catch(function(){return getBinary(binaryFile)})}}return Promise.resolve().then(function(){return getBinary(binaryFile)})}function instantiateArrayBuffer(binaryFile,imports,receiver){return getBinaryPromise(binaryFile).then(function(binary){return WebAssembly.instantiate(binary,imports)}).then(function(instance){return instance}).then(receiver,function(reason){err("failed to asynchronously prepare wasm: "+reason);abort(reason)})}function instantiateAsync(binary,binaryFile,imports,callback){if(!binary&&typeof WebAssembly.instantiateStreaming=="function"&&!isDataURI(binaryFile)&&!ENVIRONMENT_IS_NODE&&typeof fetch=="function"){return fetch(binaryFile,{credentials:"same-origin"}).then(function(response){var result=WebAssembly.instantiateStreaming(response,imports);return result.then(callback,function(reason){err("wasm streaming compile failed: "+reason);err("falling back to ArrayBuffer instantiation");return instantiateArrayBuffer(binaryFile,imports,callback)})})}else{return instantiateArrayBuffer(binaryFile,imports,callback)}}function createWasm(){var info={"a":wasmImports};function receiveInstance(instance,module){var exports=instance.exports;Module["asm"]=exports;wasmMemory=Module["asm"]["l"];updateMemoryViews();wasmTable=Module["asm"]["o"];addOnInit(Module["asm"]["m"]);removeRunDependency("wasm-instantiate");return exports}addRunDependency("wasm-instantiate");function receiveInstantiationResult(result){receiveInstance(result["instance"])}instantiateAsync(wasmBinary,wasmBinaryFile,info,receiveInstantiationResult);return{}}function ExitStatus(status){this.name="ExitStatus";this.message="Program terminated with exit("+status+")";this.status=status}function callRuntimeCallbacks(callbacks){while(callbacks.length>0){callbacks.shift()(Module)}}function ExceptionInfo(excPtr){this.excPtr=excPtr;this.ptr=excPtr-24;this.set_type=function(type){HEAPU32[this.ptr+4>>2]=type};this.get_type=function(){return HEAPU32[this.ptr+4>>2]};this.set_destructor=function(destructor){HEAPU32[this.ptr+8>>2]=destructor};this.get_destructor=function(){return HEAPU32[this.ptr+8>>2]};this.set_refcount=function(refcount){HEAP32[this.ptr>>2]=refcount};this.set_caught=function(caught){caught=caught?1:0;HEAP8[this.ptr+12>>0]=caught};this.get_caught=function(){return HEAP8[this.ptr+12>>0]!=0};this.set_rethrown=function(rethrown){rethrown=rethrown?1:0;HEAP8[this.ptr+13>>0]=rethrown};this.get_rethrown=function(){return HEAP8[this.ptr+13>>0]!=0};this.init=function(type,destructor){this.set_adjusted_ptr(0);this.set_type(type);this.set_destructor(destructor);this.set_refcount(0);this.set_caught(false);this.set_rethrown(false)};this.add_ref=function(){var value=HEAP32[this.ptr>>2];HEAP32[this.ptr>>2]=value+1};this.release_ref=function(){var prev=HEAP32[this.ptr>>2];HEAP32[this.ptr>>2]=prev-1;return prev===1};this.set_adjusted_ptr=function(adjustedPtr){HEAPU32[this.ptr+16>>2]=adjustedPtr};this.get_adjusted_ptr=function(){return HEAPU32[this.ptr+16>>2]};this.get_exception_ptr=function(){var isPointer=___cxa_is_pointer_type(this.get_type());if(isPointer){return HEAPU32[this.excPtr>>2]}var adjusted=this.get_adjusted_ptr();if(adjusted!==0)return adjusted;return this.excPtr}}var exceptionLast=0;var uncaughtExceptionCount=0;function ___cxa_throw(ptr,type,destructor){var info=new ExceptionInfo(ptr);info.init(type,destructor);exceptionLast=ptr;uncaughtExceptionCount++;throw ptr}function _abort(){abort("")}function _emscripten_memcpy_big(dest,src,num){HEAPU8.copyWithin(dest,src,src+num)}function abortOnCannotGrowMemory(requestedSize){abort("OOM")}function _emscripten_resize_heap(requestedSize){var oldSize=HEAPU8.length;requestedSize=requestedSize>>>0;abortOnCannotGrowMemory(requestedSize)}var ENV={};function getExecutableName(){return thisProgram||"./this.program"}function getEnvStrings(){if(!getEnvStrings.strings){var lang=(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8";var env={"USER":"web_user","LOGNAME":"web_user","PATH":"/","PWD":"/","HOME":"/home/web_user","LANG":lang,"_":getExecutableName()};for(var x in ENV){if(ENV[x]===undefined)delete env[x];else env[x]=ENV[x]}var strings=[];for(var x in env){strings.push(x+"="+env[x])}getEnvStrings.strings=strings}return getEnvStrings.strings}function writeAsciiToMemory(str,buffer,dontAddNull){for(var i=0;i>0]=str.charCodeAt(i)}if(!dontAddNull)HEAP8[buffer>>0]=0}var SYSCALLS={varargs:undefined,get:function(){SYSCALLS.varargs+=4;var ret=HEAP32[SYSCALLS.varargs-4>>2];return ret},getStr:function(ptr){var ret=UTF8ToString(ptr);return ret}};function _environ_get(__environ,environ_buf){var bufSize=0;getEnvStrings().forEach(function(string,i){var ptr=environ_buf+bufSize;HEAPU32[__environ+i*4>>2]=ptr;writeAsciiToMemory(string,ptr);bufSize+=string.length+1});return 0}function _environ_sizes_get(penviron_count,penviron_buf_size){var strings=getEnvStrings();HEAPU32[penviron_count>>2]=strings.length;var bufSize=0;strings.forEach(function(string){bufSize+=string.length+1});HEAPU32[penviron_buf_size>>2]=bufSize;return 0}function _fd_close(fd){return 52}function _fd_read(fd,iov,iovcnt,pnum){return 52}function _fd_seek(fd,offset_low,offset_high,whence,newOffset){return 70}var printCharBuffers=[null,[],[]];function printChar(stream,curr){var buffer=printCharBuffers[stream];if(curr===0||curr===10){(stream===1?out:err)(UTF8ArrayToString(buffer,0));buffer.length=0}else{buffer.push(curr)}}function _fd_write(fd,iov,iovcnt,pnum){var num=0;for(var i=0;i>2];var len=HEAPU32[iov+4>>2];iov+=8;for(var j=0;j>2]=num;return 0}function __isLeapYear(year){return year%4===0&&(year%100!==0||year%400===0)}function __arraySum(array,index){var sum=0;for(var i=0;i<=index;sum+=array[i++]){}return sum}var __MONTH_DAYS_LEAP=[31,29,31,30,31,30,31,31,30,31,30,31];var __MONTH_DAYS_REGULAR=[31,28,31,30,31,30,31,31,30,31,30,31];function __addDays(date,days){var newDate=new Date(date.getTime());while(days>0){var leap=__isLeapYear(newDate.getFullYear());var currentMonth=newDate.getMonth();var daysInCurrentMonth=(leap?__MONTH_DAYS_LEAP:__MONTH_DAYS_REGULAR)[currentMonth];if(days>daysInCurrentMonth-newDate.getDate()){days-=daysInCurrentMonth-newDate.getDate()+1;newDate.setDate(1);if(currentMonth<11){newDate.setMonth(currentMonth+1)}else{newDate.setMonth(0);newDate.setFullYear(newDate.getFullYear()+1)}}else{newDate.setDate(newDate.getDate()+days);return newDate}}return newDate}function intArrayFromString(stringy,dontAddNull,length){var len=length>0?length:lengthBytesUTF8(stringy)+1;var u8array=new Array(len);var numBytesWritten=stringToUTF8Array(stringy,u8array,0,u8array.length);if(dontAddNull)u8array.length=numBytesWritten;return u8array}function writeArrayToMemory(array,buffer){HEAP8.set(array,buffer)}function _strftime(s,maxsize,format,tm){var tm_zone=HEAP32[tm+40>>2];var date={tm_sec:HEAP32[tm>>2],tm_min:HEAP32[tm+4>>2],tm_hour:HEAP32[tm+8>>2],tm_mday:HEAP32[tm+12>>2],tm_mon:HEAP32[tm+16>>2],tm_year:HEAP32[tm+20>>2],tm_wday:HEAP32[tm+24>>2],tm_yday:HEAP32[tm+28>>2],tm_isdst:HEAP32[tm+32>>2],tm_gmtoff:HEAP32[tm+36>>2],tm_zone:tm_zone?UTF8ToString(tm_zone):""};var pattern=UTF8ToString(format);var EXPANSION_RULES_1={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"};for(var rule in EXPANSION_RULES_1){pattern=pattern.replace(new RegExp(rule,"g"),EXPANSION_RULES_1[rule])}var WEEKDAYS=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];var MONTHS=["January","February","March","April","May","June","July","August","September","October","November","December"];function leadingSomething(value,digits,character){var str=typeof value=="number"?value.toString():value||"";while(str.length0?1:0}var compare;if((compare=sgn(date1.getFullYear()-date2.getFullYear()))===0){if((compare=sgn(date1.getMonth()-date2.getMonth()))===0){compare=sgn(date1.getDate()-date2.getDate())}}return compare}function getFirstWeekStartDate(janFourth){switch(janFourth.getDay()){case 0:return new Date(janFourth.getFullYear()-1,11,29);case 1:return janFourth;case 2:return new Date(janFourth.getFullYear(),0,3);case 3:return new Date(janFourth.getFullYear(),0,2);case 4:return new Date(janFourth.getFullYear(),0,1);case 5:return new Date(janFourth.getFullYear()-1,11,31);case 6:return new Date(janFourth.getFullYear()-1,11,30)}}function getWeekBasedYear(date){var thisDate=__addDays(new Date(date.tm_year+1900,0,1),date.tm_yday);var janFourthThisYear=new Date(thisDate.getFullYear(),0,4);var janFourthNextYear=new Date(thisDate.getFullYear()+1,0,4);var firstWeekStartThisYear=getFirstWeekStartDate(janFourthThisYear);var firstWeekStartNextYear=getFirstWeekStartDate(janFourthNextYear);if(compareByDay(firstWeekStartThisYear,thisDate)<=0){if(compareByDay(firstWeekStartNextYear,thisDate)<=0){return thisDate.getFullYear()+1}return thisDate.getFullYear()}return thisDate.getFullYear()-1}var EXPANSION_RULES_2={"%a":function(date){return WEEKDAYS[date.tm_wday].substring(0,3)},"%A":function(date){return WEEKDAYS[date.tm_wday]},"%b":function(date){return MONTHS[date.tm_mon].substring(0,3)},"%B":function(date){return MONTHS[date.tm_mon]},"%C":function(date){var year=date.tm_year+1900;return leadingNulls(year/100|0,2)},"%d":function(date){return leadingNulls(date.tm_mday,2)},"%e":function(date){return leadingSomething(date.tm_mday,2," ")},"%g":function(date){return getWeekBasedYear(date).toString().substring(2)},"%G":function(date){return getWeekBasedYear(date)},"%H":function(date){return leadingNulls(date.tm_hour,2)},"%I":function(date){var twelveHour=date.tm_hour;if(twelveHour==0)twelveHour=12;else if(twelveHour>12)twelveHour-=12;return leadingNulls(twelveHour,2)},"%j":function(date){return leadingNulls(date.tm_mday+__arraySum(__isLeapYear(date.tm_year+1900)?__MONTH_DAYS_LEAP:__MONTH_DAYS_REGULAR,date.tm_mon-1),3)},"%m":function(date){return leadingNulls(date.tm_mon+1,2)},"%M":function(date){return leadingNulls(date.tm_min,2)},"%n":function(){return"\n"},"%p":function(date){if(date.tm_hour>=0&&date.tm_hour<12){return"AM"}return"PM"},"%S":function(date){return leadingNulls(date.tm_sec,2)},"%t":function(){return"\t"},"%u":function(date){return date.tm_wday||7},"%U":function(date){var days=date.tm_yday+7-date.tm_wday;return leadingNulls(Math.floor(days/7),2)},"%V":function(date){var val=Math.floor((date.tm_yday+7-(date.tm_wday+6)%7)/7);if((date.tm_wday+371-date.tm_yday-2)%7<=2){val++}if(!val){val=52;var dec31=(date.tm_wday+7-date.tm_yday-1)%7;if(dec31==4||dec31==5&&__isLeapYear(date.tm_year%400-1)){val++}}else if(val==53){var jan1=(date.tm_wday+371-date.tm_yday)%7;if(jan1!=4&&(jan1!=3||!__isLeapYear(date.tm_year)))val=1}return leadingNulls(val,2)},"%w":function(date){return date.tm_wday},"%W":function(date){var days=date.tm_yday+7-(date.tm_wday+6)%7;return leadingNulls(Math.floor(days/7),2)},"%y":function(date){return(date.tm_year+1900).toString().substring(2)},"%Y":function(date){return date.tm_year+1900},"%z":function(date){var off=date.tm_gmtoff;var ahead=off>=0;off=Math.abs(off)/60;off=off/60*100+off%60;return(ahead?"+":"-")+String("0000"+off).slice(-4)},"%Z":function(date){return date.tm_zone},"%%":function(){return"%"}};pattern=pattern.replace(/%%/g,"\0\0");for(var rule in EXPANSION_RULES_2){if(pattern.includes(rule)){pattern=pattern.replace(new RegExp(rule,"g"),EXPANSION_RULES_2[rule](date))}}pattern=pattern.replace(/\0\0/g,"%");var bytes=intArrayFromString(pattern,false);if(bytes.length>maxsize){return 0}writeArrayToMemory(bytes,s);return bytes.length-1}function _strftime_l(s,maxsize,format,tm,loc){return _strftime(s,maxsize,format,tm)}function _proc_exit(code){EXITSTATUS=code;if(!keepRuntimeAlive()){ABORT=true}quit_(code,new ExitStatus(code))}function exitJS(status,implicit){EXITSTATUS=status;_proc_exit(status)}function handleException(e){if(e instanceof ExitStatus||e=="unwind"){return EXITSTATUS}quit_(1,e)}function allocateUTF8OnStack(str){var size=lengthBytesUTF8(str)+1;var ret=stackAlloc(size);stringToUTF8Array(str,HEAP8,ret,size);return ret}var wasmImports={"k":___cxa_throw,"a":_abort,"h":_emscripten_memcpy_big,"j":_emscripten_resize_heap,"d":_environ_get,"e":_environ_sizes_get,"f":_fd_close,"g":_fd_read,"i":_fd_seek,"b":_fd_write,"c":_strftime_l};var asm=createWasm();var ___wasm_call_ctors=function(){return(___wasm_call_ctors=Module["asm"]["m"]).apply(null,arguments)};var _main=Module["_main"]=function(){return(_main=Module["_main"]=Module["asm"]["n"]).apply(null,arguments)};var ___errno_location=function(){return(___errno_location=Module["asm"]["__errno_location"]).apply(null,arguments)};var stackAlloc=function(){return(stackAlloc=Module["asm"]["p"]).apply(null,arguments)};var ___cxa_is_pointer_type=function(){return(___cxa_is_pointer_type=Module["asm"]["q"]).apply(null,arguments)};var calledRun;dependenciesFulfilled=function runCaller(){if(!calledRun)run();if(!calledRun)dependenciesFulfilled=runCaller};function callMain(args=[]){var entryFunction=_main;args.unshift(thisProgram);var argc=args.length;var argv=stackAlloc((argc+1)*4);var argv_ptr=argv>>2;args.forEach(arg=>{HEAP32[argv_ptr++]=allocateUTF8OnStack(arg)});HEAP32[argv_ptr]=0;try{var ret=entryFunction(argc,argv);exitJS(ret,true);return ret}catch(e){return handleException(e)}}function run(args=arguments_){if(runDependencies>0){return}preRun();if(runDependencies>0){return}function doRun(){if(calledRun)return;calledRun=true;Module["calledRun"]=true;if(ABORT)return;initRuntime();preMain();if(shouldRunNow)callMain(args);postRun()}{doRun()}}var shouldRunNow=true;run(); diff --git a/frontend/resources/public/wasm/build/main.wasm b/frontend/resources/public/wasm/build/main.wasm new file mode 100755 index 0000000000..2cb5f4cdf4 Binary files /dev/null and b/frontend/resources/public/wasm/build/main.wasm differ diff --git a/frontend/resources/public/wasm/int.h b/frontend/resources/public/wasm/int.h deleted file mode 100644 index 6080266dd5..0000000000 --- a/frontend/resources/public/wasm/int.h +++ /dev/null @@ -1,10 +0,0 @@ -#pragma once - -typedef __INT8_TYPE__ int8_t; -typedef __UINT8_TYPE__ uint8_t; - -typedef __INT16_TYPE__ int16_t; -typedef __UINT16_TYPE__ uint16_t; - -typedef __INT32_TYPE__ int32_t; -typedef __UINT32_TYPE__ uint32_t; diff --git a/frontend/resources/public/wasm/labs/Makefile b/frontend/resources/public/wasm/labs/Makefile new file mode 100644 index 0000000000..077ae98dc4 --- /dev/null +++ b/frontend/resources/public/wasm/labs/Makefile @@ -0,0 +1,3 @@ +all: + em++ --no-entry -sEXPORT_KEEPALIVE=1 -sENVIRONMENT=web -sFILESYSTEM=0 vector.cpp -o vector.wasm + diff --git a/frontend/resources/public/wasm/labs/test-vector.mjs b/frontend/resources/public/wasm/labs/test-vector.mjs new file mode 100644 index 0000000000..5721489d43 --- /dev/null +++ b/frontend/resources/public/wasm/labs/test-vector.mjs @@ -0,0 +1,9 @@ +import Vector from './vector.mjs' + +console.log(Vector) +async function main() +{ + const vector = await Vector() +} + +main() diff --git a/frontend/resources/public/wasm/labs/vector.cpp b/frontend/resources/public/wasm/labs/vector.cpp new file mode 100644 index 0000000000..3af1f19d78 --- /dev/null +++ b/frontend/resources/public/wasm/labs/vector.cpp @@ -0,0 +1,25 @@ +#include + +#include +#include +#include + +enum ShapeType +{ + FRAME = 0, + RECT, + ELLIPSE, +}; + +struct Shape { + ShapeType type; + + Shape() : type(FRAME) {}; +}; + +static std::shared_ptr root; + +void EMSCRIPTEN_KEEPALIVE resize(const std::shared_ptr ptr) +{ + std::cout << "resize" << std::endl; +} diff --git a/frontend/resources/public/wasm/labs/vector.wasm b/frontend/resources/public/wasm/labs/vector.wasm new file mode 100755 index 0000000000..d5cbebf88c Binary files /dev/null and b/frontend/resources/public/wasm/labs/vector.wasm differ diff --git a/frontend/resources/public/wasm/src/Matrix23.h b/frontend/resources/public/wasm/src/Matrix2D.h similarity index 63% rename from frontend/resources/public/wasm/src/Matrix23.h rename to frontend/resources/public/wasm/src/Matrix2D.h index d56ed3ca37..5266cb1ec1 100644 --- a/frontend/resources/public/wasm/src/Matrix23.h +++ b/frontend/resources/public/wasm/src/Matrix2D.h @@ -4,20 +4,20 @@ #include template -struct Matrix23 { +struct Matrix2D { // a c tx // b d ty T a, b, c, d, tx, ty; - Matrix23() : a(1), b(0), c(0), d(1), tx(0), ty(0) {} - Matrix23(T a, T b, T c, T d, T tx, T ty) : a(a), b(b), c(c), d(d), tx(tx), ty(ty) {} - Matrix23(const Matrix23& other) : a(other.a), b(other.b), c(other.c), d(other.d), tx(other.tx), ty(other.ty) {} + Matrix2D() : a(1), b(0), c(0), d(1), tx(0), ty(0) {} + Matrix2D(T a, T b, T c, T d, T tx, T ty) : a(a), b(b), c(c), d(d), tx(tx), ty(ty) {} + Matrix2D(const Matrix2D& other) : a(other.a), b(other.b), c(other.c), d(other.d), tx(other.tx), ty(other.ty) {} auto determinant() const { return a * d - b * c; } - Matrix23& identity() + Matrix2D& identity() { a = 1; b = 0; @@ -28,14 +28,14 @@ struct Matrix23 { return *this; } - Matrix23& translate(T x, T y) + Matrix2D& translate(T x, T y) { tx += x; ty += y; return *this; } - Matrix23& scale(T x, T y) + Matrix2D& scale(T x, T y) { a *= x; b *= y; @@ -44,7 +44,7 @@ struct Matrix23 { return *this; } - Matrix23& rotate(auto angle) + Matrix2D& rotate(auto angle) { auto cos = std::cos(angle); auto sin = std::sin(angle); @@ -62,7 +62,7 @@ struct Matrix23 { return *this; } - Matrix23 invert() + Matrix2D invert() { auto det = determinant(); if (det == 0) @@ -80,7 +80,7 @@ struct Matrix23 { }; } - Matrix23 operator*(const Matrix23& other) + Matrix2D operator*(const Matrix2D& other) { // M N // a c x a c x @@ -95,11 +95,28 @@ struct Matrix23 { tx * other.b + ty * other.d + other.ty }; } + + static Matrix2D create_translation(const T x, const T y) + { + return { 1, 0, 0, 1, x, y }; + } + + static Matrix2D create_scale(const T x, const T y) + { + return { x, 0, 0, y, 0, 0 }; + } + + static Matrix2D create_rotation(auto angle) + { + auto c = std::cos(angle); + auto s = std::sin(angle); + return { c, s, -s, c, 0, 0 }; + } }; template -std::ostream &operator<<(std::ostream &os, const Matrix23 &matrix) +std::ostream &operator<<(std::ostream &os, const Matrix2D &matrix) { - os << "Matrix23(" << matrix.a << ", " << matrix.b << ", " << matrix.c << ", " << matrix.d << ", " << matrix.tx << ", " << matrix.ty << ")"; + os << "Matrix2D(" << matrix.a << ", " << matrix.b << ", " << matrix.c << ", " << matrix.d << ", " << matrix.tx << ", " << matrix.ty << ")"; return os; } diff --git a/frontend/resources/public/wasm/src/Shape.h b/frontend/resources/public/wasm/src/Shape.h new file mode 100644 index 0000000000..1611f509af --- /dev/null +++ b/frontend/resources/public/wasm/src/Shape.h @@ -0,0 +1,65 @@ +#pragma once + +#include +#include + +#include "Vector2.h" +#include "Matrix2D.h" +#include "Color.h" + +enum ShapeType +{ + FRAME = 0, + RECT, + ELLIPSE, + PATH, + TEXT +}; + +enum PaintType +{ + COLOR = 0, + IMAGE, + PATTERN, + LINEAR_GRADIENT, + RADIAL_GRADIENT +}; + +struct MatrixTransform +{ + Matrix2D concatenatedMatrix; + Matrix2D matrix; +}; + +struct Transform +{ + Vector2 position; + Vector2 scale; + float rotation; +}; + +struct Paint +{ + PaintType type; +}; + +struct Stroke +{ + float width; + Paint paint; +}; + +struct Fill +{ + Paint paint; +}; + +struct Shape +{ + ShapeType type; + Transform transform; + std::shared_ptr parent; + std::vector> children; + // std::vector strokes; + // std::vector fills; +}; diff --git a/frontend/resources/public/wasm/src/Vector2.h b/frontend/resources/public/wasm/src/Vector2.h index 5a037e451d..69eab2751e 100644 --- a/frontend/resources/public/wasm/src/Vector2.h +++ b/frontend/resources/public/wasm/src/Vector2.h @@ -4,6 +4,7 @@ #include #include "Interpolation.h" +#include "Matrix2D.h" template struct Vector2 { @@ -108,7 +109,7 @@ struct Vector2 { ); } - Vector2 operator*(const Matrix23 m) + Vector2 operator*(const Matrix2D m) { return { x * m.a + y * m.c + m.tx, diff --git a/frontend/resources/public/wasm/src/main.cpp b/frontend/resources/public/wasm/src/main.cpp index 6ed2155455..523f701d94 100644 --- a/frontend/resources/public/wasm/src/main.cpp +++ b/frontend/resources/public/wasm/src/main.cpp @@ -2,7 +2,7 @@ #include #include "Interpolation.h" -#include "Matrix23.h" +#include "Matrix2D.h" #include "Vector2.h" #include "Box2.h" @@ -16,7 +16,7 @@ int main(int argc, char** argv) Vector2 a(1, 0); Vector2 b(0, 1); - Matrix23 m; + Matrix2D m; std::cout << m << std::endl;