blob: 78e62f3c30a900f9e1e07cafad007301eacc9cf6 [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
Nathaniel Nifonge5d32542020-03-26 09:27:48 -04007// Constructs a Color with the same API as CSS's rgba(), that is
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05008// r,g,b are 0-255, and a is 0.0 to 1.0.
9// if a is omitted, it will be assumed to be 1.0
Nathaniel Nifonge5d32542020-03-26 09:27:48 -040010// Internally, Colors are a TypedArray of four unpremultiplied 32-bit floats: a, r, g, b
11// In order to construct one with more precision or in a wider gamut, use
12// CanvasKit.Color4f
Kevin Lubickf5ea37f2019-02-28 10:06:18 -050013CanvasKit.Color = function(r, g, b, a) {
14 if (a === undefined) {
15 a = 1;
Kevin Lubick217056c2018-09-20 17:39:31 -040016 }
Nathaniel Nifonge5d32542020-03-26 09:27:48 -040017 return CanvasKit.Color4f(clamp(r)/255, clamp(g)/255, clamp(b)/255, a);
Kevin Lubickf5ea37f2019-02-28 10:06:18 -050018}
Kevin Lubick217056c2018-09-20 17:39:31 -040019
Nathaniel Nifonge5d32542020-03-26 09:27:48 -040020// Construct a 4-float color.
21// Opaque if opacity is omitted.
22CanvasKit.Color4f = function(r, g, b, a) {
23 if (a === undefined) {
24 a = 1;
25 }
26 return Float32Array.of(r, g, b, a);
27}
28
29// Color constants use property getters to prevent other code from accidentally
30// changing them.
31Object.defineProperty(CanvasKit, "TRANSPARENT", {
32 get: function() { return CanvasKit.Color4f(0, 0, 0, 0); }
33});
34Object.defineProperty(CanvasKit, "BLACK", {
35 get: function() { return CanvasKit.Color4f(0, 0, 0, 1); }
36});
37Object.defineProperty(CanvasKit, "WHITE", {
38 get: function() { return CanvasKit.Color4f(1, 1, 1, 1); }
39});
40Object.defineProperty(CanvasKit, "RED", {
41 get: function() { return CanvasKit.Color4f(1, 0, 0, 1); }
42});
43Object.defineProperty(CanvasKit, "GREEN", {
44 get: function() { return CanvasKit.Color4f(0, 1, 0, 1); }
45});
46Object.defineProperty(CanvasKit, "BLUE", {
47 get: function() { return CanvasKit.Color4f(0, 0, 1, 1); }
48});
49Object.defineProperty(CanvasKit, "YELLOW", {
50 get: function() { return CanvasKit.Color4f(1, 1, 0, 1); }
51});
52Object.defineProperty(CanvasKit, "CYAN", {
53 get: function() { return CanvasKit.Color4f(0, 1, 1, 1); }
54});
55Object.defineProperty(CanvasKit, "MAGENTA", {
56 get: function() { return CanvasKit.Color4f(1, 0, 1, 1); }
57});
58
59// returns a css style [r, g, b, a] from a CanvasKit.Color
60// where r, g, b are returned as ints in the range [0, 255]
Kevin Lubickf5ea37f2019-02-28 10:06:18 -050061// where a is scaled between 0 and 1.0
62CanvasKit.getColorComponents = function(color) {
63 return [
Nathaniel Nifonge5d32542020-03-26 09:27:48 -040064 Math.floor(color[0]*255),
65 Math.floor(color[1]*255),
66 Math.floor(color[2]*255),
67 color[3]
68 ];
Kevin Lubickf5ea37f2019-02-28 10:06:18 -050069}
70
Kevin Lubick39284662020-02-20 10:29:55 -050071// parseColorString takes in a CSS color value and returns a CanvasKit.Color
Nathaniel Nifonge5d32542020-03-26 09:27:48 -040072// (which is an array of 4 floats in RGBA order). An optional colorMap
73// may be provided which maps custom strings to values.
Kevin Lubick39284662020-02-20 10:29:55 -050074// In the CanvasKit canvas2d shim layer, we provide this map for processing
75// canvas2d calls, but not here for code size reasons.
76CanvasKit.parseColorString = function(colorStr, colorMap) {
77 colorStr = colorStr.toLowerCase();
78 // See https://drafts.csswg.org/css-color/#typedef-hex-color
79 if (colorStr.startsWith('#')) {
80 var r, g, b, a = 255;
81 switch (colorStr.length) {
82 case 9: // 8 hex chars #RRGGBBAA
83 a = parseInt(colorStr.slice(7, 9), 16);
84 case 7: // 6 hex chars #RRGGBB
85 r = parseInt(colorStr.slice(1, 3), 16);
86 g = parseInt(colorStr.slice(3, 5), 16);
87 b = parseInt(colorStr.slice(5, 7), 16);
88 break;
89 case 5: // 4 hex chars #RGBA
90 // multiplying by 17 is the same effect as
91 // appending another character of the same value
92 // e.g. e => ee == 14 => 238
93 a = parseInt(colorStr.slice(4, 5), 16) * 17;
94 case 4: // 6 hex chars #RGB
95 r = parseInt(colorStr.slice(1, 2), 16) * 17;
96 g = parseInt(colorStr.slice(2, 3), 16) * 17;
97 b = parseInt(colorStr.slice(3, 4), 16) * 17;
98 break;
99 }
100 return CanvasKit.Color(r, g, b, a/255);
101
102 } else if (colorStr.startsWith('rgba')) {
103 // Trim off rgba( and the closing )
104 colorStr = colorStr.slice(5, -1);
105 var nums = colorStr.split(',');
106 return CanvasKit.Color(+nums[0], +nums[1], +nums[2],
107 valueOrPercent(nums[3]));
108 } else if (colorStr.startsWith('rgb')) {
109 // Trim off rgba( and the closing )
110 colorStr = colorStr.slice(4, -1);
111 var nums = colorStr.split(',');
112 // rgb can take 3 or 4 arguments
113 return CanvasKit.Color(+nums[0], +nums[1], +nums[2],
114 valueOrPercent(nums[3]));
115 } else if (colorStr.startsWith('gray(')) {
116 // TODO
117 } else if (colorStr.startsWith('hsl')) {
118 // TODO
119 } else if (colorMap) {
120 // Try for named color
121 var nc = colorMap[colorStr];
122 if (nc !== undefined) {
123 return nc;
124 }
125 }
126 SkDebug('unrecognized color ' + colorStr);
127 return CanvasKit.BLACK;
128}
129
Nathaniel Nifonge5d32542020-03-26 09:27:48 -0400130function isCanvasKitColor(ob) {
131 if (!ob) {
132 return false;
133 }
134 return (ob.constructor === Float32Array && ob.length === 4);
135}
136
137// Warning information is lost by this conversion
138function toUint32Color(c) {
139 return ((clamp(c[3]*255) << 24) | (clamp(c[0]*255) << 16) | (clamp(c[1]*255) << 8) | (clamp(c[2]*255) << 0)) >>> 0;
140}
141function uIntColorToCanvasKitColor(c) {
142 return CanvasKit.Color(
143 (c >> 16) & 0xFF,
144 (c >> 8) & 0xFF,
145 (c >> 0) & 0xFF,
146 ((c >> 24) & 0xFF) / 255
147 );
148}
149
Kevin Lubick39284662020-02-20 10:29:55 -0500150function valueOrPercent(aStr) {
151 if (aStr === undefined) {
152 return 1; // default to opaque.
153 }
154 var a = parseFloat(aStr);
155 if (aStr && aStr.indexOf('%') !== -1) {
156 return a / 100;
157 }
158 return a;
159}
160
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500161CanvasKit.multiplyByAlpha = function(color, alpha) {
Nathaniel Nifonge5d32542020-03-26 09:27:48 -0400162 // make a copy of the color so the function remains pure.
163 var result = color.slice();
164 result[3] = Math.max(0, Math.min(result[3] * alpha, 1));
165 return result;
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500166}
Kevin Lubick61ef7b22018-11-27 13:26:59 -0500167
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500168function radiansToDegrees(rad) {
169 return (rad / Math.PI) * 180;
170}
Kevin Lubick12c0e502018-11-28 12:51:56 -0500171
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500172function degreesToRadians(deg) {
173 return (deg / 180) * Math.PI;
174}
Kevin Lubick12c0e502018-11-28 12:51:56 -0500175
176// See https://stackoverflow.com/a/31090240
177// This contraption keeps closure from minifying away the check
178// if btoa is defined *and* prevents runtime "btoa" or "window" is not defined.
179// Defined outside any scopes to make it available in all files.
180var isNode = !(new Function("try {return this===window;}catch(e){ return false;}")());
Kevin Lubick1646e7d2018-12-07 13:03:08 -0500181
182function almostEqual(floata, floatb) {
183 return Math.abs(floata - floatb) < 0.00001;
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500184}
185
186
187var nullptr = 0; // emscripten doesn't like to take null as uintptr_t
188
189// arr can be a normal JS array or a TypedArray
190// dest is something like CanvasKit.HEAPF32
Kevin Lubickd6ba7252019-06-03 14:38:05 -0400191// ptr can be optionally provided if the memory was already allocated.
192function copy1dArray(arr, dest, ptr) {
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500193 if (!arr || !arr.length) {
194 return nullptr;
195 }
Kevin Lubicke25df6c2019-10-22 09:04:32 -0400196 // This was created with CanvasKit.Malloc, so it's already been copied.
197 if (arr['_ck']) {
198 return arr.byteOffset;
199 }
Kevin Lubickd6ba7252019-06-03 14:38:05 -0400200 if (!ptr) {
201 ptr = CanvasKit._malloc(arr.length * dest.BYTES_PER_ELEMENT);
202 }
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500203 // In c++ terms, the WASM heap is a uint8_t*, a long buffer/array of single
204 // byte elements. When we run _malloc, we always get an offset/pointer into
205 // that block of memory.
206 // CanvasKit exposes some different views to make it easier to work with
207 // different types. HEAPF32 for example, exposes it as a float*
208 // However, to make the ptr line up, we have to do some pointer arithmetic.
209 // Concretely, we need to convert ptr to go from an index into a 1-byte-wide
210 // buffer to an index into a 4-byte-wide buffer (in the case of HEAPF32)
211 // and thus we divide ptr by 4.
212 dest.set(arr, ptr / dest.BYTES_PER_ELEMENT);
213 return ptr;
214}
215
216// arr should be a non-jagged 2d JS array (TypedArrays can't be nested
Kevin Lubick37ab53e2019-11-11 10:06:08 -0500217// inside themselves). A common use case is points.
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500218// dest is something like CanvasKit.HEAPF32
Kevin Lubickd6ba7252019-06-03 14:38:05 -0400219// ptr can be optionally provided if the memory was already allocated.
220function copy2dArray(arr, dest, ptr) {
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500221 if (!arr || !arr.length) {
222 return nullptr;
223 }
Kevin Lubickd6ba7252019-06-03 14:38:05 -0400224 if (!ptr) {
225 ptr = CanvasKit._malloc(arr.length * arr[0].length * dest.BYTES_PER_ELEMENT);
226 }
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500227 var idx = 0;
228 var adjustedPtr = ptr / dest.BYTES_PER_ELEMENT;
229 for (var r = 0; r < arr.length; r++) {
230 for (var c = 0; c < arr[0].length; c++) {
231 dest[adjustedPtr + idx] = arr[r][c];
232 idx++;
233 }
234 }
235 return ptr;
236}
237
238// arr should be a non-jagged 3d JS array (TypedArrays can't be nested
239// inside themselves.)
240// dest is something like CanvasKit.HEAPF32
Kevin Lubickd6ba7252019-06-03 14:38:05 -0400241// ptr can be optionally provided if the memory was already allocated.
242function copy3dArray(arr, dest, ptr) {
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500243 if (!arr || !arr.length || !arr[0].length) {
244 return nullptr;
245 }
Kevin Lubickd6ba7252019-06-03 14:38:05 -0400246 if (!ptr) {
247 ptr = CanvasKit._malloc(arr.length * arr[0].length * arr[0][0].length * dest.BYTES_PER_ELEMENT);
248 }
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500249 var idx = 0;
250 var adjustedPtr = ptr / dest.BYTES_PER_ELEMENT;
251 for (var x = 0; x < arr.length; x++) {
252 for (var y = 0; y < arr[0].length; y++) {
253 for (var z = 0; z < arr[0][0].length; z++) {
254 dest[adjustedPtr + idx] = arr[x][y][z];
255 idx++;
256 }
257 }
258 }
259 return ptr;
260}
261
Kevin Lubick6bffe392020-04-02 15:24:15 -0400262var defaultPerspective = Float32Array.of(0, 0, 1);
263
264// Copies the given DOMMatrix/Array/TypedArray to the CanvasKit heap and
265// returns a pointer to the memory. This memory is a float* of length 9.
266// If the passed in matrix is null/undefined, we return 0 (nullptr). All calls
267// on the C++ side should check for nullptr where appropriate. It is generally
268// the responsibility of the JS side code to call CanvasKit._free on the
269// allocated memory before returning to the user code.
270function copy3x3MatrixToWasm(matr) {
271 if (!matr) {
272 return nullptr;
273 }
274 var mPtr = CanvasKit._malloc(9 * 4); // 9 matrix scalars, each at 4 bytes.
275 if (matr.length) {
276 // TODO(kjlubick): Downsample a 16 length (4x4 matrix)
277 if (matr.length !== 6 && matr.length !== 9) {
278 throw 'invalid matrix size';
279 }
280 // This should be an array or typed array.
281 // have to divide the pointer by 4 to "cast" it from bytes to float.
282 CanvasKit.HEAPF32.set(matr, mPtr / 4);
283 if (matr.length === 6) {
284 CanvasKit.HEAPF32.set(defaultPerspective, 6 + mPtr / 4);
285 }
286 } else {
Kevin Lubickc1d08982020-04-06 13:52:15 -0400287 // Try as if it's a DOMMatrix. Reminder that DOMMatrix is column-major.
Kevin Lubick6bffe392020-04-02 15:24:15 -0400288 var floats = Float32Array.of(
289 matr.m11, matr.m21, matr.m41,
290 matr.m12, matr.m22, matr.m42,
291 matr.m14, matr.m24, matr.m44);
292 // have to divide the pointer by 4 to "cast" it from bytes to float.
293 CanvasKit.HEAPF32.set(floats, mPtr / 4);
294 }
295 return mPtr;
296}
297
Kevin Lubickc1d08982020-04-06 13:52:15 -0400298function copy4x4MatrixToWasm(matr) {
299 if (!matr) {
300 return nullptr;
301 }
302 var mPtr = CanvasKit._malloc(16 * 4); // 9 matrix scalars, each at 4 bytes.
303 if (matr.length) {
304 if (matr.length !== 16 && matr.length !== 6 && matr.length !== 9) {
305 throw 'invalid matrix size';
306 }
307 if (matr.length === 16) {
308 // This should be an array or typed array.
309 // have to divide the pointer by 4 to "cast" it from bytes to float.
310 CanvasKit.HEAPF32.set(matr, mPtr / 4);
311 } else {
312 // Upscale the row-major 3x3 or 3x2 matrix into a 4x4 row-major matrix
313 // TODO(skbug.com/10108) This will need to change when we convert our
314 // JS 4x4 to be column-major.
315 var floats = Float32Array.of(
316 matr[0], matr[1], 0, matr[2],
317 matr[3], matr[4], 0, matr[5],
318 0, 0, 0, 0,
319 matr[6], matr[7], 0, matr[8]);
320 if (matr.length === 6) {
321 // fix perspective for the 3x2 case (from above, they will be undefined).
322 floats[4*3+0]=0;
323 floats[4*3+1]=0;
324 floats[4*3+3]=1;
325 }
326 CanvasKit.HEAPF32.set(floats, mPtr / 4);
327 }
328 } else {
329 // Try as if it's a DOMMatrix. Reminder that DOMMatrix is column-major.
330 // TODO(skbug.com/10108) use toFloat32Array().
331 var floats = Float32Array.of(
332 matr.m11, matr.m21, matr.m31, matr.m41,
333 matr.m12, matr.m22, matr.m32, matr.m42,
334 matr.m13, matr.m23, matr.m33, matr.m43,
335 matr.m14, matr.m24, matr.m34, matr.m44);
336 // have to divide the pointer by 4 to "cast" it from bytes to float.
337 CanvasKit.HEAPF32.set(floats, mPtr / 4);
338 }
339 return mPtr;
340}
341
342// copies a 4x4 matrix at the given pointer into a JS array.
343function copy4x4MatrixFromWasm(matrPtr) {
344 // read them out into an array. TODO(kjlubick): If we change SkMatrix to be
345 // typedArrays, then we should return a typed array here too.
346 var rv = new Array(16);
347 for (var i = 0; i < 16; i++) {
348 rv[i] = CanvasKit.HEAPF32[matrPtr/4 + i]; // divide by 4 to "cast" to float.
349 }
350 CanvasKit._free(matrPtr);
351 return rv;
352}
353
Nathaniel Nifong1bedbeb2020-05-04 16:46:17 -0400354// copies the four floats at the given pointer in a js Float32Array
355function copyColorFromWasm(colorPtr) {
356 var rv = new Float32Array(4);
357 for (var i = 0; i < 4; i++) {
358 rv[i] = CanvasKit.HEAPF32[colorPtr/4 + i]; // divide by 4 to "cast" to float.
359 }
360 CanvasKit._free(colorPtr);
361 return rv;
362}
363
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500364// Caching the Float32Arrays can save having to reallocate them
365// over and over again.
366var Float32ArrayCache = {};
367
368// Takes a 2D array of commands and puts them into the WASM heap
369// as a 1D array. This allows them to referenced from the C++ code.
370// Returns a 2 element array, with the first item being essentially a
371// pointer to the array and the second item being the length of
372// the new 1D array.
373//
374// Example usage:
375// let cmds = [
376// [CanvasKit.MOVE_VERB, 0, 10],
377// [CanvasKit.LINE_VERB, 30, 40],
378// [CanvasKit.QUAD_VERB, 20, 50, 45, 60],
379// ];
380function loadCmdsTypedArray(arr) {
381 var len = 0;
382 for (var r = 0; r < arr.length; r++) {
383 len += arr[r].length;
384 }
385
386 var ta;
387 if (Float32ArrayCache[len]) {
388 ta = Float32ArrayCache[len];
389 } else {
390 ta = new Float32Array(len);
391 Float32ArrayCache[len] = ta;
392 }
393 // Flatten into a 1d array
394 var i = 0;
395 for (var r = 0; r < arr.length; r++) {
396 for (var c = 0; c < arr[r].length; c++) {
397 var item = arr[r][c];
398 ta[i] = item;
399 i++;
400 }
401 }
402
403 var ptr = copy1dArray(ta, CanvasKit.HEAPF32);
404 return [ptr, len];
405}
Kevin Lubickd3cfbca2019-03-15 15:36:29 -0400406
Kevin Lubickcc13fd32019-04-05 13:00:01 -0400407function saveBytesToFile(bytes, fileName) {
408 if (!isNode) {
409 // https://stackoverflow.com/a/32094834
410 var blob = new Blob([bytes], {type: 'application/octet-stream'});
411 url = window.URL.createObjectURL(blob);
412 var a = document.createElement('a');
413 document.body.appendChild(a);
414 a.href = url;
415 a.download = fileName;
416 a.click();
417 // clean up after because FF might not download it synchronously
418 setTimeout(function() {
419 URL.revokeObjectURL(url);
420 a.remove();
421 }, 50);
422 } else {
423 var fs = require('fs');
424 // https://stackoverflow.com/a/42006750
425 // https://stackoverflow.com/a/47018122
426 fs.writeFile(fileName, new Buffer(bytes), function(err) {
427 if (err) throw err;
428 });
429 }
430}
Kevin Lubickee91c072019-03-29 10:39:52 -0400431/**
432 * Generic helper for dealing with an array of four floats.
433 */
434CanvasKit.FourFloatArrayHelper = function() {
435 this._floats = [];
Kevin Lubickd3cfbca2019-03-15 15:36:29 -0400436 this._ptr = null;
Kevin Lubickee91c072019-03-29 10:39:52 -0400437
438 Object.defineProperty(this, 'length', {
439 enumerable: true,
440 get: function() {
441 return this._floats.length / 4;
442 },
443 });
Kevin Lubickd3cfbca2019-03-15 15:36:29 -0400444}
445
446/**
Kevin Lubickee91c072019-03-29 10:39:52 -0400447 * push the four floats onto the end of the array - if build() has already
448 * been called, the call will return without modifying anything.
Kevin Lubickd3cfbca2019-03-15 15:36:29 -0400449 */
Kevin Lubickee91c072019-03-29 10:39:52 -0400450CanvasKit.FourFloatArrayHelper.prototype.push = function(f1, f2, f3, f4) {
Kevin Lubickd3cfbca2019-03-15 15:36:29 -0400451 if (this._ptr) {
452 SkDebug('Cannot push more points - already built');
453 return;
454 }
Kevin Lubickee91c072019-03-29 10:39:52 -0400455 this._floats.push(f1, f2, f3, f4);
Kevin Lubickd3cfbca2019-03-15 15:36:29 -0400456}
457
Kevin Lubickee91c072019-03-29 10:39:52 -0400458/**
459 * Set the four floats at a given index - if build() has already
460 * been called, the WASM memory will be written to directly.
461 */
462CanvasKit.FourFloatArrayHelper.prototype.set = function(idx, f1, f2, f3, f4) {
463 if (idx < 0 || idx >= this._floats.length/4) {
464 SkDebug('Cannot set index ' + idx + ', it is out of range', this._floats.length/4);
465 return;
466 }
467 idx *= 4;
468 var BYTES_PER_ELEMENT = 4;
469 if (this._ptr) {
470 // convert this._ptr from uint8_t* to SkScalar* by dividing by 4
471 var floatPtr = (this._ptr / BYTES_PER_ELEMENT) + idx;
472 CanvasKit.HEAPF32[floatPtr] = f1;
473 CanvasKit.HEAPF32[floatPtr + 1] = f2;
474 CanvasKit.HEAPF32[floatPtr + 2] = f3;
475 CanvasKit.HEAPF32[floatPtr + 3] = f4;
476 return;
477 }
478 this._floats[idx] = f1;
479 this._floats[idx + 1] = f2;
480 this._floats[idx + 2] = f3;
481 this._floats[idx + 3] = f4;
482}
483
484/**
485 * Copies the float data to the WASM memory and returns a pointer
486 * to that allocated memory. Once build has been called, this
487 * float array cannot be made bigger.
488 */
489CanvasKit.FourFloatArrayHelper.prototype.build = function() {
Kevin Lubickd3cfbca2019-03-15 15:36:29 -0400490 if (this._ptr) {
491 return this._ptr;
492 }
Kevin Lubickee91c072019-03-29 10:39:52 -0400493 this._ptr = copy1dArray(this._floats, CanvasKit.HEAPF32);
Kevin Lubickd3cfbca2019-03-15 15:36:29 -0400494 return this._ptr;
495}
496
Kevin Lubickee91c072019-03-29 10:39:52 -0400497/**
498 * Frees the wasm memory associated with this array. Of note,
499 * the points are not removed, so push/set/build can all
500 * be called to make a newly allocated (possibly bigger)
501 * float array.
502 */
503CanvasKit.FourFloatArrayHelper.prototype.delete = function() {
Kevin Lubickd3cfbca2019-03-15 15:36:29 -0400504 if (this._ptr) {
505 CanvasKit._free(this._ptr);
506 this._ptr = null;
507 }
508}
Kevin Lubickee91c072019-03-29 10:39:52 -0400509
510/**
511 * Generic helper for dealing with an array of unsigned ints.
512 */
513CanvasKit.OneUIntArrayHelper = function() {
514 this._uints = [];
515 this._ptr = null;
516
517 Object.defineProperty(this, 'length', {
518 enumerable: true,
519 get: function() {
520 return this._uints.length;
521 },
522 });
523}
524
525/**
526 * push the unsigned int onto the end of the array - if build() has already
527 * been called, the call will return without modifying anything.
528 */
529CanvasKit.OneUIntArrayHelper.prototype.push = function(u) {
530 if (this._ptr) {
531 SkDebug('Cannot push more points - already built');
532 return;
533 }
534 this._uints.push(u);
535}
536
537/**
538 * Set the uint at a given index - if build() has already
539 * been called, the WASM memory will be written to directly.
540 */
541CanvasKit.OneUIntArrayHelper.prototype.set = function(idx, u) {
542 if (idx < 0 || idx >= this._uints.length) {
543 SkDebug('Cannot set index ' + idx + ', it is out of range', this._uints.length);
544 return;
545 }
546 idx *= 4;
547 var BYTES_PER_ELEMENT = 4;
548 if (this._ptr) {
549 // convert this._ptr from uint8_t* to SkScalar* by dividing by 4
550 var uintPtr = (this._ptr / BYTES_PER_ELEMENT) + idx;
551 CanvasKit.HEAPU32[uintPtr] = u;
552 return;
553 }
554 this._uints[idx] = u;
555}
556
557/**
558 * Copies the uint data to the WASM memory and returns a pointer
559 * to that allocated memory. Once build has been called, this
560 * unit array cannot be made bigger.
561 */
562CanvasKit.OneUIntArrayHelper.prototype.build = function() {
563 if (this._ptr) {
564 return this._ptr;
565 }
566 this._ptr = copy1dArray(this._uints, CanvasKit.HEAPU32);
567 return this._ptr;
568}
569
570/**
571 * Frees the wasm memory associated with this array. Of note,
572 * the points are not removed, so push/set/build can all
573 * be called to make a newly allocated (possibly bigger)
574 * uint array.
575 */
576CanvasKit.OneUIntArrayHelper.prototype.delete = function() {
577 if (this._ptr) {
578 CanvasKit._free(this._ptr);
579 this._ptr = null;
580 }
581}
582
583/**
584 * Helper for building an array of SkRects (which are just structs
585 * of 4 floats).
586 *
587 * It can be more performant to use this helper, as
588 * the C++-side array is only allocated once (on the first call)
589 * to build. Subsequent set() operations operate directly on
590 * the C++-side array, avoiding having to re-allocate (and free)
591 * the array every time.
592 *
593 * Input points are taken as left, top, right, bottom
594 */
595CanvasKit.SkRectBuilder = CanvasKit.FourFloatArrayHelper;
596/**
597 * Helper for building an array of RSXForms (which are just structs
598 * of 4 floats).
599 *
600 * It can be more performant to use this helper, as
601 * the C++-side array is only allocated once (on the first call)
602 * to build. Subsequent set() operations operate directly on
603 * the C++-side array, avoiding having to re-allocate (and free)
604 * the array every time.
605 *
606 * An RSXForm is a compressed form of a rotation+scale matrix.
607 *
608 * [ scos -ssin tx ]
609 * [ ssin scos ty ]
610 * [ 0 0 1 ]
611 *
612 * Input points are taken as scos, ssin, tx, ty
613 */
614CanvasKit.RSXFormBuilder = CanvasKit.FourFloatArrayHelper;
615
616/**
617 * Helper for building an array of SkColor
618 *
619 * It can be more performant to use this helper, as
620 * the C++-side array is only allocated once (on the first call)
621 * to build. Subsequent set() operations operate directly on
622 * the C++-side array, avoiding having to re-allocate (and free)
623 * the array every time.
624 */
625CanvasKit.SkColorBuilder = CanvasKit.OneUIntArrayHelper;
Kevin Lubicke25df6c2019-10-22 09:04:32 -0400626
627/**
628 * Malloc returns a TypedArray backed by the C++ memory of the
629 * given length. It should only be used by advanced users who
630 * can manage memory and initialize values properly. When used
631 * correctly, it can save copying of data between JS and C++.
632 * When used incorrectly, it can lead to memory leaks.
633 *
634 * const ta = CanvasKit.Malloc(Float32Array, 20);
635 * // store data into ta
636 * const cf = CanvasKit.SkColorFilter.MakeMatrix(ta);
637 * // MakeMatrix cleans up the ptr automatically.
638 *
639 * @param {TypedArray} typedArray - constructor for the typedArray.
640 * @param {number} len - number of elements to store.
641 */
642CanvasKit.Malloc = function(typedArray, len) {
643 var byteLen = len * typedArray.BYTES_PER_ELEMENT;
644 var ptr = CanvasKit._malloc(byteLen);
Bryce Thomas1fa54042020-01-14 13:46:30 -0800645 var ta = new typedArray(CanvasKit.HEAPU8.buffer, ptr, len);
Kevin Lubicke25df6c2019-10-22 09:04:32 -0400646 // add a marker that this was allocated in C++ land
647 ta['_ck'] = true;
648 return ta;
649}