iron.h 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090
  1. #pragma once
  2. #pragma clang diagnostic ignored "-Wincompatible-pointer-types"
  3. #include <math.h>
  4. #include <stdlib.h>
  5. #include <string.h>
  6. #include <ctype.h>
  7. #include "iron_system.h"
  8. #include "iron_thread.h"
  9. #include "iron_gpu.h"
  10. #include "iron_file.h"
  11. #include "iron_string.h"
  12. #include "iron_array.h"
  13. #include "iron_map.h"
  14. #include "iron_armpack.h"
  15. #include "iron_json.h"
  16. #include "iron_gc.h"
  17. #include "iron_obj.h"
  18. #include "iron_vec2.h"
  19. #include "iron_vec3.h"
  20. #include "iron_vec4.h"
  21. #include "iron_quat.h"
  22. #include "iron_mat3.h"
  23. #include "iron_mat4.h"
  24. #include "iron_ui.h"
  25. #include "iron_ui_nodes.h"
  26. #include "iron_draw.h"
  27. #ifdef IRON_WINDOWS
  28. #include <Windows.h>
  29. #endif
  30. #ifdef WITH_AUDIO
  31. #include "iron_audio.h"
  32. #endif
  33. #ifdef WITH_EMBED
  34. #include EMBED_H_PATH
  35. #endif
  36. #ifdef WITH_ONNX
  37. #include <onnxruntime_c_api.h>
  38. #ifdef IRON_WINDOWS
  39. #include <dml_provider_factory.h>
  40. #elif defined(IRON_MACOS)
  41. #include <coreml_provider_factory.h>
  42. #endif
  43. const OrtApi *ort = NULL;
  44. OrtEnv *ort_env;
  45. OrtSessionOptions *ort_session_options;
  46. OrtSession *session = NULL;
  47. #endif
  48. int _argc;
  49. char **_argv;
  50. #ifdef WITH_EVAL
  51. #include "quickjs.h"
  52. #include "quickjs-libc.h"
  53. JSRuntime *js_runtime = NULL;
  54. JSContext *js_ctx;
  55. #ifdef WITH_PLUGINS
  56. void plugin_api_init();
  57. #endif
  58. void js_init() {
  59. js_runtime = JS_NewRuntime();
  60. js_ctx = JS_NewContext(js_runtime);
  61. js_std_add_helpers(js_ctx, _argc, _argv);
  62. js_init_module_std(js_ctx, "std");
  63. js_init_module_os(js_ctx, "os");
  64. #ifdef WITH_PLUGINS
  65. plugin_api_init();
  66. #endif
  67. }
  68. // float alang_eval(char *data);
  69. float js_eval(const char *js) {
  70. // return alang_eval(js);
  71. if (js_runtime == NULL) {
  72. js_init();
  73. }
  74. JSValue ret = JS_Eval(js_ctx, js, strlen(js), "iron", JS_EVAL_TYPE_GLOBAL);
  75. if (JS_IsException(ret)) {
  76. js_std_dump_error(js_ctx);
  77. JS_ResetUncatchableError(js_ctx);
  78. }
  79. double d;
  80. JS_ToFloat64(js_ctx, &d, ret);
  81. JS_RunGC(js_runtime);
  82. if (d != d) { // nan
  83. d = 0.0;
  84. }
  85. return d;
  86. }
  87. JSValue js_call_result;
  88. JSValue *js_call_arg(void *p, int argc, JSValue *argv) {
  89. if (js_runtime == NULL) {
  90. js_init();
  91. }
  92. JSValue fn = *(JSValue *)p;
  93. JSValue global_obj = JS_GetGlobalObject(js_ctx);
  94. js_call_result = JS_Call(js_ctx, fn, global_obj, argc, argv);
  95. if (JS_IsException(js_call_result)) {
  96. js_std_dump_error(js_ctx);
  97. JS_ResetUncatchableError(js_ctx);
  98. }
  99. JS_FreeValue(js_ctx, global_obj);
  100. return &js_call_result;
  101. }
  102. char *js_call_ptr(void *p, void *arg) {
  103. JSValue argv[] = { JS_NewInt64(js_ctx, (int64_t)arg) };
  104. return (char *)JS_ToCString(js_ctx, *js_call_arg(p, 1, argv));
  105. }
  106. char *js_call_ptr_str(void *p, void *arg0, char *arg1) {
  107. JSValue argv[] = { JS_NewInt64(js_ctx, (int64_t)arg0), JS_NewString(js_ctx, arg1) };
  108. return (char *)JS_ToCString(js_ctx, *js_call_arg(p, 2, argv));
  109. }
  110. void *js_pcall_str(void *p, char *arg0) {
  111. JSValue argv[] = { JS_NewString(js_ctx, arg0) };
  112. int64_t result;
  113. JS_ToInt64(js_ctx, &result, *js_call_arg(p, 1, argv));
  114. return (void *)result;
  115. }
  116. char *js_call(void *p) {
  117. return (char *)JS_ToCString(js_ctx, *js_call_arg(p, 0, NULL));
  118. }
  119. #else
  120. void js_init() {}
  121. float js_eval(const char *js) { return 0.0; }
  122. void *js_call_arg(void *p, int argc, void *argv) { return NULL; }
  123. char *js_call_ptr(void *p, void *arg) { return NULL; }
  124. char *js_call_ptr_str(void *p, void *arg0, char *arg1) { return NULL; }
  125. void *js_pcall_str(void *p, char *arg0) { return NULL; }
  126. char *js_call(void *p) { return NULL; }
  127. #endif
  128. #ifdef WITH_EMBED
  129. buffer_t *embed_get(char *key) {
  130. #ifdef IRON_WINDOWS
  131. key = string_replace_all(key, "\\", "/");
  132. #endif
  133. for (int i = 0; i < embed_count; ++i) {
  134. if (strcmp(embed_keys[i], key) == 0) {
  135. buffer_t *buffer = buffer_create(0);
  136. buffer->buffer = embed_values[i];
  137. buffer->length = embed_sizes[i];
  138. return buffer;
  139. }
  140. }
  141. return NULL;
  142. }
  143. #endif
  144. #define f64 double
  145. #define i64 int64_t
  146. #define u64 uint64_t
  147. #define f32 float
  148. #define i32 int32_t
  149. #define u32 uint32_t
  150. #define i16 int16_t
  151. #define u16 uint16_t
  152. #define i8 int8_t
  153. #define u8 uint8_t
  154. #define string_t char
  155. #define any void *
  156. #define any_ptr void **
  157. #define f64_ptr f64 *
  158. #define i64_ptr i64 *
  159. #define u64_ptr u64 *
  160. #define f32_ptr f32 *
  161. #define i32_ptr i32 *
  162. #define u32_ptr u32 *
  163. #define i16_ptr i16 *
  164. #define u16_ptr u16 *
  165. #define i8_ptr i8 *
  166. #define u8_ptr u8 *
  167. #define null NULL
  168. #define DEREFERENCE *
  169. #define ADDRESS &
  170. #define ARRAY_ACCESS(a, i) a[i]
  171. f32 f32_nan() {
  172. return NAN;
  173. }
  174. bool f32_isnan(f32 f) {
  175. return isnan(f);
  176. }
  177. void _kickstart();
  178. bool enable_window = true;
  179. bool in_background = false;
  180. int paused_frames = 0;
  181. bool save_and_quit_callback_set = false;
  182. #ifdef IDLE_SLEEP
  183. bool input_down = false;
  184. int last_window_width = 0;
  185. int last_window_height = 0;
  186. #endif
  187. char temp_string[1024 * 32];
  188. char temp_string_vs[1024 * 128];
  189. char temp_string_fs[1024 * 128];
  190. #ifdef IRON_WINDOWS
  191. wchar_t temp_wstring[1024 * 32];
  192. struct HWND__ *iron_windows_window_handle();
  193. #endif
  194. void (*iron_update)(void);
  195. void (*iron_drop_files)(char *);
  196. void (*iron_foreground)(void);
  197. void (*iron_resume)(void);
  198. void (*iron_pause)(void);
  199. void (*iron_background)(void);
  200. void (*iron_shutdown)(void);
  201. void (*iron_pause)(void);
  202. void (*iron_key_down)(int);
  203. void (*iron_key_up)(int);
  204. void (*iron_key_press)(int);
  205. void (*iron_mouse_down)(int, int, int);
  206. void (*iron_mouse_up)(int, int, int);
  207. void (*iron_mouse_move)(int, int, int, int);
  208. void (*iron_mouse_wheel)(int);
  209. void (*iron_touch_down)(int, int, int);
  210. void (*iron_touch_up)(int, int, int);
  211. void (*iron_touch_move)(int, int, int);
  212. void (*iron_pen_down)(int, int, float);
  213. void (*iron_pen_up)(int, int, float);
  214. void (*iron_pen_move)(int, int, float);
  215. #ifdef WITH_GAMEPAD
  216. void (*iron_gamepad_axis)(int, int, float);
  217. void (*iron_gamepad_button)(int, int, float);
  218. #endif
  219. void (*iron_save_and_quit)(bool);
  220. char *_substring(char *s, int32_t start, int32_t end) {
  221. char *buffer = calloc(1, end - start + 1);
  222. for (int i = 0; i < end - start; ++i) {
  223. buffer[i] = s[start + i];
  224. }
  225. return buffer;
  226. }
  227. int kickstart(int argc, char **argv) {
  228. _argc = argc;
  229. _argv = argv;
  230. #ifdef IRON_ANDROID
  231. char *bindir = "/";
  232. #elif defined(IRON_IOS)
  233. char *bindir = "";
  234. #else
  235. char *bindir = argv[0];
  236. #endif
  237. #ifdef IRON_WINDOWS // Handle non-ascii path
  238. HMODULE hmodule = GetModuleHandleW(NULL);
  239. GetModuleFileNameW(hmodule, temp_wstring, 1024);
  240. WideCharToMultiByte(CP_UTF8, 0, temp_wstring, -1, temp_string, 4096, NULL, NULL);
  241. bindir = _substring(temp_string, 0, string_last_index_of(temp_string, "\\"));
  242. #else
  243. bindir = _substring(bindir, 0, string_last_index_of(bindir, "/"));
  244. #endif
  245. char *assetsdir = argc > 1 ? argv[1] : bindir;
  246. // Opening a file
  247. int l = strlen(assetsdir);
  248. if ((l > 6 && assetsdir[l - 6] == '.') ||
  249. (l > 5 && assetsdir[l - 5] == '.') ||
  250. (l > 4 && assetsdir[l - 4] == '.')) {
  251. assetsdir = bindir;
  252. }
  253. for (int i = 2; i < argc; ++i) {
  254. if (strcmp(argv[i], "--nowindow") == 0) {
  255. enable_window = false;
  256. }
  257. }
  258. #if !defined(IRON_MACOS) && !defined(IRON_IOS)
  259. iron_internal_set_files_location(assetsdir);
  260. #endif
  261. iron_threads_init();
  262. iron_display_init();
  263. gc_start(&argc);
  264. _kickstart();
  265. #ifdef WITH_AUDIO
  266. iron_a2_shutdown();
  267. #endif
  268. #ifdef WITH_ONNX
  269. if (ort != NULL) {
  270. ort->ReleaseEnv(ort_env);
  271. ort->ReleaseSessionOptions(ort_session_options);
  272. }
  273. #endif
  274. gc_stop();
  275. return 0;
  276. }
  277. i32 iron_get_arg_count() {
  278. return _argc;
  279. }
  280. string_t *iron_get_arg(i32 index) {
  281. return _argv[index];
  282. }
  283. // ██╗██████╗ ██████╗ ███╗ ██╗ █████╗ ██████╗ ██╗
  284. // ██║██╔══██╗██╔═══██╗████╗ ██║ ██╔══██╗██╔══██╗██║
  285. // ██║██████╔╝██║ ██║██╔██╗ ██║ ███████║██████╔╝██║
  286. // ██║██╔══██╗██║ ██║██║╚██╗██║ ██╔══██║██╔═══╝ ██║
  287. // ██║██║ ██║╚██████╔╝██║ ╚████║ ██║ ██║██║ ██║
  288. // ╚═╝╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═╝ ╚═╝╚═╝ ╚═╝
  289. #ifndef NO_IRON_API
  290. #include <stdio.h>
  291. #include "iron_math.h"
  292. #include "iron_net.h"
  293. #include <lz4x.h>
  294. #include "kong/dir.h"
  295. #ifdef WITH_AUDIO
  296. #include "iron_audio.h"
  297. #endif
  298. #define STB_IMAGE_IMPLEMENTATION
  299. #include <stb_image.h>
  300. #ifdef IRON_DIRECT3D12
  301. #include <d3d12.h>
  302. #endif
  303. #ifdef WITH_D3DCOMPILER
  304. #include <d3d11.h>
  305. #include <D3Dcompiler.h>
  306. #endif
  307. #ifdef WITH_NFD
  308. #include <nfd.h>
  309. #elif defined(IRON_ANDROID)
  310. #include "backends/android_file_dialog.h"
  311. #include "backends/android_http_request.h"
  312. #elif defined(IRON_IOS)
  313. #include <wchar.h>
  314. #include "backends/ios_file_dialog.h"
  315. #endif
  316. #ifdef WITH_IMAGE_WRITE
  317. #ifdef WITH_COMPRESS
  318. unsigned char *iron_deflate_raw(unsigned char *data, int data_len, int *out_len, int quality);
  319. #define STBIW_ZLIB_COMPRESS iron_deflate_raw
  320. #endif
  321. #define STBI_WINDOWS_UTF8
  322. #define STB_IMAGE_WRITE_IMPLEMENTATION
  323. #include <stb_image_write.h>
  324. #endif
  325. #ifdef WITH_VIDEO_WRITE
  326. #include <minih264e.h>
  327. #include <minimp4.h>
  328. #endif
  329. #ifdef WITH_COMPRESS
  330. #define SDEFL_IMPLEMENTATION
  331. #include "sdefl.h"
  332. #define SINFL_IMPLEMENTATION
  333. #include "sinfl.h"
  334. #endif
  335. #if defined(IDLE_SLEEP) && !defined(IRON_WINDOWS)
  336. // #include <unistd.h>
  337. int usleep(unsigned int usec);
  338. #endif
  339. #ifdef IRON_MACOS
  340. const char *iron_get_resource_path();
  341. #endif
  342. #ifdef IRON_IOS
  343. const char *iron_get_resource_path();
  344. #endif
  345. #if defined(IRON_IOS) || defined(IRON_ANDROID)
  346. char mobile_title[1024];
  347. #endif
  348. static gpu_buffer_t rt_constant_buffer;
  349. static gpu_raytrace_pipeline_t rt_pipeline;
  350. static gpu_raytrace_acceleration_structure_t rt_accel;
  351. static bool rt_created = false;
  352. static bool rt_accel_created = false;
  353. const int rt_constant_buffer_size = 24;
  354. static gpu_texture_t *textures_to_destroy[128];
  355. static gpu_buffer_t *buffers_to_destroy[128];
  356. static gpu_pipeline_t *pipelines_to_destroy[32];
  357. static int textures_to_destroy_count = 0;
  358. static int buffers_to_destroy_count = 0;
  359. static int pipelines_to_destroy_count = 0;
  360. void _update(void *data) {
  361. #ifdef IRON_WINDOWS
  362. if (in_background && ++paused_frames > 3) {
  363. Sleep(1);
  364. return;
  365. }
  366. #endif
  367. #ifdef IDLE_SLEEP
  368. if (last_window_width != iron_window_width() || last_window_height != iron_window_height()) {
  369. last_window_width = iron_window_width();
  370. last_window_height = iron_window_height();
  371. paused_frames = 0;
  372. }
  373. #if defined(IRON_IOS) || defined(IRON_ANDROID)
  374. const int start_sleep = 1200;
  375. #else
  376. const int start_sleep = 120;
  377. #endif
  378. if (++paused_frames > start_sleep && !input_down) {
  379. #ifdef IRON_WINDOWS
  380. Sleep(1);
  381. #else
  382. usleep(1000);
  383. #endif
  384. return;
  385. }
  386. if (paused_frames == 30) {
  387. gc_run();
  388. }
  389. #endif
  390. #ifdef WITH_AUDIO
  391. iron_a2_update();
  392. #endif
  393. while (textures_to_destroy_count > 0) {
  394. textures_to_destroy_count--;
  395. gpu_texture_destroy(textures_to_destroy[textures_to_destroy_count]);
  396. free(textures_to_destroy[textures_to_destroy_count]);
  397. }
  398. while (buffers_to_destroy_count > 0) {
  399. buffers_to_destroy_count--;
  400. gpu_buffer_destroy(buffers_to_destroy[buffers_to_destroy_count]);
  401. free(buffers_to_destroy[buffers_to_destroy_count]);
  402. }
  403. while (pipelines_to_destroy_count > 0) {
  404. pipelines_to_destroy_count--;
  405. gpu_pipeline_destroy(pipelines_to_destroy[pipelines_to_destroy_count]);
  406. free(pipelines_to_destroy[pipelines_to_destroy_count]);
  407. }
  408. iron_update();
  409. gpu_present();
  410. }
  411. char *_copy(void *data) {
  412. strcpy(temp_string, ui_copy());
  413. return temp_string;
  414. }
  415. char *_cut(void *data) {
  416. strcpy(temp_string, ui_cut());
  417. return temp_string;
  418. }
  419. void _paste(char *text, void *data) {
  420. ui_paste(text);
  421. }
  422. void _foreground(void *data) {
  423. iron_foreground();
  424. in_background = false;
  425. }
  426. void _resume(void *data) {
  427. iron_resume();
  428. }
  429. void _pause(void *data) {
  430. iron_pause();
  431. }
  432. void _background(void *data) {
  433. iron_background();
  434. in_background = true;
  435. paused_frames = 0;
  436. }
  437. void _shutdown(void *data) {
  438. iron_shutdown();
  439. }
  440. void _key_down(int code, void *data) {
  441. iron_key_down(code);
  442. for (int i = 0; i < ui_instances_count; ++i) {
  443. ui_key_down(ui_instances[i], code);
  444. }
  445. #ifdef IDLE_SLEEP
  446. input_down = true;
  447. paused_frames = 0;
  448. #endif
  449. }
  450. void _key_up(int code, void *data) {
  451. iron_key_up(code);
  452. for (int i = 0; i < ui_instances_count; ++i) {
  453. ui_key_up(ui_instances[i], code);
  454. }
  455. #ifdef IDLE_SLEEP
  456. input_down = false;
  457. paused_frames = 0;
  458. #endif
  459. }
  460. void _key_press(unsigned int character, void *data) {
  461. iron_key_press(character);
  462. for (int i = 0; i < ui_instances_count; ++i) {
  463. ui_key_press(ui_instances[i], character);
  464. }
  465. #ifdef IDLE_SLEEP
  466. paused_frames = 0;
  467. #endif
  468. }
  469. void _mouse_down(int button, int x, int y, void *data) {
  470. iron_mouse_down(button, x, y);
  471. for (int i = 0; i < ui_instances_count; ++i) {
  472. ui_mouse_down(ui_instances[i], button, x, y);
  473. }
  474. #ifdef IDLE_SLEEP
  475. input_down = true;
  476. paused_frames = 0;
  477. #endif
  478. }
  479. void _mouse_up(int button, int x, int y, void *data) {
  480. iron_mouse_up(button, x, y);
  481. for (int i = 0; i < ui_instances_count; ++i) {
  482. ui_mouse_up(ui_instances[i], button, x, y);
  483. }
  484. #ifdef IDLE_SLEEP
  485. input_down = false;
  486. paused_frames = 0;
  487. #endif
  488. }
  489. void _mouse_move(int x, int y, int mx, int my, void *data) {
  490. iron_mouse_move(x, y, mx, my);
  491. for (int i = 0; i < ui_instances_count; ++i) {
  492. ui_mouse_move(ui_instances[i], x, y, mx, my);
  493. }
  494. #ifdef IDLE_SLEEP
  495. paused_frames = 0;
  496. #endif
  497. }
  498. void _mouse_wheel(int delta, void *data) {
  499. iron_mouse_wheel(delta);
  500. for (int i = 0; i < ui_instances_count; ++i) {
  501. ui_mouse_wheel(ui_instances[i], delta);
  502. }
  503. #ifdef IDLE_SLEEP
  504. paused_frames = 0;
  505. #endif
  506. }
  507. void _touch_move(int index, int x, int y) {
  508. iron_touch_move(index, x, y);
  509. #if defined(IRON_ANDROID) || defined(IRON_IOS)
  510. for (int i = 0; i < ui_instances_count; ++i) {
  511. ui_touch_move(ui_instances[i], index, x, y);
  512. }
  513. #endif
  514. #ifdef IDLE_SLEEP
  515. paused_frames = 0;
  516. #endif
  517. }
  518. void _touch_down(int index, int x, int y) {
  519. iron_touch_down(index, x, y);
  520. #if defined(IRON_ANDROID) || defined(IRON_IOS)
  521. for (int i = 0; i < ui_instances_count; ++i) {
  522. ui_touch_down(ui_instances[i], index, x, y);
  523. }
  524. #endif
  525. #ifdef IDLE_SLEEP
  526. input_down = true;
  527. paused_frames = 0;
  528. #endif
  529. }
  530. void _touch_up(int index, int x, int y) {
  531. iron_touch_up(index, x, y);
  532. #if defined(IRON_ANDROID) || defined(IRON_IOS)
  533. for (int i = 0; i < ui_instances_count; ++i) {
  534. ui_touch_up(ui_instances[i], index, x, y);
  535. }
  536. #endif
  537. #ifdef IDLE_SLEEP
  538. input_down = false;
  539. paused_frames = 0;
  540. #endif
  541. }
  542. void _pen_down(int x, int y, float pressure) {
  543. iron_pen_down(x, y, pressure);
  544. for (int i = 0; i < ui_instances_count; ++i) {
  545. ui_pen_down(ui_instances[i], x, y, pressure);
  546. }
  547. #ifdef IDLE_SLEEP
  548. input_down = true;
  549. paused_frames = 0;
  550. #endif
  551. }
  552. void _pen_up(int x, int y, float pressure) {
  553. iron_pen_up(x, y, pressure);
  554. for (int i = 0; i < ui_instances_count; ++i) {
  555. ui_pen_up(ui_instances[i], x, y, pressure);
  556. }
  557. #ifdef IDLE_SLEEP
  558. input_down = false;
  559. paused_frames = 0;
  560. #endif
  561. }
  562. void _pen_move(int x, int y, float pressure) {
  563. iron_pen_move(x, y, pressure);
  564. for (int i = 0; i < ui_instances_count; ++i) {
  565. ui_pen_move(ui_instances[i], x, y, pressure);
  566. }
  567. #ifdef IDLE_SLEEP
  568. paused_frames = 0;
  569. #endif
  570. }
  571. #ifdef WITH_GAMEPAD
  572. void _gamepad_axis(int gamepad, int axis, float value, void *data) {
  573. iron_gamepad_axis(gamepad, axis, value);
  574. #ifdef IDLE_SLEEP
  575. paused_frames = 0;
  576. #endif
  577. }
  578. void _gamepad_button(int gamepad, int button, float value, void *data) {
  579. iron_gamepad_button(gamepad, button, value);
  580. #ifdef IDLE_SLEEP
  581. paused_frames = 0;
  582. #endif
  583. }
  584. #endif
  585. void _drop_files(wchar_t *file_path, void *data) {
  586. // Update mouse position
  587. #ifdef IRON_WINDOWS
  588. POINT p;
  589. GetCursorPos(&p);
  590. ScreenToClient(iron_windows_window_handle(), &p);
  591. _mouse_move(p.x, p.y, 0, 0, NULL);
  592. #endif
  593. char buffer[1024];
  594. #ifdef IRON_WINDOWS
  595. WideCharToMultiByte(CP_UTF8, 0, file_path, wcslen(file_path) + 1, buffer, sizeof(buffer), NULL, NULL);
  596. #else
  597. wcstombs(buffer, file_path, sizeof(buffer));
  598. #endif
  599. iron_drop_files(buffer);
  600. in_background = false;
  601. #ifdef IDLE_SLEEP
  602. paused_frames = 0;
  603. #endif
  604. }
  605. char *uri_decode(const char *src) {
  606. char *res = gc_alloc(1024);
  607. char *dst = res;
  608. char a, b;
  609. while (*src) {
  610. if ((*src == '%') && ((a = src[1]) && (b = src[2])) && (isxdigit(a) && isxdigit(b))) {
  611. if (a >= 'a') {
  612. a -= 'a' - 'A';
  613. }
  614. if (a >= 'A') {
  615. a -= ('A' - 10);
  616. }
  617. else {
  618. a -= '0';
  619. }
  620. if (b >= 'a') {
  621. b -= 'a' - 'A';
  622. }
  623. if (b >= 'A') {
  624. b -= ('A' - 10);
  625. }
  626. else {
  627. b -= '0';
  628. }
  629. *dst++ = 16 * a + b;
  630. src += 3;
  631. }
  632. else if (*src == '+') {
  633. *dst++ = ' ';
  634. src++;
  635. }
  636. else {
  637. *dst++ = *src++;
  638. }
  639. }
  640. *dst++ = '\0';
  641. return res;
  642. }
  643. f32 math_floor(f32 x) { return floorf(x); }
  644. f32 math_cos(f32 x) { return cosf(x); }
  645. f32 math_sin(f32 x) { return sinf(x); }
  646. f32 math_tan(f32 x) { return tanf(x); }
  647. f32 math_sqrt(f32 x) { return sqrtf(x); }
  648. f32 math_abs(f32 x) { return fabsf(x); }
  649. f32 math_random() { return rand() / (float)RAND_MAX; }
  650. f32 math_atan2(f32 y, f32 x) { return atan2f(y, x); }
  651. f32 math_asin(f32 x) { return asinf(x); }
  652. f32 math_pi() { return 3.14159265358979323846; }
  653. f32 math_pow(f32 x, f32 y) { return powf(x, y); }
  654. f32 math_round(f32 x) { return roundf(x); }
  655. f32 math_ceil(f32 x) { return ceilf(x); }
  656. f32 math_min(f32 x, f32 y) { return x < y ? x : y; }
  657. f32 math_max(f32 x, f32 y) { return x > y ? x : y; }
  658. f32 math_log(f32 x) { return logf(x); }
  659. f32 math_log2(f32 x) { return log2f(x); }
  660. f32 math_atan(f32 x) { return atanf(x); }
  661. f32 math_acos(f32 x) { return acosf(x); }
  662. f32 math_exp(f32 x) { return expf(x); }
  663. f32 math_fmod(f32 x, f32 y) { return fmod(x, y); }
  664. #ifdef _WIN32
  665. i32 parse_int(const char *s) { return _strtoi64(s, NULL, 10); }
  666. i32 parse_int_hex(const char *s) { return _strtoi64(s, NULL, 16); }
  667. #else
  668. i32 parse_int(const char *s) { return strtol(s, NULL, 10); }
  669. i32 parse_int_hex(const char *s) { return strtol(s, NULL, 16); }
  670. #endif
  671. f32 parse_float(const char *s) { return strtof(s, NULL); }
  672. i32 color_from_floats(f32 r, f32 g, f32 b, f32 a) {
  673. return ((int)(a * 255) << 24) | ((int)(r * 255) << 16) | ((int)(g * 255) << 8) | (int)(b * 255);
  674. }
  675. u8 color_get_rb(i32 c) {
  676. return (c & 0x00ff0000) >> 16;
  677. }
  678. u8 color_get_gb(i32 c) {
  679. return (c & 0x0000ff00) >> 8;
  680. }
  681. u8 color_get_bb(i32 c) {
  682. return c & 0x000000ff;
  683. }
  684. u8 color_get_ab(i32 c) {
  685. return c & 0x000000ff;
  686. }
  687. i32 color_set_rb(i32 c, u8 i) {
  688. return (color_get_ab(c) << 24) | (i << 16) | (color_get_gb(c) << 8) | color_get_bb(c);
  689. }
  690. i32 color_set_gb(i32 c, u8 i) {
  691. return (color_get_ab(c) << 24) | (color_get_rb(c) << 16) | (i << 8) | color_get_bb(c);
  692. }
  693. i32 color_set_bb(i32 c, u8 i) {
  694. return (color_get_ab(c) << 24) | (color_get_rb(c) << 16) | (color_get_gb(c) << 8) | i;
  695. }
  696. i32 color_set_ab(i32 c, u8 i) {
  697. return (i << 24) | (color_get_rb(c) << 16) | (color_get_gb(c) << 8) | color_get_bb(c);
  698. }
  699. void _iron_init(iron_window_options_t *ops) {
  700. ops->display_index = -1;
  701. ops->visible = enable_window;
  702. ops->color_bits = 32;
  703. iron_init(ops);
  704. iron_random_init((int)(iron_time() * 1000));
  705. iron_set_cut_callback(_cut, NULL);
  706. iron_set_copy_callback(_copy, NULL);
  707. iron_set_paste_callback(_paste, NULL);
  708. #ifdef IRON_WINDOWS
  709. // Maximized window has x < -1, prevent window centering
  710. if (ops->x < -1 && ops->y < -1) {
  711. iron_window_move(ops->x, ops->y);
  712. }
  713. #endif
  714. #ifdef WITH_AUDIO
  715. iron_a1_init();
  716. iron_a2_init();
  717. #endif
  718. #ifdef IRON_ANDROID
  719. android_check_permissions();
  720. #endif
  721. }
  722. void _iron_set_update_callback(void (*callback)(void)) {
  723. iron_update = callback;
  724. iron_set_update_callback(_update, NULL);
  725. }
  726. void _iron_set_drop_files_callback(void (*callback)(char *)) {
  727. iron_drop_files = callback;
  728. iron_set_drop_files_callback(_drop_files, NULL);
  729. }
  730. void iron_set_application_state_callback(void (*on_foreground)(void), void (*on_resume)(void), void (*on_pause)(void), void (*on_background)(void), void (*on_shutdown)(void)) {
  731. iron_set_foreground_callback(on_foreground != NULL ? _foreground : NULL, NULL);
  732. iron_set_resume_callback(on_resume != NULL ? _resume : NULL, NULL);
  733. iron_set_pause_callback(on_pause != NULL ? _pause : NULL, NULL);
  734. iron_set_background_callback(on_background != NULL ? _background : NULL, NULL);
  735. iron_set_shutdown_callback(on_shutdown != NULL ? _shutdown : NULL, NULL);
  736. iron_foreground = on_foreground;
  737. iron_resume = on_resume;
  738. iron_pause = on_pause;
  739. iron_background = on_background;
  740. iron_shutdown = on_shutdown;
  741. }
  742. void iron_set_keyboard_down_callback(void (*callback)(int)) {
  743. iron_key_down = callback;
  744. iron_keyboard_set_key_down_callback(_key_down, NULL);
  745. }
  746. void iron_set_keyboard_up_callback(void (*callback)(int)) {
  747. iron_key_up = callback;
  748. iron_keyboard_set_key_up_callback(_key_up, NULL);
  749. }
  750. void iron_set_keyboard_press_callback(void (*callback)(int)) {
  751. iron_key_press = callback;
  752. iron_keyboard_set_key_press_callback(_key_press, NULL);
  753. }
  754. void iron_set_mouse_down_callback(void (*callback)(int, int, int)) {
  755. iron_mouse_down = callback;
  756. iron_mouse_set_press_callback(_mouse_down, NULL);
  757. }
  758. void iron_set_mouse_up_callback(void (*callback)(int, int, int)) {
  759. iron_mouse_up = callback;
  760. iron_mouse_set_release_callback(_mouse_up, NULL);
  761. }
  762. void iron_set_mouse_move_callback(void (*callback)(int, int, int, int)) {
  763. iron_mouse_move = callback;
  764. iron_mouse_set_move_callback(_mouse_move, NULL);
  765. }
  766. void iron_set_mouse_wheel_callback(void (*callback)(int)) {
  767. iron_mouse_wheel = callback;
  768. iron_mouse_set_scroll_callback(_mouse_wheel, NULL);
  769. }
  770. void iron_set_touch_down_callback(void (*callback)(int, int, int)) {
  771. iron_touch_down = callback;
  772. iron_surface_set_touch_start_callback(_touch_down);
  773. }
  774. void iron_set_touch_up_callback(void (*callback)(int, int, int)) {
  775. iron_touch_up = callback;
  776. iron_surface_set_touch_end_callback(_touch_up);
  777. }
  778. void iron_set_touch_move_callback(void (*callback)(int, int, int)) {
  779. iron_touch_move = callback;
  780. iron_surface_set_move_callback(_touch_move);
  781. }
  782. void iron_set_pen_down_callback(void (*callback)(int, int, float)) {
  783. iron_pen_down = callback;
  784. iron_pen_set_press_callback(_pen_down);
  785. }
  786. void iron_set_pen_up_callback(void (*callback)(int, int, float)) {
  787. iron_pen_up = callback;
  788. iron_pen_set_release_callback(_pen_up);
  789. }
  790. void iron_set_pen_move_callback(void (*callback)(int, int, float)) {
  791. iron_pen_move = callback;
  792. iron_pen_set_move_callback(_pen_move);
  793. }
  794. #ifdef WITH_GAMEPAD
  795. void iron_set_gamepad_axis_callback(void (*callback)(int, int, float)) {
  796. iron_gamepad_axis = callback;
  797. iron_gamepad_set_axis_callback(_gamepad_axis, NULL);
  798. }
  799. void iron_set_gamepad_button_callback(void (*callback)(int, int, float)) {
  800. iron_gamepad_button = callback;
  801. iron_gamepad_set_button_callback(_gamepad_button, NULL);
  802. }
  803. #endif
  804. void gpu_delete_buffer(gpu_buffer_t *buffer) {
  805. buffers_to_destroy[buffers_to_destroy_count] = buffer;
  806. buffers_to_destroy_count++;
  807. }
  808. any gpu_create_index_buffer(i32 count) {
  809. gpu_buffer_t *buffer = (gpu_buffer_t *)malloc(sizeof(gpu_buffer_t));
  810. gpu_index_buffer_init(buffer, count);
  811. return buffer;
  812. }
  813. u32_array_t *gpu_lock_index_buffer(gpu_buffer_t *buffer) {
  814. u32_array_t *ar = (u32_array_t *)malloc(sizeof(u32_array_t));
  815. ar->buffer = gpu_index_buffer_lock(buffer);
  816. ar->length = buffer->count;
  817. return ar;
  818. }
  819. any gpu_create_vertex_buffer(i32 count, gpu_vertex_structure_t *structure) {
  820. gpu_buffer_t *buffer = (gpu_buffer_t *)malloc(sizeof(gpu_buffer_t));
  821. gpu_vertex_buffer_init(buffer, count, structure);
  822. return buffer;
  823. }
  824. buffer_t *gpu_lock_vertex_buffer(gpu_buffer_t *buffer) {
  825. buffer_t *b = (buffer_t *)malloc(sizeof(buffer_t));
  826. b->buffer = gpu_vertex_buffer_lock(buffer);
  827. b->length = buffer->count * buffer->stride;
  828. return b;
  829. }
  830. gpu_shader_t *gpu_create_shader(buffer_t *data, i32 shader_type) {
  831. gpu_shader_t *shader = (gpu_shader_t *)malloc(sizeof(gpu_shader_t));
  832. gpu_shader_init(shader, data->buffer, data->length, (gpu_shader_type_t)shader_type);
  833. return shader;
  834. }
  835. #ifdef WITH_KONG
  836. #include "../../sources/libs/kong/analyzer.h"
  837. #include "../../sources/libs/kong/compiler.h"
  838. #include "../../sources/libs/kong/disasm.h"
  839. #include "../../sources/libs/kong/errors.h"
  840. #include "../../sources/libs/kong/functions.h"
  841. #include "../../sources/libs/kong/globals.h"
  842. #include "../../sources/libs/kong/log.h"
  843. #include "../../sources/libs/kong/names.h"
  844. #include "../../sources/libs/kong/parser.h"
  845. #include "../../sources/libs/kong/tokenizer.h"
  846. #include "../../sources/libs/kong/typer.h"
  847. #include "../../sources/libs/kong/types.h"
  848. #include "../../sources/libs/kong/transformer.h"
  849. #include "../../sources/libs/kong/backends/hlsl.h"
  850. #include "../../sources/libs/kong/backends/metal.h"
  851. #include "../../sources/libs/kong/backends/spirv.h"
  852. #include "../../sources/libs/kong/backends/wgsl.h"
  853. #include "../../sources/libs/kong/libs/stb_ds.h"
  854. extern uint64_t next_variable_id;
  855. extern size_t allocated_globals_size;
  856. extern function_id next_function_index;
  857. extern global_id globals_size;
  858. extern name_id names_index;
  859. extern size_t sets_count;
  860. extern type_id next_type_index;
  861. extern size_t vertex_inputs_size;
  862. extern size_t fragment_inputs_size;
  863. extern size_t vertex_functions_size;
  864. extern size_t fragment_functions_size;
  865. extern struct { char *key; name_id value; } *hash;
  866. extern int expression_index;
  867. extern int statement_index;
  868. uint64_t _next_variable_id;
  869. size_t _allocated_globals_size;
  870. function_id _next_function_index;
  871. global_id _globals_size;
  872. name_id _names_index;
  873. size_t _sets_count;
  874. type_id _next_type_index;
  875. size_t _vertex_inputs_size;
  876. size_t _fragment_inputs_size;
  877. size_t _vertex_functions_size;
  878. size_t _fragment_functions_size;
  879. struct { char *key; name_id value; } *_hash;
  880. int _expression_index;
  881. int _statement_index;
  882. void hlsl_export2(char **vs, char **fs, api_kind d3d, bool debug);
  883. void spirv_export2(char **vs, char **fs, int *vs_size, int *fs_size, bool debug);
  884. static struct { char *key; name_id value; } *_clone_hash(struct { char *key; name_id value; } *hash) {
  885. struct { char *key; name_id value; } *clone = NULL;
  886. sh_new_arena(clone);
  887. ptrdiff_t len = shlen(hash);
  888. for (ptrdiff_t i = 0; i < len; i++) {
  889. shput(clone, hash[i].key, hash[i].value);
  890. }
  891. return clone;
  892. }
  893. void gpu_create_shaders_from_kong(char *kong, char **vs, char **fs, int *vs_size, int *fs_size) {
  894. static bool first = true;
  895. if (first) {
  896. first = false;
  897. names_init();
  898. types_init();
  899. functions_init();
  900. globals_init();
  901. _next_variable_id = next_variable_id;
  902. _allocated_globals_size = allocated_globals_size;
  903. _next_function_index = next_function_index;
  904. _globals_size = globals_size;
  905. _names_index = names_index;
  906. _sets_count = sets_count;
  907. _next_type_index = next_type_index;
  908. _vertex_inputs_size = vertex_inputs_size;
  909. _fragment_inputs_size = fragment_inputs_size;
  910. _vertex_functions_size = vertex_functions_size;
  911. _fragment_functions_size = fragment_functions_size;
  912. _hash = _clone_hash(hash);
  913. _expression_index = expression_index;
  914. _statement_index = statement_index;
  915. }
  916. else {
  917. next_variable_id = _next_variable_id;
  918. allocated_globals_size = _allocated_globals_size;
  919. next_function_index = _next_function_index;
  920. globals_size = _globals_size;
  921. names_index = _names_index;
  922. sets_count = _sets_count;
  923. next_type_index = _next_type_index;
  924. vertex_inputs_size = _vertex_inputs_size;
  925. fragment_inputs_size = _fragment_inputs_size;
  926. vertex_functions_size = _vertex_functions_size;
  927. fragment_functions_size = _fragment_functions_size;
  928. shfree(hash);
  929. hash = _clone_hash(_hash);
  930. expression_index = _expression_index;
  931. statement_index = _statement_index;
  932. }
  933. char *from = "";
  934. tokens tokens = tokenize(from, kong);
  935. parse(from, &tokens);
  936. resolve_types();
  937. allocate_globals();
  938. for (function_id i = 0; get_function(i) != NULL; ++i) {
  939. compile_function_block(&get_function(i)->code, get_function(i)->block);
  940. }
  941. analyze();
  942. #ifdef _WIN32
  943. hlsl_export2(vs, fs, API_DIRECT3D11, false);
  944. #elif defined(__APPLE__)
  945. static char vs_temp[1024 * 128];
  946. strcpy(vs_temp, "//>kong_vert\n");
  947. char *metal = metal_export("");
  948. strcat(vs_temp, metal);
  949. *vs = &vs_temp[0];
  950. *fs = "//>kong_frag\n";
  951. free(metal);
  952. #else
  953. transform(TRANSFORM_FLAG_ONE_COMPONENT_SWIZZLE | TRANSFORM_FLAG_BINARY_UNIFY_LENGTH);
  954. spirv_export2(vs, fs, vs_size, fs_size, false);
  955. #endif
  956. free(tokens.t);
  957. }
  958. #endif
  959. gpu_shader_t *gpu_create_shader_from_source(string_t *source, int source_size, gpu_shader_type_t shader_type) {
  960. gpu_shader_t *shader = (gpu_shader_t *)malloc(sizeof(gpu_shader_t));
  961. char *temp_string_s = shader_type == GPU_SHADER_TYPE_VERTEX ? temp_string_vs : temp_string_fs;
  962. #ifdef WITH_D3DCOMPILER
  963. strcpy(temp_string_s, source);
  964. ID3DBlob *error_message;
  965. ID3DBlob *shader_buffer;
  966. UINT flags = D3DCOMPILE_SKIP_OPTIMIZATION | D3DCOMPILE_SKIP_VALIDATION;
  967. HRESULT hr = D3DCompile(temp_string_s, strlen(source) + 1, NULL, NULL, NULL, "main",
  968. shader_type == GPU_SHADER_TYPE_VERTEX ? "vs_5_0" : "ps_5_0", flags, 0, &shader_buffer, &error_message);
  969. if (hr != S_OK) {
  970. iron_log("%s", (char *)error_message->lpVtbl->GetBufferPointer(error_message));
  971. return NULL;
  972. }
  973. int size = shader_buffer->lpVtbl->GetBufferSize(shader_buffer);
  974. gpu_shader_init(shader, (char *)shader_buffer->lpVtbl->GetBufferPointer(shader_buffer), size, shader_type);
  975. shader_buffer->lpVtbl->Release(shader_buffer);
  976. #elif defined(IRON_METAL)
  977. strcpy(temp_string_s, source);
  978. gpu_shader_init(shader, temp_string_s, strlen(temp_string_s), shader_type);
  979. #elif defined(IRON_VULKAN)
  980. gpu_shader_init(shader, source, source_size, shader_type);
  981. #endif
  982. return shader;
  983. }
  984. gpu_pipeline_t *gpu_create_pipeline() {
  985. gpu_pipeline_t *pipeline = (gpu_pipeline_t *)malloc(sizeof(gpu_pipeline_t));
  986. gpu_pipeline_init(pipeline);
  987. return pipeline;
  988. }
  989. void gpu_delete_pipeline(gpu_pipeline_t *pipeline) {
  990. pipelines_to_destroy[pipelines_to_destroy_count] = pipeline;
  991. pipelines_to_destroy_count++;
  992. }
  993. gpu_texture_t *gpu_create_render_target(i32 width, i32 height, i32 format) {
  994. gpu_texture_t *render_target = (gpu_texture_t *)malloc(sizeof(gpu_texture_t));
  995. gpu_render_target_init(render_target, width, height, (gpu_texture_format_t)format);
  996. render_target->buffer = NULL;
  997. return render_target;
  998. }
  999. gpu_texture_t *gpu_create_texture_from_bytes(buffer_t *data, i32 width, i32 height, i32 format) {
  1000. gpu_texture_t *texture = (gpu_texture_t *)malloc(sizeof(gpu_texture_t));
  1001. texture->buffer = NULL;
  1002. gpu_texture_init_from_bytes(texture, data->buffer, width, height, (gpu_texture_format_t)format);
  1003. return texture;
  1004. }
  1005. gpu_texture_t *gpu_create_texture_from_encoded_bytes(buffer_t *data, string_t *format) {
  1006. gpu_texture_t *texture = (gpu_texture_t *)malloc(sizeof(gpu_texture_t));
  1007. texture->buffer = NULL;
  1008. unsigned char *texture_data;
  1009. gpu_texture_format_t texture_format;
  1010. int width;
  1011. int height;
  1012. if (ends_with(format, "k")) {
  1013. width = iron_read_s32le(data->buffer);
  1014. height = iron_read_s32le(data->buffer + 4);
  1015. char fourcc[5];
  1016. fourcc[0] = data->buffer[8];
  1017. fourcc[1] = data->buffer[9];
  1018. fourcc[2] = data->buffer[10];
  1019. fourcc[3] = data->buffer[11];
  1020. fourcc[4] = 0;
  1021. int compressed_size = data->length - 12;
  1022. if (strcmp(fourcc, "LZ4 ") == 0) {
  1023. int output_size = width * height * 4;
  1024. texture_data = (unsigned char *)malloc(output_size);
  1025. LZ4_decompress_safe((char *)data->buffer + 12, (char *)texture_data, compressed_size, output_size);
  1026. texture_format = GPU_TEXTURE_FORMAT_RGBA32;
  1027. }
  1028. else if (strcmp(fourcc, "LZ4F") == 0) {
  1029. int output_size = width * height * 16;
  1030. texture_data = (unsigned char *)malloc(output_size);
  1031. LZ4_decompress_safe((char *)data->buffer + 12, (char *)texture_data, compressed_size, output_size);
  1032. texture_format = GPU_TEXTURE_FORMAT_RGBA128;
  1033. }
  1034. }
  1035. else if (ends_with(format, "hdr")) {
  1036. int comp;
  1037. texture_data = (unsigned char *)stbi_loadf_from_memory(data->buffer, data->length, &width, &height, &comp, 4);
  1038. texture_format = GPU_TEXTURE_FORMAT_RGBA128;
  1039. }
  1040. else { // jpg, png, ..
  1041. int comp;
  1042. texture_data = stbi_load_from_memory(data->buffer, data->length, &width, &height, &comp, 4);
  1043. texture_format = GPU_TEXTURE_FORMAT_RGBA32;
  1044. }
  1045. gpu_texture_init_from_bytes(texture, texture_data, width, height, texture_format);
  1046. free(texture_data);
  1047. return texture;
  1048. }
  1049. gpu_texture_t *iron_load_texture(string_t *file) {
  1050. #ifdef WITH_EMBED
  1051. buffer_t *b = embed_get(file);
  1052. if (b != NULL) {
  1053. return gpu_create_texture_from_encoded_bytes(b, ".k");
  1054. }
  1055. #endif
  1056. iron_file_reader_t reader;
  1057. if (!iron_file_reader_open(&reader, file, IRON_FILE_TYPE_ASSET)) {
  1058. return NULL;
  1059. }
  1060. int size = (int)iron_file_reader_size(&reader);
  1061. unsigned char *data = (unsigned char *)malloc(size);
  1062. iron_file_reader_read(&reader, data, size);
  1063. iron_file_reader_close(&reader);
  1064. buffer_t buf;
  1065. buf.buffer = data;
  1066. buf.length = size;
  1067. return gpu_create_texture_from_encoded_bytes(&buf, file);
  1068. }
  1069. void iron_delete_texture(gpu_texture_t *texture) {
  1070. textures_to_destroy[textures_to_destroy_count] = texture;
  1071. textures_to_destroy_count++;
  1072. }
  1073. #ifdef WITH_AUDIO
  1074. any iron_load_sound(string_t *file) {
  1075. iron_a1_sound_t *sound = iron_a1_sound_create(file);
  1076. return sound;
  1077. }
  1078. #endif
  1079. buffer_t *iron_load_blob(string_t *file) {
  1080. #ifdef WITH_EMBED
  1081. buffer_t *b = embed_get(file);
  1082. if (b != NULL) {
  1083. return b;
  1084. }
  1085. #endif
  1086. iron_file_reader_t reader;
  1087. if (!iron_file_reader_open(&reader, file, IRON_FILE_TYPE_ASSET)) {
  1088. return NULL;
  1089. }
  1090. uint32_t reader_size = (uint32_t)iron_file_reader_size(&reader);
  1091. buffer_t *buffer = buffer_create(reader_size);
  1092. iron_file_reader_read(&reader, buffer->buffer, reader_size);
  1093. iron_file_reader_close(&reader);
  1094. return buffer;
  1095. }
  1096. void iron_set_window_title(string_t *title) {
  1097. iron_window_set_title(title);
  1098. #if defined(IRON_IOS) || defined(IRON_ANDROID)
  1099. strcpy(mobile_title, title);
  1100. #endif
  1101. }
  1102. void iron_set_window_mode(i32 mode) {
  1103. iron_window_change_mode((iron_window_mode_t)mode);
  1104. }
  1105. i32 iron_screen_dpi() {
  1106. return iron_display_current_mode(iron_primary_display()).pixels_per_inch;
  1107. }
  1108. i32 iron_display_width(i32 index) {
  1109. return iron_display_current_mode(index).width;
  1110. }
  1111. i32 iron_display_height(i32 index) {
  1112. return iron_display_current_mode(index).height;
  1113. }
  1114. i32 iron_display_x(i32 index) {
  1115. return iron_display_current_mode(index).x;
  1116. }
  1117. i32 iron_display_y(i32 index) {
  1118. return iron_display_current_mode(index).y;
  1119. }
  1120. i32 iron_display_frequency(i32 index) {
  1121. return iron_display_current_mode(index).frequency;
  1122. }
  1123. bool iron_display_is_primary(i32 index) {
  1124. return index == iron_primary_display();
  1125. }
  1126. buffer_t *gpu_get_texture_pixels(gpu_texture_t *image) {
  1127. if (image->buffer == NULL) {
  1128. image->buffer = malloc(sizeof(buffer_t));
  1129. image->buffer->buffer = NULL;
  1130. }
  1131. image->buffer->length = gpu_texture_format_size(image->format) * image->width * image->height;
  1132. if (image->buffer->buffer == NULL) {
  1133. image->buffer->buffer = malloc(image->buffer->length);
  1134. }
  1135. uint8_t *b = (uint8_t *)image->buffer->buffer;
  1136. gpu_get_render_target_pixels(image, b);
  1137. return image->buffer;
  1138. }
  1139. void _gpu_begin(gpu_texture_t *render_target, any_array_t *additional, gpu_texture_t *depth_buffer, unsigned flags, unsigned color, float depth) {
  1140. if (render_target == NULL) {
  1141. gpu_begin(NULL, 0, NULL, flags, color, depth);
  1142. }
  1143. else {
  1144. int32_t length = 1;
  1145. gpu_texture_t *render_targets[8] = { render_target, NULL, NULL, NULL, NULL, NULL, NULL, NULL };
  1146. if (additional != NULL) {
  1147. length = additional->length + 1;
  1148. for (int32_t i = 1; i < length; ++i) {
  1149. render_targets[i] = additional->buffer[i - 1];
  1150. }
  1151. }
  1152. gpu_begin(render_targets, length, depth_buffer, flags, color, depth);
  1153. }
  1154. }
  1155. void iron_file_save_bytes(string_t *path, buffer_t *bytes, u64 length) {
  1156. u64 byte_length = length > 0 ? length : (u64)bytes->length;
  1157. if (byte_length > (u64)bytes->length) {
  1158. byte_length = (u64)bytes->length;
  1159. }
  1160. #ifdef IRON_WINDOWS
  1161. MultiByteToWideChar(CP_UTF8, 0, path, -1, temp_wstring, 1024);
  1162. FILE *file = _wfopen(temp_wstring, L"wb");
  1163. #else
  1164. FILE *file = fopen(path, "wb");
  1165. #endif
  1166. if (file == NULL) {
  1167. return;
  1168. }
  1169. fwrite(bytes->buffer, 1, byte_length, file);
  1170. fclose(file);
  1171. }
  1172. i32 iron_sys_command(string_t *cmd) {
  1173. #ifdef IRON_WINDOWS
  1174. int wlen = MultiByteToWideChar(CP_UTF8, 0, cmd, -1, NULL, 0);
  1175. wchar_t *wstr = malloc(sizeof(wchar_t) * wlen);
  1176. MultiByteToWideChar(CP_UTF8, 0, cmd, -1, wstr, wlen);
  1177. int result = _wsystem(wstr);
  1178. free(wstr);
  1179. #elif defined(IRON_IOS)
  1180. int result = 0;
  1181. #else
  1182. int result = system(cmd);
  1183. #endif
  1184. return result;
  1185. }
  1186. string_t *iron_get_files_location() {
  1187. #ifdef IRON_MACOS
  1188. char path[1024];
  1189. strcpy(path, iron_get_resource_path());
  1190. strcat(path, "/");
  1191. strcat(path, IRON_OUTDIR);
  1192. strcat(path, "/");
  1193. return path;
  1194. #elif defined(IRON_IOS)
  1195. char path[1024];
  1196. strcpy(path, iron_get_resource_path());
  1197. strcat(path, "/");
  1198. strcat(path, IRON_OUTDIR);
  1199. strcat(path, "/");
  1200. return path;
  1201. #else
  1202. return iron_internal_get_files_location();
  1203. #endif
  1204. }
  1205. typedef struct _callback_data {
  1206. int32_t size;
  1207. char url[512];
  1208. void (*func)(char *, buffer_t *);
  1209. } _callback_data_t;
  1210. void _http_callback(int error, int response, const char *body, void *callback_data) {
  1211. _callback_data_t *cbd = (_callback_data_t *)callback_data;
  1212. buffer_t *buffer = NULL;
  1213. if (body != NULL) {
  1214. buffer = malloc(sizeof(buffer_t));
  1215. buffer->length = cbd->size > 0 ? cbd->size : strlen(body);
  1216. buffer->buffer = body;
  1217. }
  1218. cbd->func(cbd->url, buffer);
  1219. free(cbd);
  1220. }
  1221. void _iron_http_request(string_t *url, i32 size, void (*callback)(char *, buffer_t *)) {
  1222. _callback_data_t *cbd = malloc(sizeof(_callback_data_t));
  1223. cbd->size = size;
  1224. strcpy(cbd->url, url);
  1225. cbd->func = callback;
  1226. char url_base[512];
  1227. char url_path[512];
  1228. const char *curl = url;
  1229. int i = 0;
  1230. for (; i < strlen(curl) - 8; ++i) {
  1231. if (curl[i + 8] == '/') {
  1232. break;
  1233. }
  1234. url_base[i] = curl[i + 8]; // Strip https://
  1235. }
  1236. url_base[i] = 0;
  1237. int j = 0;
  1238. if (strlen(url_base) < strlen(curl) - 8) {
  1239. ++i; // Skip /
  1240. }
  1241. for (; j < strlen(curl) - 8 - i; ++j) {
  1242. if (curl[i + 8 + j] == 0) {
  1243. break;
  1244. }
  1245. url_path[j] = curl[i + 8 + j];
  1246. }
  1247. url_path[j] = 0;
  1248. #ifdef IRON_ANDROID // TODO: move to iron
  1249. android_http_request(curl, url_path, NULL, 443, true, 0, NULL, &_http_callback, cbd);
  1250. #elif defined(IRON_LINUX)
  1251. // TODO
  1252. #else
  1253. iron_http_request(url_base, url_path, NULL, 443, true, 0, NULL, &_http_callback, cbd);
  1254. #endif
  1255. }
  1256. bool _window_close_callback(void *data) {
  1257. #ifdef IRON_WINDOWS
  1258. bool save = false;
  1259. wchar_t title[1024];
  1260. GetWindowTextW(iron_windows_window_handle(), title, sizeof(title));
  1261. bool dirty = wcsstr(title, L"* - ArmorPaint") != NULL;
  1262. if (dirty) {
  1263. int res = MessageBox(iron_windows_window_handle(), L"Project has been modified, save changes?", L"Save Changes?", MB_YESNOCANCEL | MB_ICONEXCLAMATION);
  1264. if (res == IDYES) {
  1265. save = true;
  1266. }
  1267. else if (res == IDNO) {
  1268. save = false;
  1269. }
  1270. else { // Cancel
  1271. return false;
  1272. }
  1273. }
  1274. if (save_and_quit_callback_set) {
  1275. iron_save_and_quit(save);
  1276. return false;
  1277. }
  1278. #endif
  1279. return true;
  1280. }
  1281. void iron_set_save_and_quit_callback(void (*callback)(bool)) {
  1282. iron_save_and_quit = callback;
  1283. save_and_quit_callback_set = true;
  1284. iron_window_set_close_callback(_window_close_callback, NULL);
  1285. }
  1286. void iron_set_mouse_cursor(i32 id) {
  1287. iron_mouse_set_cursor(id);
  1288. #ifdef IRON_WINDOWS
  1289. // Set hand icon for drag even when mouse button is pressed
  1290. if (id == 1) {
  1291. SetCursor(LoadCursor(NULL, IDC_HAND));
  1292. }
  1293. #endif
  1294. }
  1295. void iron_delay_idle_sleep() {
  1296. paused_frames = 0;
  1297. }
  1298. #ifdef WITH_NFD
  1299. char_ptr_array_t *iron_open_dialog(char *filter_list, char *default_path, bool open_multiple) {
  1300. nfdpathset_t out_paths;
  1301. nfdchar_t* out_path;
  1302. nfdresult_t result = open_multiple ? NFD_OpenDialogMultiple(filter_list, default_path, &out_paths) : NFD_OpenDialog(filter_list, default_path, &out_path);
  1303. if (result == NFD_OKAY) {
  1304. int path_count = open_multiple ? (int)NFD_PathSet_GetCount(&out_paths) : 1;
  1305. char_ptr_array_t *result = any_array_create(path_count);
  1306. if (open_multiple) {
  1307. for (int i = 0; i < path_count; ++i) {
  1308. nfdchar_t* out_path = NFD_PathSet_GetPath(&out_paths, i);
  1309. result->buffer[i] = out_path;
  1310. }
  1311. // NFD_PathSet_Free(&out_paths);
  1312. }
  1313. else {
  1314. result->buffer[0] = out_path;
  1315. // free(out_path);
  1316. }
  1317. return result;
  1318. }
  1319. return NULL;
  1320. }
  1321. static char iron_save_dialog_path[512];
  1322. char *iron_save_dialog(char *filter_list, char *default_path) {
  1323. nfdchar_t *out_path = NULL;
  1324. nfdresult_t result = NFD_SaveDialog(filter_list, default_path, &out_path);
  1325. if (result == NFD_OKAY) {
  1326. strcpy(iron_save_dialog_path, out_path);
  1327. free(out_path);
  1328. return iron_save_dialog_path;
  1329. }
  1330. return NULL;
  1331. }
  1332. #elif defined(IRON_ANDROID)
  1333. char_ptr_array_t *iron_open_dialog(char *filter_list, char *default_path, bool open_multiple) {
  1334. AndroidFileDialogOpen();
  1335. return NULL;
  1336. }
  1337. char *iron_save_dialog(char *filter_list, char *default_path) {
  1338. wchar_t *out_path = AndroidFileDialogSave();
  1339. wcstombs(temp_string, out_path, sizeof(temp_string));
  1340. return temp_string;
  1341. }
  1342. #elif defined(IRON_IOS)
  1343. char_ptr_array_t *iron_open_dialog(char *filter_list, char *default_path, bool open_multiple) {
  1344. // Once finished drop_files callback is called
  1345. IOSFileDialogOpen();
  1346. return NULL;
  1347. }
  1348. char *iron_save_dialog(char *filter_list, char *default_path) {
  1349. // Path to app document directory
  1350. wchar_t *out_path = IOSFileDialogSave();
  1351. wcstombs(temp_string, out_path, sizeof(temp_string));
  1352. return temp_string;
  1353. }
  1354. #endif
  1355. char *iron_read_directory(char *path) {
  1356. char *files = temp_string;
  1357. files[0] = 0;
  1358. directory dir = open_dir(path);
  1359. if (dir.handle == NULL) {
  1360. return files;
  1361. }
  1362. while (true) {
  1363. file f = read_next_file(&dir);
  1364. if (!f.valid) {
  1365. break;
  1366. }
  1367. #ifdef IRON_WINDOWS
  1368. char file_path[512];
  1369. strcpy(file_path, path);
  1370. strcat(file_path, "\\");
  1371. strcat(file_path, f.name);
  1372. if (FILE_ATTRIBUTE_HIDDEN & GetFileAttributesA(file_path)) {
  1373. continue; // Skip hidden files
  1374. }
  1375. #endif
  1376. if (files[0] != '\0') {
  1377. strcat(files, "\n");
  1378. }
  1379. strcat(files, f.name);
  1380. }
  1381. close_dir(&dir);
  1382. return files;
  1383. }
  1384. bool iron_file_exists(char *path) {
  1385. iron_file_reader_t reader;
  1386. if (iron_file_reader_open(&reader, path, IRON_FILE_TYPE_ASSET)) {
  1387. iron_file_reader_close(&reader);
  1388. return true;
  1389. }
  1390. return false;
  1391. }
  1392. void iron_delete_file(char *path) {
  1393. #ifdef IRON_IOS
  1394. IOSDeleteFile(path);
  1395. #elif defined(IRON_WINDOWS)
  1396. char cmd[1024];
  1397. strcpy(cmd, "del /f \"");
  1398. strcat(cmd, path);
  1399. strcat(cmd, "\"");
  1400. iron_sys_command(cmd);
  1401. #else
  1402. char cmd[1024];
  1403. strcpy(cmd, "rm \"");
  1404. strcat(cmd, path);
  1405. strcat(cmd, "\"");
  1406. iron_sys_command(cmd);
  1407. #endif
  1408. }
  1409. #ifdef WITH_COMPRESS
  1410. buffer_t *iron_inflate(buffer_t *bytes, bool raw) {
  1411. unsigned char *inflated;
  1412. int inflated_len = bytes->length * 2;
  1413. int out_len = -1;
  1414. while (out_len == -1) {
  1415. inflated_len *= 2;
  1416. inflated = (unsigned char *)realloc(inflated, inflated_len);
  1417. out_len = sinflate(inflated, inflated_len, bytes->buffer, bytes->length);
  1418. }
  1419. buffer_t *output = buffer_create(0);
  1420. output->buffer = inflated;
  1421. output->length = out_len;
  1422. return output;
  1423. }
  1424. buffer_t *iron_deflate(buffer_t *bytes, bool raw) {
  1425. struct sdefl sdefl;
  1426. memset(&sdefl, 0, sizeof(sdefl));
  1427. void *deflated = malloc(sdefl_bound(bytes->length));
  1428. // raw == sdeflate
  1429. int out_len = zsdeflate(&sdefl, deflated, bytes->buffer, bytes->length, SDEFL_LVL_MIN);
  1430. buffer_t *output = buffer_create(0);
  1431. output->buffer = deflated;
  1432. output->length = out_len;
  1433. return output;
  1434. }
  1435. unsigned char *iron_deflate_raw(unsigned char *data, int data_len, int *out_len, int quality) {
  1436. struct sdefl sdefl;
  1437. memset(&sdefl, 0, sizeof(sdefl));
  1438. void *deflated = malloc(sdefl_bound(data_len));
  1439. *out_len = zsdeflate(&sdefl, deflated, data, data_len, SDEFL_LVL_MIN);
  1440. return (unsigned char *)deflated;
  1441. }
  1442. #endif
  1443. #ifdef WITH_IMAGE_WRITE
  1444. void _write_image(char *path, buffer_t *bytes, i32 w, i32 h, i32 format, int image_format, int quality) {
  1445. int comp = 0;
  1446. unsigned char *pixels = NULL;
  1447. unsigned char *rgba = (unsigned char *)bytes->buffer;
  1448. if (format == 0) { // RGBA
  1449. comp = 4;
  1450. pixels = rgba;
  1451. }
  1452. else if (format == 1) { // R
  1453. comp = 1;
  1454. pixels = rgba;
  1455. }
  1456. else if (format == 2) { // RGB1
  1457. comp = 3;
  1458. pixels = (unsigned char *)malloc(w * h * comp);
  1459. for (int i = 0; i < w * h; ++i) {
  1460. #if defined(IRON_METAL) || defined(IRON_VULKAN)
  1461. pixels[i * 3 ] = rgba[i * 4 + 2];
  1462. pixels[i * 3 + 1] = rgba[i * 4 + 1];
  1463. pixels[i * 3 + 2] = rgba[i * 4 ];
  1464. #else
  1465. pixels[i * 3 ] = rgba[i * 4 ];
  1466. pixels[i * 3 + 1] = rgba[i * 4 + 1];
  1467. pixels[i * 3 + 2] = rgba[i * 4 + 2];
  1468. #endif
  1469. }
  1470. }
  1471. else if (format > 2) { // RRR1, GGG1, BBB1, AAA1
  1472. comp = 1;
  1473. pixels = (unsigned char *)malloc(w * h * comp);
  1474. int off = format - 3;
  1475. #if defined(IRON_METAL) || defined(IRON_VULKAN)
  1476. off = 2 - off;
  1477. #endif
  1478. for (int i = 0; i < w * h; ++i) {
  1479. pixels[i] = rgba[i * 4 + off];
  1480. }
  1481. }
  1482. image_format == 0 ?
  1483. stbi_write_jpg(path, w, h, comp, pixels, quality) :
  1484. stbi_write_png(path, w, h, comp, pixels, w * comp);
  1485. if (pixels != rgba) {
  1486. free(pixels);
  1487. }
  1488. }
  1489. void iron_write_jpg(char *path, buffer_t *bytes, i32 w, i32 h, i32 format, i32 quality) {
  1490. // RGBA, R, RGB1, RRR1, GGG1, BBB1, AAA1
  1491. _write_image(path, bytes, w, h, format, 0, quality);
  1492. }
  1493. void iron_write_png(char *path, buffer_t *bytes, i32 w, i32 h, i32 format) {
  1494. _write_image(path, bytes, w, h, format, 1, 100);
  1495. }
  1496. unsigned char *_encode_data;
  1497. int _encode_size;
  1498. void _encode_image_func(void *context, void *data, int size) {
  1499. memcpy(_encode_data + _encode_size, data, size);
  1500. _encode_size += size;
  1501. }
  1502. buffer_t *_encode_image(buffer_t *bytes, i32 w, i32 h, i32 format, i32 quality) {
  1503. _encode_data = (unsigned char *)malloc(w * h * 4);
  1504. _encode_size = 0;
  1505. format == 0 ?
  1506. stbi_write_jpg_to_func(&_encode_image_func, NULL, w, h, 4, bytes->buffer, quality) :
  1507. stbi_write_png_to_func(&_encode_image_func, NULL, w, h, 4, bytes->buffer, w * 4);
  1508. buffer_t *buffer = malloc(sizeof(buffer_t));
  1509. buffer->buffer = _encode_data;
  1510. buffer->length = _encode_size;
  1511. return buffer;
  1512. }
  1513. buffer_t *iron_encode_jpg(buffer_t *bytes, i32 w, i32 h, i32 format, i32 quality) {
  1514. return _encode_image(bytes, w, h, 0, quality);
  1515. }
  1516. buffer_t *iron_encode_png(buffer_t *bytes, i32 w, i32 h, i32 format) {
  1517. return _encode_image(bytes, w, h, 1, 100);
  1518. }
  1519. #endif
  1520. #ifdef WITH_VIDEO_WRITE
  1521. static FILE *iron_mp4_fp;
  1522. static int iron_mp4_w;
  1523. static int iron_mp4_h;
  1524. static int iron_mp4_stride;
  1525. static H264E_persist_t *iron_mp4_enc = NULL;
  1526. static H264E_scratch_t *iron_mp4_scratch = NULL;
  1527. static char iron_mp4_path[512];
  1528. static char iron_mp4_path_264[512];
  1529. static char *iron_mp4_yuv_buf;
  1530. static size_t iron_mp4_get_nal_size(uint8_t *buf, size_t size) {
  1531. size_t pos = 3;
  1532. while ((size - pos) > 3) {
  1533. if (buf[pos] == 0 && buf[pos + 1] == 0 && buf[pos + 2] == 1) {
  1534. return pos;
  1535. }
  1536. if (buf[pos] == 0 && buf[pos + 1] == 0 && buf[pos + 2] == 0 && buf[pos + 3] == 1) {
  1537. return pos;
  1538. }
  1539. pos++;
  1540. }
  1541. return size;
  1542. }
  1543. static int iron_mp4_write_callback(int64_t offset, const void *buffer, size_t size, void *token) {
  1544. FILE *f = (FILE *)token;
  1545. fseek(f, offset, SEEK_SET);
  1546. return fwrite(buffer, 1, size, f) != size;
  1547. }
  1548. void iron_mp4_begin(char *path, i32 w, i32 h) {
  1549. strcpy(iron_mp4_path, path);
  1550. strcpy(iron_mp4_path_264, path);
  1551. int len = strlen(iron_mp4_path_264);
  1552. iron_mp4_path_264[len - 1] = '4';
  1553. iron_mp4_path_264[len - 2] = '6';
  1554. iron_mp4_path_264[len - 3] = '2';
  1555. iron_mp4_stride = w;
  1556. iron_mp4_w = w - w % 16;
  1557. iron_mp4_h = h - h % 16;
  1558. H264E_create_param_t create_param = {0};
  1559. create_param.width = iron_mp4_w;
  1560. create_param.height = iron_mp4_h;
  1561. int sizeof_persist = 0;
  1562. int sizeof_scratch = 0;
  1563. H264E_sizeof(&create_param, &sizeof_persist, &sizeof_scratch);
  1564. iron_mp4_enc = (H264E_persist_t *)malloc(sizeof_persist);
  1565. iron_mp4_scratch = (H264E_scratch_t *)malloc(sizeof_scratch);
  1566. H264E_init(iron_mp4_enc, &create_param);
  1567. iron_mp4_fp = fopen(iron_mp4_path_264, "wb");
  1568. int frame_size = (int)(iron_mp4_w * iron_mp4_h * 1.5);
  1569. iron_mp4_yuv_buf = malloc(frame_size);
  1570. }
  1571. void iron_mp4_end() {
  1572. if (iron_mp4_fp == NULL) {
  1573. return;
  1574. }
  1575. buffer_t *blob = iron_load_blob(iron_mp4_path_264);
  1576. uint8_t *buf = blob->buffer;
  1577. size_t buf_size = blob->length;
  1578. FILE *fout = fopen(iron_mp4_path, "wb");
  1579. MP4E_mux_t *mux = MP4E_open(0, 0, fout, iron_mp4_write_callback);
  1580. mp4_h26x_writer_t mp4wr;
  1581. mp4_h26x_write_init(&mp4wr, mux, iron_mp4_w, iron_mp4_h, false);
  1582. while (buf_size > 0) {
  1583. size_t nal_size = iron_mp4_get_nal_size(buf, buf_size);
  1584. if (nal_size < 4) {
  1585. buf += 1;
  1586. buf_size -= 1;
  1587. continue;
  1588. }
  1589. int fps = 24;
  1590. mp4_h26x_write_nal(&mp4wr, buf, nal_size, 90000 / fps);
  1591. buf += nal_size;
  1592. buf_size -= nal_size;
  1593. }
  1594. MP4E_close(mux);
  1595. mp4_h26x_write_close(&mp4wr);
  1596. free(iron_mp4_enc);
  1597. free(iron_mp4_scratch);
  1598. free(iron_mp4_yuv_buf);
  1599. fclose(fout);
  1600. fclose(iron_mp4_fp);
  1601. iron_mp4_fp = NULL;
  1602. }
  1603. void iron_mp4_encode(buffer_t *pixels) {
  1604. // rgba to yuv420p
  1605. for (int i = 0; i < iron_mp4_w; ++i) {
  1606. for (int j = 0; j < iron_mp4_h; ++j) {
  1607. int k = i + j * iron_mp4_stride;
  1608. uint8_t r = pixels->buffer[k * 4];
  1609. uint8_t g = pixels->buffer[k * 4 + 1];
  1610. uint8_t b = pixels->buffer[k * 4 + 2];
  1611. uint8_t y = (( 66 * r + 129 * g + 25 * b + 128) / 256) + 16;
  1612. uint8_t u = ((-38 * r - 74 * g + 112 * b + 128) / 256) + 128;
  1613. uint8_t v = ((112 * r - 94 * g - 18 * b + 128) / 256) + 128;
  1614. int l = i + j * iron_mp4_w;
  1615. int m = i / 2 + j / 2 * (iron_mp4_w / 2);
  1616. iron_mp4_yuv_buf[l] = y;
  1617. iron_mp4_yuv_buf[iron_mp4_w * iron_mp4_h + m] = u;
  1618. iron_mp4_yuv_buf[iron_mp4_w * iron_mp4_h + (iron_mp4_w * iron_mp4_h) / 4 + m] = v;
  1619. }
  1620. }
  1621. H264E_run_param_t run_param = {0};
  1622. run_param.frame_type = 0;
  1623. run_param.encode_speed = H264E_SPEED_SLOWEST; // H264E_SPEED_FASTEST;
  1624. run_param.desired_frame_bytes = (2048 * 4) * 1000 / 8 / 30; // 2048 * 4 kbps
  1625. run_param.qp_min = 10;
  1626. run_param.qp_max = 50;
  1627. H264E_io_yuv_t yuv;
  1628. yuv.yuv[0] = iron_mp4_yuv_buf;
  1629. yuv.stride[0] = iron_mp4_w;
  1630. yuv.yuv[1] = iron_mp4_yuv_buf + iron_mp4_w * iron_mp4_h;
  1631. yuv.stride[1] = iron_mp4_w / 2;
  1632. yuv.yuv[2] = iron_mp4_yuv_buf + (int)(iron_mp4_w * iron_mp4_h * 1.25);
  1633. yuv.stride[2] = iron_mp4_w / 2;
  1634. uint8_t *coded_data;
  1635. int sizeof_coded_data;
  1636. H264E_encode(iron_mp4_enc, iron_mp4_scratch, &run_param, &yuv, &coded_data, &sizeof_coded_data);
  1637. fwrite(coded_data, sizeof_coded_data, 1, iron_mp4_fp);
  1638. }
  1639. #endif
  1640. #ifdef WITH_ONNX
  1641. buffer_t *iron_ml_inference(buffer_t *model, any_array_t *tensors, any_array_t *input_shape, i32_array_t *output_shape, bool use_gpu) {
  1642. OrtStatus *onnx_status = NULL;
  1643. static bool use_gpu_last = false;
  1644. if (ort == NULL || use_gpu_last != use_gpu) {
  1645. use_gpu_last = use_gpu;
  1646. ort = OrtGetApiBase()->GetApi(ORT_API_VERSION);
  1647. ort->CreateEnv(ORT_LOGGING_LEVEL_WARNING, "iron", &ort_env);
  1648. ort->CreateSessionOptions(&ort_session_options);
  1649. ort->SetIntraOpNumThreads(ort_session_options, 8);
  1650. ort->SetInterOpNumThreads(ort_session_options, 8);
  1651. if (use_gpu) {
  1652. #ifdef IRON_WINDOWS
  1653. ort->SetSessionExecutionMode(ort_session_options, ORT_SEQUENTIAL);
  1654. ort->DisableMemPattern(ort_session_options);
  1655. onnx_status = OrtSessionOptionsAppendExecutionProvider_DML(ort_session_options, 0);
  1656. #elif defined(IRON_LINUX)
  1657. // onnx_status = OrtSessionOptionsAppendExecutionProvider_CUDA(ort_session_options, 0);
  1658. #elif defined(IRON_MACOS)
  1659. onnx_status = OrtSessionOptionsAppendExecutionProvider_CoreML(ort_session_options, 0);
  1660. #endif
  1661. if (onnx_status != NULL) {
  1662. const char *msg = ort->GetErrorMessage(onnx_status);
  1663. iron_error("%s", msg);
  1664. ort->ReleaseStatus(onnx_status);
  1665. }
  1666. }
  1667. }
  1668. static void *content_last = 0;
  1669. if (content_last != model->buffer || session == NULL) {
  1670. if (session != NULL) {
  1671. ort->ReleaseSession(session);
  1672. session = NULL;
  1673. }
  1674. onnx_status = ort->CreateSessionFromArray(ort_env, model->buffer, (int)model->length, ort_session_options, &session);
  1675. if (onnx_status != NULL) {
  1676. const char* msg = ort->GetErrorMessage(onnx_status);
  1677. iron_error("%s", msg);
  1678. ort->ReleaseStatus(onnx_status);
  1679. }
  1680. }
  1681. content_last = model->buffer;
  1682. OrtAllocator *allocator;
  1683. ort->GetAllocatorWithDefaultOptions(&allocator);
  1684. OrtMemoryInfo *memory_info;
  1685. ort->CreateCpuMemoryInfo(OrtArenaAllocator, OrtMemTypeDefault, &memory_info);
  1686. int32_t length = tensors->length;
  1687. if (length > 4) {
  1688. length = 4;
  1689. }
  1690. char *input_node_names[4];
  1691. OrtValue *input_tensors[4];
  1692. for (int32_t i = 0; i < length; ++i) {
  1693. ort->SessionGetInputName(session, i, allocator, &input_node_names[i]);
  1694. OrtTypeInfo *input_type_info;
  1695. ort->SessionGetInputTypeInfo(session, i, &input_type_info);
  1696. const OrtTensorTypeAndShapeInfo *input_tensor_info;
  1697. ort->CastTypeInfoToTensorInfo(input_type_info, &input_tensor_info);
  1698. size_t num_input_dims;
  1699. ort->GetDimensionsCount(input_tensor_info, &num_input_dims);
  1700. int64_t input_node_dims[32];
  1701. if (input_shape != NULL) {
  1702. for (int32_t j = 0; j < num_input_dims; ++j) {
  1703. i32_array_t *a = input_shape->buffer[i];
  1704. input_node_dims[j] = a->buffer[j];
  1705. }
  1706. }
  1707. else {
  1708. ort->GetDimensions(input_tensor_info, (int64_t *)input_node_dims, num_input_dims);
  1709. }
  1710. ONNXTensorElementDataType tensor_element_type;
  1711. ort->GetTensorElementType(input_tensor_info, &tensor_element_type);
  1712. buffer_t *b = tensors->buffer[i];
  1713. ort->CreateTensorWithDataAsOrtValue(memory_info, b->buffer, (int)b->length, input_node_dims, num_input_dims, tensor_element_type, &input_tensors[i]);
  1714. ort->ReleaseTypeInfo(input_type_info);
  1715. }
  1716. char *output_node_name;
  1717. ort->SessionGetOutputName(session, 0, allocator, &output_node_name);
  1718. OrtValue *output_tensor = NULL;
  1719. onnx_status = ort->Run(session, NULL, input_node_names, input_tensors, length, &output_node_name, 1, &output_tensor);
  1720. if (onnx_status != NULL) {
  1721. const char* msg = ort->GetErrorMessage(onnx_status);
  1722. iron_error("%s", msg);
  1723. ort->ReleaseStatus(onnx_status);
  1724. }
  1725. float *float_array;
  1726. ort->GetTensorMutableData(output_tensor, (void **)&float_array);
  1727. size_t output_byte_length = 4;
  1728. if (output_shape != NULL) {
  1729. int32_t length = output_shape->length;
  1730. for (int i = 0; i < length; ++i) {
  1731. output_byte_length *= output_shape->buffer[i];
  1732. }
  1733. }
  1734. else {
  1735. OrtTypeInfo *output_type_info;
  1736. ort->SessionGetOutputTypeInfo(session, 0, &output_type_info);
  1737. const OrtTensorTypeAndShapeInfo *output_tensor_info;
  1738. ort->CastTypeInfoToTensorInfo(output_type_info, &output_tensor_info);
  1739. size_t num_output_dims;
  1740. ort->GetDimensionsCount(output_tensor_info, &num_output_dims);
  1741. int64_t output_node_dims[32];
  1742. ort->GetDimensions(output_tensor_info, (int64_t *)output_node_dims, num_output_dims);
  1743. ort->ReleaseTypeInfo(output_type_info);
  1744. for (int i = 0; i < num_output_dims; ++i) {
  1745. if (output_node_dims[i] > 1) {
  1746. output_byte_length *= output_node_dims[i];
  1747. }
  1748. }
  1749. }
  1750. buffer_t *output = buffer_create(output_byte_length);
  1751. memcpy(output->buffer, float_array, output_byte_length);
  1752. ort->ReleaseMemoryInfo(memory_info);
  1753. ort->ReleaseValue(output_tensor);
  1754. for (int i = 0; i < length; ++i) {
  1755. ort->ReleaseValue(input_tensors[i]);
  1756. }
  1757. return output;
  1758. }
  1759. void iron_ml_unload() {
  1760. if (session != NULL) {
  1761. ort->ReleaseSession(session);
  1762. session = NULL;
  1763. }
  1764. }
  1765. #endif
  1766. void iron_raytrace_init(buffer_t *shader) {
  1767. if (rt_created) {
  1768. gpu_constant_buffer_destroy(&rt_constant_buffer);
  1769. gpu_raytrace_pipeline_destroy(&rt_pipeline);
  1770. }
  1771. rt_created = true;
  1772. gpu_constant_buffer_init(&rt_constant_buffer, rt_constant_buffer_size * 4);
  1773. gpu_raytrace_pipeline_init(&rt_pipeline, shader->buffer, (int)shader->length, &rt_constant_buffer);
  1774. }
  1775. void iron_raytrace_as_init() {
  1776. if (rt_accel_created) {
  1777. gpu_raytrace_acceleration_structure_destroy(&rt_accel);
  1778. }
  1779. rt_accel_created = true;
  1780. gpu_raytrace_acceleration_structure_init(&rt_accel);
  1781. }
  1782. void iron_raytrace_as_add(struct gpu_buffer *vb, gpu_buffer_t *ib, iron_matrix4x4_t transform) {
  1783. gpu_raytrace_acceleration_structure_add(&rt_accel, vb, ib, transform);
  1784. }
  1785. void iron_raytrace_as_build(struct gpu_buffer *vb_full, gpu_buffer_t *ib_full) {
  1786. gpu_raytrace_acceleration_structure_build(&rt_accel, vb_full, ib_full);
  1787. }
  1788. void iron_raytrace_set_textures(gpu_texture_t *tex0, gpu_texture_t *tex1, gpu_texture_t *tex2, gpu_texture_t *texenv, gpu_texture_t *texsobol, gpu_texture_t *texscramble, gpu_texture_t *texrank) {
  1789. gpu_raytrace_set_textures(tex0, tex1, tex2, texenv, texsobol, texscramble, texrank);
  1790. }
  1791. void iron_raytrace_dispatch_rays(gpu_texture_t *render_target, buffer_t *buffer) {
  1792. float *cb = (float *)buffer->buffer;
  1793. gpu_constant_buffer_lock(&rt_constant_buffer, 0, rt_constant_buffer.count);
  1794. for (int i = 0; i < rt_constant_buffer_size; ++i) {
  1795. float *floats = (float *)(&rt_constant_buffer.data[i * 4]);
  1796. floats[0] = cb[i];
  1797. }
  1798. gpu_constant_buffer_unlock(&rt_constant_buffer);
  1799. gpu_raytrace_set_acceleration_structure(&rt_accel);
  1800. gpu_raytrace_set_pipeline(&rt_pipeline);
  1801. gpu_raytrace_set_target(render_target);
  1802. gpu_raytrace_dispatch_rays();
  1803. }
  1804. #endif