blob: d6510e66ad6af49c11a2d03eabab81583f21c29b [file] [log] [blame]
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001// helper JS that could be used anywhere in the glue code
Kevin Lubick217056c2018-09-20 17:39:31 -04002
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05003function clamp(c) {
4 return Math.round(Math.max(0, Math.min(c || 0, 255)));
5}
Kevin Lubick217056c2018-09-20 17:39:31 -04006
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05007// Colors are just a 32 bit number with 8 bits each of a, r, g, b
8// The API is the same as CSS's representation of color rgba(), that is
9// r,g,b are 0-255, and a is 0.0 to 1.0.
10// if a is omitted, it will be assumed to be 1.0
11CanvasKit.Color = function(r, g, b, a) {
12 if (a === undefined) {
13 a = 1;
Kevin Lubick217056c2018-09-20 17:39:31 -040014 }
Kevin Lubickee91c072019-03-29 10:39:52 -040015 // The >>> 0 converts the signed int to an unsigned int. Skia's
16 // SkColor object is an unsigned int.
17 // https://stackoverflow.com/a/14891172
18 return ((clamp(a*255) << 24) | (clamp(r) << 16) | (clamp(g) << 8) | (clamp(b) << 0)) >>> 0;
Kevin Lubickf5ea37f2019-02-28 10:06:18 -050019}
Kevin Lubick217056c2018-09-20 17:39:31 -040020
Kevin Lubickf5ea37f2019-02-28 10:06:18 -050021// returns [r, g, b, a] from a color
22// where a is scaled between 0 and 1.0
23CanvasKit.getColorComponents = function(color) {
24 return [
25 (color >> 16) & 0xFF,
26 (color >> 8) & 0xFF,
27 (color >> 0) & 0xFF,
28 ((color >> 24) & 0xFF) / 255,
29 ]
30}
31
32CanvasKit.multiplyByAlpha = function(color, alpha) {
33 if (alpha === 1) {
34 return color;
Kevin Lubick217056c2018-09-20 17:39:31 -040035 }
Kevin Lubickf5ea37f2019-02-28 10:06:18 -050036 // extract as int from 0 to 255
37 var a = (color >> 24) & 0xFF;
38 a *= alpha;
39 // mask off the old alpha
40 color &= 0xFFFFFF;
Kevin Lubickee91c072019-03-29 10:39:52 -040041 // back to unsigned int to match SkColor.
42 return (clamp(a) << 24 | color) >>> 0;
Kevin Lubickf5ea37f2019-02-28 10:06:18 -050043}
Kevin Lubick61ef7b22018-11-27 13:26:59 -050044
Kevin Lubickf5ea37f2019-02-28 10:06:18 -050045function radiansToDegrees(rad) {
46 return (rad / Math.PI) * 180;
47}
Kevin Lubick12c0e502018-11-28 12:51:56 -050048
Kevin Lubickf5ea37f2019-02-28 10:06:18 -050049function degreesToRadians(deg) {
50 return (deg / 180) * Math.PI;
51}
Kevin Lubick12c0e502018-11-28 12:51:56 -050052
53// See https://stackoverflow.com/a/31090240
54// This contraption keeps closure from minifying away the check
55// if btoa is defined *and* prevents runtime "btoa" or "window" is not defined.
56// Defined outside any scopes to make it available in all files.
57var isNode = !(new Function("try {return this===window;}catch(e){ return false;}")());
Kevin Lubick1646e7d2018-12-07 13:03:08 -050058
59function almostEqual(floata, floatb) {
60 return Math.abs(floata - floatb) < 0.00001;
Kevin Lubickf5ea37f2019-02-28 10:06:18 -050061}
62
63
64var nullptr = 0; // emscripten doesn't like to take null as uintptr_t
65
66// arr can be a normal JS array or a TypedArray
67// dest is something like CanvasKit.HEAPF32
68function copy1dArray(arr, dest) {
69 if (!arr || !arr.length) {
70 return nullptr;
71 }
72 var ptr = CanvasKit._malloc(arr.length * dest.BYTES_PER_ELEMENT);
73 // In c++ terms, the WASM heap is a uint8_t*, a long buffer/array of single
74 // byte elements. When we run _malloc, we always get an offset/pointer into
75 // that block of memory.
76 // CanvasKit exposes some different views to make it easier to work with
77 // different types. HEAPF32 for example, exposes it as a float*
78 // However, to make the ptr line up, we have to do some pointer arithmetic.
79 // Concretely, we need to convert ptr to go from an index into a 1-byte-wide
80 // buffer to an index into a 4-byte-wide buffer (in the case of HEAPF32)
81 // and thus we divide ptr by 4.
82 dest.set(arr, ptr / dest.BYTES_PER_ELEMENT);
83 return ptr;
84}
85
86// arr should be a non-jagged 2d JS array (TypedArrays can't be nested
87// inside themselves.)
88// dest is something like CanvasKit.HEAPF32
89function copy2dArray(arr, dest) {
90 if (!arr || !arr.length) {
91 return nullptr;
92 }
93 var ptr = CanvasKit._malloc(arr.length * arr[0].length * dest.BYTES_PER_ELEMENT);
94 var idx = 0;
95 var adjustedPtr = ptr / dest.BYTES_PER_ELEMENT;
96 for (var r = 0; r < arr.length; r++) {
97 for (var c = 0; c < arr[0].length; c++) {
98 dest[adjustedPtr + idx] = arr[r][c];
99 idx++;
100 }
101 }
102 return ptr;
103}
104
105// arr should be a non-jagged 3d JS array (TypedArrays can't be nested
106// inside themselves.)
107// dest is something like CanvasKit.HEAPF32
108function copy3dArray(arr, dest) {
109 if (!arr || !arr.length || !arr[0].length) {
110 return nullptr;
111 }
112 var ptr = CanvasKit._malloc(arr.length * arr[0].length * arr[0][0].length * dest.BYTES_PER_ELEMENT);
113 var idx = 0;
114 var adjustedPtr = ptr / dest.BYTES_PER_ELEMENT;
115 for (var x = 0; x < arr.length; x++) {
116 for (var y = 0; y < arr[0].length; y++) {
117 for (var z = 0; z < arr[0][0].length; z++) {
118 dest[adjustedPtr + idx] = arr[x][y][z];
119 idx++;
120 }
121 }
122 }
123 return ptr;
124}
125
126// Caching the Float32Arrays can save having to reallocate them
127// over and over again.
128var Float32ArrayCache = {};
129
130// Takes a 2D array of commands and puts them into the WASM heap
131// as a 1D array. This allows them to referenced from the C++ code.
132// Returns a 2 element array, with the first item being essentially a
133// pointer to the array and the second item being the length of
134// the new 1D array.
135//
136// Example usage:
137// let cmds = [
138// [CanvasKit.MOVE_VERB, 0, 10],
139// [CanvasKit.LINE_VERB, 30, 40],
140// [CanvasKit.QUAD_VERB, 20, 50, 45, 60],
141// ];
142function loadCmdsTypedArray(arr) {
143 var len = 0;
144 for (var r = 0; r < arr.length; r++) {
145 len += arr[r].length;
146 }
147
148 var ta;
149 if (Float32ArrayCache[len]) {
150 ta = Float32ArrayCache[len];
151 } else {
152 ta = new Float32Array(len);
153 Float32ArrayCache[len] = ta;
154 }
155 // Flatten into a 1d array
156 var i = 0;
157 for (var r = 0; r < arr.length; r++) {
158 for (var c = 0; c < arr[r].length; c++) {
159 var item = arr[r][c];
160 ta[i] = item;
161 i++;
162 }
163 }
164
165 var ptr = copy1dArray(ta, CanvasKit.HEAPF32);
166 return [ptr, len];
167}
Kevin Lubickd3cfbca2019-03-15 15:36:29 -0400168
Kevin Lubickcc13fd32019-04-05 13:00:01 -0400169function saveBytesToFile(bytes, fileName) {
170 if (!isNode) {
171 // https://stackoverflow.com/a/32094834
172 var blob = new Blob([bytes], {type: 'application/octet-stream'});
173 url = window.URL.createObjectURL(blob);
174 var a = document.createElement('a');
175 document.body.appendChild(a);
176 a.href = url;
177 a.download = fileName;
178 a.click();
179 // clean up after because FF might not download it synchronously
180 setTimeout(function() {
181 URL.revokeObjectURL(url);
182 a.remove();
183 }, 50);
184 } else {
185 var fs = require('fs');
186 // https://stackoverflow.com/a/42006750
187 // https://stackoverflow.com/a/47018122
188 fs.writeFile(fileName, new Buffer(bytes), function(err) {
189 if (err) throw err;
190 });
191 }
192}
Kevin Lubickee91c072019-03-29 10:39:52 -0400193/**
194 * Generic helper for dealing with an array of four floats.
195 */
196CanvasKit.FourFloatArrayHelper = function() {
197 this._floats = [];
Kevin Lubickd3cfbca2019-03-15 15:36:29 -0400198 this._ptr = null;
Kevin Lubickee91c072019-03-29 10:39:52 -0400199
200 Object.defineProperty(this, 'length', {
201 enumerable: true,
202 get: function() {
203 return this._floats.length / 4;
204 },
205 });
Kevin Lubickd3cfbca2019-03-15 15:36:29 -0400206}
207
208/**
Kevin Lubickee91c072019-03-29 10:39:52 -0400209 * push the four floats onto the end of the array - if build() has already
210 * been called, the call will return without modifying anything.
Kevin Lubickd3cfbca2019-03-15 15:36:29 -0400211 */
Kevin Lubickee91c072019-03-29 10:39:52 -0400212CanvasKit.FourFloatArrayHelper.prototype.push = function(f1, f2, f3, f4) {
Kevin Lubickd3cfbca2019-03-15 15:36:29 -0400213 if (this._ptr) {
214 SkDebug('Cannot push more points - already built');
215 return;
216 }
Kevin Lubickee91c072019-03-29 10:39:52 -0400217 this._floats.push(f1, f2, f3, f4);
Kevin Lubickd3cfbca2019-03-15 15:36:29 -0400218}
219
Kevin Lubickee91c072019-03-29 10:39:52 -0400220/**
221 * Set the four floats at a given index - if build() has already
222 * been called, the WASM memory will be written to directly.
223 */
224CanvasKit.FourFloatArrayHelper.prototype.set = function(idx, f1, f2, f3, f4) {
225 if (idx < 0 || idx >= this._floats.length/4) {
226 SkDebug('Cannot set index ' + idx + ', it is out of range', this._floats.length/4);
227 return;
228 }
229 idx *= 4;
230 var BYTES_PER_ELEMENT = 4;
231 if (this._ptr) {
232 // convert this._ptr from uint8_t* to SkScalar* by dividing by 4
233 var floatPtr = (this._ptr / BYTES_PER_ELEMENT) + idx;
234 CanvasKit.HEAPF32[floatPtr] = f1;
235 CanvasKit.HEAPF32[floatPtr + 1] = f2;
236 CanvasKit.HEAPF32[floatPtr + 2] = f3;
237 CanvasKit.HEAPF32[floatPtr + 3] = f4;
238 return;
239 }
240 this._floats[idx] = f1;
241 this._floats[idx + 1] = f2;
242 this._floats[idx + 2] = f3;
243 this._floats[idx + 3] = f4;
244}
245
246/**
247 * Copies the float data to the WASM memory and returns a pointer
248 * to that allocated memory. Once build has been called, this
249 * float array cannot be made bigger.
250 */
251CanvasKit.FourFloatArrayHelper.prototype.build = function() {
Kevin Lubickd3cfbca2019-03-15 15:36:29 -0400252 if (this._ptr) {
253 return this._ptr;
254 }
Kevin Lubickee91c072019-03-29 10:39:52 -0400255 this._ptr = copy1dArray(this._floats, CanvasKit.HEAPF32);
Kevin Lubickd3cfbca2019-03-15 15:36:29 -0400256 return this._ptr;
257}
258
Kevin Lubickee91c072019-03-29 10:39:52 -0400259/**
260 * Frees the wasm memory associated with this array. Of note,
261 * the points are not removed, so push/set/build can all
262 * be called to make a newly allocated (possibly bigger)
263 * float array.
264 */
265CanvasKit.FourFloatArrayHelper.prototype.delete = function() {
Kevin Lubickd3cfbca2019-03-15 15:36:29 -0400266 if (this._ptr) {
267 CanvasKit._free(this._ptr);
268 this._ptr = null;
269 }
270}
Kevin Lubickee91c072019-03-29 10:39:52 -0400271
272/**
273 * Generic helper for dealing with an array of unsigned ints.
274 */
275CanvasKit.OneUIntArrayHelper = function() {
276 this._uints = [];
277 this._ptr = null;
278
279 Object.defineProperty(this, 'length', {
280 enumerable: true,
281 get: function() {
282 return this._uints.length;
283 },
284 });
285}
286
287/**
288 * push the unsigned int onto the end of the array - if build() has already
289 * been called, the call will return without modifying anything.
290 */
291CanvasKit.OneUIntArrayHelper.prototype.push = function(u) {
292 if (this._ptr) {
293 SkDebug('Cannot push more points - already built');
294 return;
295 }
296 this._uints.push(u);
297}
298
299/**
300 * Set the uint at a given index - if build() has already
301 * been called, the WASM memory will be written to directly.
302 */
303CanvasKit.OneUIntArrayHelper.prototype.set = function(idx, u) {
304 if (idx < 0 || idx >= this._uints.length) {
305 SkDebug('Cannot set index ' + idx + ', it is out of range', this._uints.length);
306 return;
307 }
308 idx *= 4;
309 var BYTES_PER_ELEMENT = 4;
310 if (this._ptr) {
311 // convert this._ptr from uint8_t* to SkScalar* by dividing by 4
312 var uintPtr = (this._ptr / BYTES_PER_ELEMENT) + idx;
313 CanvasKit.HEAPU32[uintPtr] = u;
314 return;
315 }
316 this._uints[idx] = u;
317}
318
319/**
320 * Copies the uint data to the WASM memory and returns a pointer
321 * to that allocated memory. Once build has been called, this
322 * unit array cannot be made bigger.
323 */
324CanvasKit.OneUIntArrayHelper.prototype.build = function() {
325 if (this._ptr) {
326 return this._ptr;
327 }
328 this._ptr = copy1dArray(this._uints, CanvasKit.HEAPU32);
329 return this._ptr;
330}
331
332/**
333 * Frees the wasm memory associated with this array. Of note,
334 * the points are not removed, so push/set/build can all
335 * be called to make a newly allocated (possibly bigger)
336 * uint array.
337 */
338CanvasKit.OneUIntArrayHelper.prototype.delete = function() {
339 if (this._ptr) {
340 CanvasKit._free(this._ptr);
341 this._ptr = null;
342 }
343}
344
345/**
346 * Helper for building an array of SkRects (which are just structs
347 * of 4 floats).
348 *
349 * It can be more performant to use this helper, as
350 * the C++-side array is only allocated once (on the first call)
351 * to build. Subsequent set() operations operate directly on
352 * the C++-side array, avoiding having to re-allocate (and free)
353 * the array every time.
354 *
355 * Input points are taken as left, top, right, bottom
356 */
357CanvasKit.SkRectBuilder = CanvasKit.FourFloatArrayHelper;
358/**
359 * Helper for building an array of RSXForms (which are just structs
360 * of 4 floats).
361 *
362 * It can be more performant to use this helper, as
363 * the C++-side array is only allocated once (on the first call)
364 * to build. Subsequent set() operations operate directly on
365 * the C++-side array, avoiding having to re-allocate (and free)
366 * the array every time.
367 *
368 * An RSXForm is a compressed form of a rotation+scale matrix.
369 *
370 * [ scos -ssin tx ]
371 * [ ssin scos ty ]
372 * [ 0 0 1 ]
373 *
374 * Input points are taken as scos, ssin, tx, ty
375 */
376CanvasKit.RSXFormBuilder = CanvasKit.FourFloatArrayHelper;
377
378/**
379 * Helper for building an array of SkColor
380 *
381 * It can be more performant to use this helper, as
382 * the C++-side array is only allocated once (on the first call)
383 * to build. Subsequent set() operations operate directly on
384 * the C++-side array, avoiding having to re-allocate (and free)
385 * the array every time.
386 */
387CanvasKit.SkColorBuilder = CanvasKit.OneUIntArrayHelper;