• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1// helper JS that could be used anywhere in the glue code
2
3function clamp(c) {
4  return Math.round(Math.max(0, Math.min(c || 0, 255)));
5}
6
7// 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;
14  }
15  // 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;
19}
20
21// 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;
35  }
36  // 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;
41  // back to unsigned int to match SkColor.
42  return (clamp(a) << 24 | color) >>> 0;
43}
44
45function radiansToDegrees(rad) {
46  return (rad / Math.PI) * 180;
47}
48
49function degreesToRadians(deg) {
50  return (deg / 180) * Math.PI;
51}
52
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;}")());
58
59function almostEqual(floata, floatb) {
60  return Math.abs(floata - floatb) < 0.00001;
61}
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
68// ptr can be optionally provided if the memory was already allocated.
69function copy1dArray(arr, dest, ptr) {
70  if (!arr || !arr.length) {
71    return nullptr;
72  }
73  if (!ptr) {
74    ptr = CanvasKit._malloc(arr.length * dest.BYTES_PER_ELEMENT);
75  }
76  // In c++ terms, the WASM heap is a uint8_t*, a long buffer/array of single
77  // byte elements. When we run _malloc, we always get an offset/pointer into
78  // that block of memory.
79  // CanvasKit exposes some different views to make it easier to work with
80  // different types. HEAPF32 for example, exposes it as a float*
81  // However, to make the ptr line up, we have to do some pointer arithmetic.
82  // Concretely, we need to convert ptr to go from an index into a 1-byte-wide
83  // buffer to an index into a 4-byte-wide buffer (in the case of HEAPF32)
84  // and thus we divide ptr by 4.
85  dest.set(arr, ptr / dest.BYTES_PER_ELEMENT);
86  return ptr;
87}
88
89// arr should be a non-jagged 2d JS array (TypedArrays can't be nested
90//     inside themselves.)
91// dest is something like CanvasKit.HEAPF32
92// ptr can be optionally provided if the memory was already allocated.
93function copy2dArray(arr, dest, ptr) {
94  if (!arr || !arr.length) {
95    return nullptr;
96  }
97  if (!ptr) {
98    ptr = CanvasKit._malloc(arr.length * arr[0].length * dest.BYTES_PER_ELEMENT);
99  }
100  var idx = 0;
101  var adjustedPtr = ptr / dest.BYTES_PER_ELEMENT;
102  for (var r = 0; r < arr.length; r++) {
103    for (var c = 0; c < arr[0].length; c++) {
104      dest[adjustedPtr + idx] = arr[r][c];
105      idx++;
106    }
107  }
108  return ptr;
109}
110
111// arr should be a non-jagged 3d JS array (TypedArrays can't be nested
112//     inside themselves.)
113// dest is something like CanvasKit.HEAPF32
114// ptr can be optionally provided if the memory was already allocated.
115function copy3dArray(arr, dest, ptr) {
116  if (!arr || !arr.length || !arr[0].length) {
117    return nullptr;
118  }
119  if (!ptr) {
120    ptr = CanvasKit._malloc(arr.length * arr[0].length * arr[0][0].length * dest.BYTES_PER_ELEMENT);
121  }
122  var idx = 0;
123  var adjustedPtr = ptr / dest.BYTES_PER_ELEMENT;
124  for (var x = 0; x < arr.length; x++) {
125    for (var y = 0; y < arr[0].length; y++) {
126      for (var z = 0; z < arr[0][0].length; z++) {
127        dest[adjustedPtr + idx] = arr[x][y][z];
128        idx++;
129      }
130    }
131  }
132  return ptr;
133}
134
135// Caching the Float32Arrays can save having to reallocate them
136// over and over again.
137var Float32ArrayCache = {};
138
139// Takes a 2D array of commands and puts them into the WASM heap
140// as a 1D array. This allows them to referenced from the C++ code.
141// Returns a 2 element array, with the first item being essentially a
142// pointer to the array and the second item being the length of
143// the new 1D array.
144//
145// Example usage:
146// let cmds = [
147//   [CanvasKit.MOVE_VERB, 0, 10],
148//   [CanvasKit.LINE_VERB, 30, 40],
149//   [CanvasKit.QUAD_VERB, 20, 50, 45, 60],
150// ];
151function loadCmdsTypedArray(arr) {
152  var len = 0;
153  for (var r = 0; r < arr.length; r++) {
154    len += arr[r].length;
155  }
156
157  var ta;
158  if (Float32ArrayCache[len]) {
159    ta = Float32ArrayCache[len];
160  } else {
161    ta = new Float32Array(len);
162    Float32ArrayCache[len] = ta;
163  }
164  // Flatten into a 1d array
165  var i = 0;
166  for (var r = 0; r < arr.length; r++) {
167    for (var c = 0; c < arr[r].length; c++) {
168      var item = arr[r][c];
169      ta[i] = item;
170      i++;
171    }
172  }
173
174  var ptr = copy1dArray(ta, CanvasKit.HEAPF32);
175  return [ptr, len];
176}
177
178function saveBytesToFile(bytes, fileName) {
179  if (!isNode) {
180    // https://stackoverflow.com/a/32094834
181    var blob = new Blob([bytes], {type: 'application/octet-stream'});
182    url = window.URL.createObjectURL(blob);
183    var a = document.createElement('a');
184    document.body.appendChild(a);
185    a.href = url;
186    a.download = fileName;
187    a.click();
188    // clean up after because FF might not download it synchronously
189    setTimeout(function() {
190      URL.revokeObjectURL(url);
191      a.remove();
192    }, 50);
193  } else {
194    var fs = require('fs');
195    // https://stackoverflow.com/a/42006750
196    // https://stackoverflow.com/a/47018122
197    fs.writeFile(fileName, new Buffer(bytes), function(err) {
198      if (err) throw err;
199    });
200  }
201}
202/**
203 * Generic helper for dealing with an array of four floats.
204 */
205CanvasKit.FourFloatArrayHelper = function() {
206  this._floats = [];
207  this._ptr = null;
208
209  Object.defineProperty(this, 'length', {
210    enumerable: true,
211    get: function() {
212      return this._floats.length / 4;
213    },
214  });
215}
216
217/**
218 * push the four floats onto the end of the array - if build() has already
219 * been called, the call will return without modifying anything.
220 */
221CanvasKit.FourFloatArrayHelper.prototype.push = function(f1, f2, f3, f4) {
222  if (this._ptr) {
223    SkDebug('Cannot push more points - already built');
224    return;
225  }
226  this._floats.push(f1, f2, f3, f4);
227}
228
229/**
230 * Set the four floats at a given index - if build() has already
231 * been called, the WASM memory will be written to directly.
232 */
233CanvasKit.FourFloatArrayHelper.prototype.set = function(idx, f1, f2, f3, f4) {
234  if (idx < 0 || idx >= this._floats.length/4) {
235    SkDebug('Cannot set index ' + idx + ', it is out of range', this._floats.length/4);
236    return;
237  }
238  idx *= 4;
239  var BYTES_PER_ELEMENT = 4;
240  if (this._ptr) {
241    // convert this._ptr from uint8_t* to SkScalar* by dividing by 4
242    var floatPtr = (this._ptr / BYTES_PER_ELEMENT) + idx;
243    CanvasKit.HEAPF32[floatPtr]     = f1;
244    CanvasKit.HEAPF32[floatPtr + 1] = f2;
245    CanvasKit.HEAPF32[floatPtr + 2] = f3;
246    CanvasKit.HEAPF32[floatPtr + 3] = f4;
247    return;
248  }
249  this._floats[idx]     = f1;
250  this._floats[idx + 1] = f2;
251  this._floats[idx + 2] = f3;
252  this._floats[idx + 3] = f4;
253}
254
255/**
256 * Copies the float data to the WASM memory and returns a pointer
257 * to that allocated memory. Once build has been called, this
258 * float array cannot be made bigger.
259 */
260CanvasKit.FourFloatArrayHelper.prototype.build = function() {
261  if (this._ptr) {
262    return this._ptr;
263  }
264  this._ptr = copy1dArray(this._floats, CanvasKit.HEAPF32);
265  return this._ptr;
266}
267
268/**
269 * Frees the wasm memory associated with this array. Of note,
270 * the points are not removed, so push/set/build can all
271 * be called to make a newly allocated (possibly bigger)
272 * float array.
273 */
274CanvasKit.FourFloatArrayHelper.prototype.delete = function() {
275  if (this._ptr) {
276    CanvasKit._free(this._ptr);
277    this._ptr = null;
278  }
279}
280
281/**
282 * Generic helper for dealing with an array of unsigned ints.
283 */
284CanvasKit.OneUIntArrayHelper = function() {
285  this._uints = [];
286  this._ptr = null;
287
288  Object.defineProperty(this, 'length', {
289    enumerable: true,
290    get: function() {
291      return this._uints.length;
292    },
293  });
294}
295
296/**
297 * push the unsigned int onto the end of the array - if build() has already
298 * been called, the call will return without modifying anything.
299 */
300CanvasKit.OneUIntArrayHelper.prototype.push = function(u) {
301  if (this._ptr) {
302    SkDebug('Cannot push more points - already built');
303    return;
304  }
305  this._uints.push(u);
306}
307
308/**
309 * Set the uint at a given index - if build() has already
310 * been called, the WASM memory will be written to directly.
311 */
312CanvasKit.OneUIntArrayHelper.prototype.set = function(idx, u) {
313  if (idx < 0 || idx >= this._uints.length) {
314    SkDebug('Cannot set index ' + idx + ', it is out of range', this._uints.length);
315    return;
316  }
317  idx *= 4;
318  var BYTES_PER_ELEMENT = 4;
319  if (this._ptr) {
320    // convert this._ptr from uint8_t* to SkScalar* by dividing by 4
321    var uintPtr = (this._ptr / BYTES_PER_ELEMENT) + idx;
322    CanvasKit.HEAPU32[uintPtr] = u;
323    return;
324  }
325  this._uints[idx] = u;
326}
327
328/**
329 * Copies the uint data to the WASM memory and returns a pointer
330 * to that allocated memory. Once build has been called, this
331 * unit array cannot be made bigger.
332 */
333CanvasKit.OneUIntArrayHelper.prototype.build = function() {
334  if (this._ptr) {
335    return this._ptr;
336  }
337  this._ptr = copy1dArray(this._uints, CanvasKit.HEAPU32);
338  return this._ptr;
339}
340
341/**
342 * Frees the wasm memory associated with this array. Of note,
343 * the points are not removed, so push/set/build can all
344 * be called to make a newly allocated (possibly bigger)
345 * uint array.
346 */
347CanvasKit.OneUIntArrayHelper.prototype.delete = function() {
348  if (this._ptr) {
349    CanvasKit._free(this._ptr);
350    this._ptr = null;
351  }
352}
353
354/**
355 * Helper for building an array of SkRects (which are just structs
356 * of 4 floats).
357 *
358 * It can be more performant to use this helper, as
359 * the C++-side array is only allocated once (on the first call)
360 * to build. Subsequent set() operations operate directly on
361 * the C++-side array, avoiding having to re-allocate (and free)
362 * the array every time.
363 *
364 * Input points are taken as left, top, right, bottom
365 */
366CanvasKit.SkRectBuilder = CanvasKit.FourFloatArrayHelper;
367/**
368 * Helper for building an array of RSXForms (which are just structs
369 * of 4 floats).
370 *
371 * It can be more performant to use this helper, as
372 * the C++-side array is only allocated once (on the first call)
373 * to build. Subsequent set() operations operate directly on
374 * the C++-side array, avoiding having to re-allocate (and free)
375 * the array every time.
376 *
377 *  An RSXForm is a compressed form of a rotation+scale matrix.
378 *
379 *  [ scos    -ssin    tx ]
380 *  [ ssin     scos    ty ]
381 *  [    0        0     1 ]
382 *
383 * Input points are taken as scos, ssin, tx, ty
384 */
385CanvasKit.RSXFormBuilder = CanvasKit.FourFloatArrayHelper;
386
387/**
388 * Helper for building an array of SkColor
389 *
390 * It can be more performant to use this helper, as
391 * the C++-side array is only allocated once (on the first call)
392 * to build. Subsequent set() operations operate directly on
393 * the C++-side array, avoiding having to re-allocate (and free)
394 * the array every time.
395 */
396CanvasKit.SkColorBuilder = CanvasKit.OneUIntArrayHelper;
397