-
Notifications
You must be signed in to change notification settings - Fork 38
/
Copy pathinit.hpp
221 lines (180 loc) · 6.33 KB
/
init.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
/**
* @note This file is part of Empirical, https://github.com/devosoft/Empirical
* @copyright Copyright (C) Michigan State University, MIT Software license; see doc/LICENSE.md
* @date 2015-2018.
*
* @file init.hpp
* @brief Define Initialize() and other functions to set up Empirical to build Emscripten projects.
*/
#ifndef EMP_INIT_H
#define EMP_INIT_H
#include <type_traits>
/// If __EMSCRIPTEN__ is defined, initialize everything. Otherwise create useful stubs.
#ifdef __EMSCRIPTEN__
#include <emscripten.h>
#include "../tools/string_utils.hpp"
#ifdef __EMSCRIPTEN_PTHREADS__
#include <pthread.h>
#endif // __EMSCRIPTEN_PTHREADS__
// temporary patch for https://github.com/emscripten-core/emscripten/issues/11539
#define MAIN_THREAD_EMP_ASM(...) [&](){ \
[[maybe_unused]] volatile int no_optimize{}; \
MAIN_THREAD_EM_ASM(__VA_ARGS__); \
}()
extern "C" {
extern void EMP_Initialize();
}
namespace emp {
/// Setup timings on animations through Emscripten.
static void InitializeAnim() {
thread_local bool init = false; // Make sure we only initialize once!
if (!init) {
// Setup the animation callback in Javascript
MAIN_THREAD_EMP_ASM({
window.requestAnimFrame = (function(callback) {
return window.requestAnimationFrame
|| window.webkitRequestAnimationFrame
|| window.mozRequestAnimationFrame
|| window.oRequestAnimationFrame
|| window.msRequestAnimationFrame
|| function(callback) { window.setTimeout(callback, 1000 / 60); };
})();
});
}
init = true;
}
/// Add a listener on the browser thread that will look for incoming
/// bitmaps and transfer them into web canvases.
static void InitializeBitmapListener() {
#ifdef __EMSCRIPTEN_PTHREADS__
// adapted from https://stackoverflow.com/a/18002694
if ( EM_ASM_INT({ // detect if we are a web worker
return typeof WorkerGlobalScope !== 'undefined'
&& self instanceof WorkerGlobalScope;
}) ) {
MAIN_THREAD_EMP_ASM({
console.assert( Object.keys( PThread.pthreads ).length === 1 );
Object.values(PThread.pthreads)[0].worker.addEventListener(
'message',
function( event ){
if ( event.data.emp_canvas_id ) {
document.getElementById(
event.data.emp_canvas_id
).getContext("bitmaprenderer").transferFromImageBitmap( event.data.emp_bitmap
);
}
}
)
});
}
#endif // __EMSCRIPTEN_PTHREADS__
}
/// Create a offscreen canvases registry that maps id to impl and a registry
/// for updated canvases that need to be sent to the main thread.
static void InitializeOffscreenCanvasRegistries() {
#ifdef __EMSCRIPTEN_PTHREADS__
// adapted from https://stackoverflow.com/a/18002694
if ( EM_ASM_INT({ // detect if we are a web worker
return typeof WorkerGlobalScope !== 'undefined'
&& self instanceof WorkerGlobalScope;
}) ) EM_ASM({
emp_i.offscreen_canvases = {};
emp_i.pending_offscreen_canvas_ids = new Set();
});
#endif // __EMSCRIPTEN_PTHREADS__
}
/// globalThis polyfill to provide globalThis support in older environments
/// adapted from https://mathiasbynens.be/notes/globalthis
static void SetupGlobalThisPolyfill() {
EM_ASM({
(function() {
if (typeof globalThis === 'object') return;
Object.prototype.__defineGetter__('__magic__', function() {
return this;
});
__magic__.globalThis = __magic__; // lolwat
delete Object.prototype.__magic__;
}());
});
}
/// Do all initializations for using EMP tricks with Emscripten.
static void Initialize() {
SetupGlobalThisPolyfill();
// have to dip into javascript because static and thread_local are wonky
// with pthreads
const bool should_run = EM_ASM_INT({
if ( !globalThis.emp_init_once_flag ) {
globalThis.emp_init_once_flag = true;
return true;
} else return false;
});
if ( should_run ) {
EMP_Initialize(); // Call JS initializations
InitializeAnim();
#ifdef __EMSCRIPTEN_PTHREADS__
MAIN_THREAD_EMP_ASM({ _EMP_Initialize(); });
InitializeBitmapListener();
InitializeOffscreenCanvasRegistries();
#endif
}
}
namespace web {
// Some helper functions.
// Live keyword means that whatever is passed in needs to be re-evaluated every update.
namespace internal {
/// If a variable is passed in to Live(), construct a function to look up its current value.
template <typename VAR_TYPE>
std::function<std::string()> Live_impl(VAR_TYPE & var, int) {
return [&var](){ return emp::to_string(var); };
}
/// If a non-variable is passed in to Live(), assume it is a function and print it each redraw.
template <
typename IN_TYPE,
typename = std::enable_if_t< std::is_invocable<IN_TYPE>::value >
>
std::function<std::string()> Live_impl(IN_TYPE && fun, bool) {
return [fun](){ return emp::to_string(fun()); };
}
}
/// Take a function or variable and set it up so that it can update each time a text box is redrawn.
template <typename T>
std::function<std::string()> Live(T && val) {
return internal::Live_impl(std::forward<T>(val), bool{});
}
inline std::string ToJSLiteral(bool x) {
if (x == true) return "true";
else return "false";
}
}
}
// === Initialization for NON-emscripten to ignore macros ===
#else
#define MAIN_THREAD_EMP_ASM(...)
#define MAIN_THREAD_EMP_ASM(...)
#define MAIN_THREAD_EM_ASM_INT(...) 0
#define MAIN_THREAD_EM_ASM_DOUBLE(...) 0.0
#define MAIN_THREAD_EM_ASM_INT_V(...) 0
#define MAIN_THREAD_EM_ASM_DOUBLE_V(...) 0.0
#include <fstream>
namespace emp {
std::ofstream debug_file("debug_file");
/// Stub for when Emscripten is not in use.
static bool Initialize() {
// Nothing to do here yet...
static_assert(false, "Emscripten web tools require emcc for compilation (for now).");
return true;
}
/// Stub for when Emscripten is not in use.
static bool InitializeAnim() {
// Nothing to do here yet...
return true;
}
namespace web {
inline std::string ToJSLiteral(bool x) {
if (x == true) return "true";
else return "false";
}
}
}
#endif
#endif