diff --git a/common/src/app/common/types/modifiers.cljc b/common/src/app/common/types/modifiers.cljc index 5097550e96..4866e5ebb3 100644 --- a/common/src/app/common/types/modifiers.cljc +++ b/common/src/app/common/types/modifiers.cljc @@ -389,6 +389,7 @@ ([vector] (move (empty) vector))) +;; This function is never used (defn move-parent-modifiers ([x y] (move-parent (empty) (gpt/point x y))) @@ -403,6 +404,7 @@ ([vector origin transform transform-inverse] (resize (empty) vector origin transform transform-inverse))) +;; This function is never used (defn resize-parent-modifiers ([vector origin] (resize-parent (empty) vector origin)) diff --git a/frontend/resources/public/wasm/Makefile b/frontend/resources/public/wasm/Makefile index 8fc4eb217b..189974bc29 100644 --- a/frontend/resources/public/wasm/Makefile +++ b/frontend/resources/public/wasm/Makefile @@ -1,3 +1,10 @@ all: 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 + clang \ + -target wasm32 \ + -nostdlib \ + -Wl,--no-entry \ + -Wl,--export-all \ + -o build/resize.wasm \ + src/resize.c + diff --git a/frontend/resources/public/wasm/NOTAS.md b/frontend/resources/public/wasm/NOTAS.md deleted file mode 100644 index 1110c5085c..0000000000 --- a/frontend/resources/public/wasm/NOTAS.md +++ /dev/null @@ -1,72 +0,0 @@ -# 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). -- [ ] Implementar CMake para construir el proyecto. - -Para compilar el código en C++ se puede usar la siguiente línea: - -```sh -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) - -## 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/build/main.js b/frontend/resources/public/wasm/build/main.js deleted file mode 100644 index 0416d29db1..0000000000 --- a/frontend/resources/public/wasm/build/main.js +++ /dev/null @@ -1 +0,0 @@ -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 deleted file mode 100755 index 2cb5f4cdf4..0000000000 Binary files a/frontend/resources/public/wasm/build/main.wasm and /dev/null differ diff --git a/frontend/resources/public/wasm/labs/Makefile b/frontend/resources/public/wasm/labs/Makefile deleted file mode 100644 index 077ae98dc4..0000000000 --- a/frontend/resources/public/wasm/labs/Makefile +++ /dev/null @@ -1,3 +0,0 @@ -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 deleted file mode 100644 index 5721489d43..0000000000 --- a/frontend/resources/public/wasm/labs/test-vector.mjs +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 3af1f19d78..0000000000 --- a/frontend/resources/public/wasm/labs/vector.cpp +++ /dev/null @@ -1,25 +0,0 @@ -#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 deleted file mode 100755 index d5cbebf88c..0000000000 Binary files a/frontend/resources/public/wasm/labs/vector.wasm and /dev/null differ diff --git a/frontend/resources/public/wasm/src/Box2.h b/frontend/resources/public/wasm/src/Box2.h deleted file mode 100644 index 44e28c5a1a..0000000000 --- a/frontend/resources/public/wasm/src/Box2.h +++ /dev/null @@ -1,54 +0,0 @@ -#pragma once - -#include "Vector2.h" - -template -struct Box2 -{ - Vector2 position; - Vector2 size; - - Box2(T x, T y, T width, T height) { - position.set(x, y); - size.set(width, height); - } - Box2(const Box2& box) : position(box.position), size(box.size) {} - Box2(const Vector2& position, const Vector2& size) : position(position), size(size) {} - - auto left() const - { - return position.x; - } - - auto right() const - { - return position.x + size.x; - } - - auto top() const - { - return position.y; - } - - auto bottom() const - { - return position.y + size.y; - } - - bool contains(const Vector2& point) const { - return point.x > position.x - && point.x < position.x + size.x - && point.y > position.y - && point.y < position.y + size.y; - } - - bool intersects(const Box2 &other) const { - if (left() > other.right() || right() < other.left()) - return false; - - if (top() > other.bottom() || bottom() < other.top()) - return false; - - return true; - } -}; diff --git a/frontend/resources/public/wasm/src/Color.h b/frontend/resources/public/wasm/src/Color.h deleted file mode 100644 index 5d8b59b0dd..0000000000 --- a/frontend/resources/public/wasm/src/Color.h +++ /dev/null @@ -1,96 +0,0 @@ -#pragma once - -template -struct Color { - T r, g, b, a; - - Color& set(T new_r, T new_g, T new_b, T new_a) - { - r = new_r; - g = new_g; - b = new_b; - a = new_a; - return *this; - } - - Color& set(T new_r, T new_g, T new_b) - { - r = new_r; - g = new_g; - b = new_b; - return *this; - } - - Color operator+(const Color other) - { - return { - r + other.r, - g + other.g, - b + other.b - }; - } - - Color operator-(const Color other) - { - return { - r - other.r, - g - other.g, - b - other.b - }; - } - - Color operator*(const Color other) - { - return { - r * other.r, - g * other.g, - b * other.b - }; - } - - Color operator/(const Color other) - { - return { - r / other.r, - g / other.g, - b / other.b - }; - } - - - Color operator+(const T scalar) - { - return { - r + scalar, - g + scalar, - b + scalar - }; - } - - Color operator-(const T scalar) - { - return { - r - scalar, - g - scalar, - b - scalar - }; - } - - Color operator*(const T scalar) - { - return { - r * scalar, - g * scalar, - b * scalar - }; - } - - Color operator/(const T scalar) - { - return { - r / scalar, - g / scalar, - b / scalar - }; - } -} diff --git a/frontend/resources/public/wasm/src/Interpolation.h b/frontend/resources/public/wasm/src/Interpolation.h deleted file mode 100644 index cd5241fcf7..0000000000 --- a/frontend/resources/public/wasm/src/Interpolation.h +++ /dev/null @@ -1,20 +0,0 @@ -#pragma once - -namespace Interpolation { - - template - T linear(const T x, const T a, const T b) { - return (1 - x) * a + x * b; - } - - template - T quadratic(const T x, const T a, const T b, const T c) { - return linear(x, linear(x, a, b), linear(x, b, c)); - } - - template - T cubic(const T x, const T a, const T b, const T c, const T d) { - return linear(x, quadratic(x, a, b, c), quadratic(x, b, c, d)); - } - -} diff --git a/frontend/resources/public/wasm/src/Matrix2D.h b/frontend/resources/public/wasm/src/Matrix2D.h deleted file mode 100644 index 5266cb1ec1..0000000000 --- a/frontend/resources/public/wasm/src/Matrix2D.h +++ /dev/null @@ -1,122 +0,0 @@ -#pragma once - -#include -#include - -template -struct Matrix2D { - // a c tx - // b d ty - T a, b, c, d, tx, 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; - } - - Matrix2D& identity() - { - a = 1; - b = 0; - c = 0; - d = 1; - tx = 0; - ty = 0; - return *this; - } - - Matrix2D& translate(T x, T y) - { - tx += x; - ty += y; - return *this; - } - - Matrix2D& scale(T x, T y) - { - a *= x; - b *= y; - c *= x; - d *= y; - return *this; - } - - Matrix2D& rotate(auto angle) - { - auto cos = std::cos(angle); - auto sin = std::sin(angle); - - auto new_a = a * cos + c * sin; - auto new_b = b * cos + d * sin; - auto new_c = c * cos - a * sin; - auto new_d = d * cos - b * sin; - - a = new_a; - b = new_b; - c = new_c; - d = new_d; - - return *this; - } - - Matrix2D invert() - { - auto det = determinant(); - if (det == 0) - { - return *this; - } - auto inv_det = 1.0 / det; - return { - d * inv_det, - -b * inv_det, - -c * inv_det, - a * inv_det, - (c * ty - d * tx) * inv_det, - (b * tx - a * ty) * inv_det - }; - } - - Matrix2D operator*(const Matrix2D& other) - { - // M N - // a c x a c x - // b d y x b d y = T - // 0 0 1 0 0 1 - return { - a * other.a + b * other.c, - a * other.b + b * other.d, - c * other.a + d * other.c, - c * other.b + d * other.d, - tx * other.a + ty * other.c + other.tx, - 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 Matrix2D &matrix) -{ - 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 deleted file mode 100644 index 1611f509af..0000000000 --- a/frontend/resources/public/wasm/src/Shape.h +++ /dev/null @@ -1,65 +0,0 @@ -#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 deleted file mode 100644 index 69eab2751e..0000000000 --- a/frontend/resources/public/wasm/src/Vector2.h +++ /dev/null @@ -1,198 +0,0 @@ -#pragma once - -#include -#include - -#include "Interpolation.h" -#include "Matrix2D.h" - -template -struct Vector2 { - T x, y; - - Vector2() : x(0), y(0) {} - Vector2(T x, T y) : x(x), y(y) {} - Vector2(const Vector2& other) : x(other.x), y(other.y) {} - - auto dot(const Vector2 &other) const - { - return x * other.x + y * other.y; - } - - auto cross(const Vector2 &other) const - { - return x * other.y - y * other.x; - } - - auto direction() const - { - return std::atan2(y, x); - } - - auto length() const - { - return std::hypot(x, y); - } - - auto lengthSquared() const - { - return x * x + y * y; - } - - Vector2& normalize() - { - auto l = length(); - return set(x / l, x / l); - } - - Vector2& perpLeft() - { - return set(y, -x); - } - - Vector2& perpRight() - { - return set(-y, x); - } - - Vector2& rotate(auto rotation) - { - auto c = std::cos(rotation); - auto s = std::sin(rotation); - return set( - c * x - s * y, - s * x + c * y - ); - } - - Vector2& scale(auto s) - { - return set( - x * s, - y * s - ); - } - - Vector2& set(T newX, T newY) - { - x = newX; - y = newY; - return *this; - } - - Vector2& copy(const Vector2& other) - { - return set(other.x, other.y); - } - - Vector2& linear(auto p, Vector2& a, Vector2& b) - { - return set( - Interpolation::linear(p, a.x, b.x), - Interpolation::linear(p, a.y, b.y) - ); - } - - Vector2& quadratic(auto p, Vector2& a, Vector2& b, Vector2& c) - { - return set( - Interpolation::quadratic(p, a.x, b.x, c.x), - Interpolation::quadratic(p, a.y, b.y, c.y) - ); - } - - Vector2& cubic(auto p, Vector2& a, Vector2& b, Vector2& c, Vector2& d) - { - return set( - Interpolation::cubic(p, a.x, b.x, c.x, d.x), - Interpolation::cubic(p, a.y, b.y, c.y, d.y) - ); - } - - Vector2 operator*(const Matrix2D m) - { - return { - x * m.a + y * m.c + m.tx, - x * m.b + y * m.d + m.ty - }; - } - - Vector2 operator+(const Vector2 other) - { - return { - x + other.x, - y + other.y - }; - } - - Vector2 operator-(const Vector2 other) - { - return { - x - other.x, - y - other.y - }; - } - - Vector2 operator*(const Vector2 other) - { - return { - x * other.x, - y * other.y - }; - } - - Vector2 operator/(const Vector2 other) - { - return { - x / other.x, - y / other.y - }; - } - - Vector2 operator+(T scalar) - { - return { - x + scalar, - y + scalar - }; - } - - Vector2 operator-(T scalar) - { - return { - x - scalar, - y - scalar - }; - } - - Vector2 operator*(T scalar) - { - return { - x * scalar, - y * scalar - }; - } - - Vector2 operator/(T scalar) - { - return { - x / scalar, - y / scalar - }; - } - - Vector2 operator-() const - { - return { - -x, - -y - }; - } -}; - -template -std::ostream& operator<<(std::ostream &os, const Vector2& vector) -{ - os << "Vector2(" << vector.x << ", " << vector.y << ")"; - return os; -} diff --git a/frontend/resources/public/wasm/src/main.cpp b/frontend/resources/public/wasm/src/main.cpp deleted file mode 100644 index 523f701d94..0000000000 --- a/frontend/resources/public/wasm/src/main.cpp +++ /dev/null @@ -1,34 +0,0 @@ -#include -#include - -#include "Interpolation.h" -#include "Matrix2D.h" -#include "Vector2.h" -#include "Box2.h" - -void resize() -{ - -} - -int main(int argc, char** argv) -{ - Vector2 a(1, 0); - Vector2 b(0, 1); - - Matrix2D m; - - std::cout << m << std::endl; - - std::cout << m.rotate(M_PI / 2) << std::endl; - - Vector2 a2 = a * m; - Vector2 b2 = b * m; - - std::cout << a << ", " << a2 << std::endl; - std::cout << b << ", " << b2 << std::endl; - - std::cout << "Hello, World!" << std::endl; - - return 0; -} diff --git a/frontend/src/app/main/data/workspace/modifiers.cljs b/frontend/src/app/main/data/workspace/modifiers.cljs index 110439add6..f393850881 100644 --- a/frontend/src/app/main/data/workspace/modifiers.cljs +++ b/frontend/src/app/main/data/workspace/modifiers.cljs @@ -392,6 +392,7 @@ (reduce merge {})) undo-id (js/Symbol)] + (js/console.log (clj->js object-modifiers) (clj->js text-modifiers) (clj->js objects)) (rx/concat (if undo-transation? (rx/of (dwu/start-undo-transaction undo-id)) diff --git a/frontend/src/app/main/data/workspace/transforms.cljs b/frontend/src/app/main/data/workspace/transforms.cljs index ed43feba55..6f27541eb1 100644 --- a/frontend/src/app/main/data/workspace/transforms.cljs +++ b/frontend/src/app/main/data/workspace/transforms.cljs @@ -29,6 +29,7 @@ [app.main.snap :as snap] [app.main.streams :as ms] [app.util.dom :as dom] + [app.wasm :as wasm] [beicon.core :as rx] [cljs.spec.alpha :as s] [potok.core :as ptk])) @@ -175,6 +176,9 @@ set-fix-height? (not (mth/close? (:y scalev) 1)) + ;; Creates the initial structure of modifiers + ;; that will be later filled in the create-modif-tree + ;; call modifiers (-> (ctm/empty) (cond-> displacement @@ -190,7 +194,10 @@ (cond-> scale-text (ctm/scale-content (:x scalev)))) - modif-tree (dwm/create-modif-tree ids modifiers)] + ;; Fills modifiers using identifiers + modif-tree (dwm/create-modif-tree ids modifiers)] + (js/console.log (clj->js modif-tree)) + (wasm/resize handler ids shape) (rx/of (dwm/set-modifiers modif-tree)))) ;; Unifies the instantaneous proportion lock modifier @@ -209,7 +216,7 @@ ptk/WatchEvent (watch [_ state stream] (let [initial-position @ms/mouse-position - stoper (rx/filter ms/mouse-up? stream) + stopper (rx/filter ms/mouse-up? stream) layout (:workspace-layout state) page-id (:current-page-id state) focus (:workspace-focus-selected state) @@ -226,7 +233,7 @@ (->> (snap/closest-snap-point page-id resizing-shapes objects layout zoom focus point) (rx/map #(conj current %))))) (rx/mapcat (partial resize shape initial-position layout)) - (rx/take-until stoper)) + (rx/take-until stopper)) (rx/of (dwm/apply-modifiers) (finish-transform)))))))) diff --git a/frontend/src/app/main/ui/workspace/viewport/selection.cljs b/frontend/src/app/main/ui/workspace/viewport/selection.cljs index a3977510c7..72c5e42485 100644 --- a/frontend/src/app/main/ui/workspace/viewport/selection.cljs +++ b/frontend/src/app/main/ui/workspace/viewport/selection.cljs @@ -370,6 +370,7 @@ (when (dom/left-mouse? event) (dom/stop-propagation event) (st/emit! (dw/start-resize current-position selected shape)))) + ;;(js/console.log event (dw/start-resize current-position selected shape)))) on-rotate (fn [event] @@ -410,6 +411,7 @@ (when (dom/left-mouse? event) (dom/stop-propagation event) (st/emit! (dw/start-resize current-position #{shape-id} shape)))) + ;;(js/console.log event (clj->js (dw/start-resize current-position #{shape-id} shape))))) on-rotate (fn [event] diff --git a/frontend/src/app/wasm.cljs b/frontend/src/app/wasm.cljs index c5419858f1..85db6c4503 100644 --- a/frontend/src/app/wasm.cljs +++ b/frontend/src/app/wasm.cljs @@ -2,7 +2,7 @@ (:require [promesa.core :as p])) -(defonce instance (atom nil)) +(defonce assembly (atom nil)) (defn load-wasm "Loads a WebAssembly module" @@ -10,7 +10,7 @@ (-> (p/let [response (js/fetch uri) array-buffer (.arrayBuffer response) - assembly (.instantiate js/WebAssembly array-buffer)] + assembly (.instantiate js/WebAssembly array-buffer (js-obj "env" (js-obj)))] assembly) (p/catch (fn [error] (prn "error: " error))))) @@ -18,18 +18,30 @@ "Initializes WebAssembly module" [] (p/then - (load-wasm "wasm/add.wasm") - (fn [assembly] - (let [operations (js/Int32Array. - assembly.instance.exports.memory.buffer ;; buffer we want to use - assembly.instance.exports.operations.value ;; offset of pointer 'operations' - (* 2048 12))] - (aset operations 0 2) - (aset operations 1 2) - (.set operations #js [4 5 -1] 3) - (js/console.time "compute") - (assembly.instance.exports.compute) - (js/console.timeEnd "compute") - (js/console.log assembly) - ) - (reset! instance assembly.instance)))) + (load-wasm "wasm/build/resize.wasm") + (fn [asm] + (reset! assembly + (js-obj "instance" asm.instance + "module" asm.module + "exports" asm.instance.exports))))) + +(defn get-handler-id + [handler] + (case handler + :top 0 + :top-right 1 + :right 2 + :bottom-right 3 + :bottom 4 + :bottom-left 5 + :left 6 + :top-left 7)) + +(defn resize + [handler ids shape] + ;; TODO: Tenemos que resolver los diferentes shapes + ;; para subirlos al módulo de WebAssembly. + (when @assembly + (let [asm @assembly] + (js/console.log (clj->js ids) (clj->js shape)) + (asm.exports.resize (get-handler-id handler) ids shape))))