blob: a859cbd84b867920d5393e5c727c2c0dccd1aa79 [file] [log] [blame]
Kevin Lubick217056c2018-09-20 17:39:31 -04001// Adds JS functions to augment the CanvasKit interface.
2// For example, if there is a wrapper around the C++ call or logic to allow
3// chaining, it should go here.
Kevin Lubick1a05fce2018-11-20 12:51:16 -05004
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05005// CanvasKit.onRuntimeInitialized is called after the WASM library has loaded.
6// Anything that modifies an exposed class (e.g. SkPath) should be set
7// after onRuntimeInitialized, otherwise, it can happen outside of that scope.
8CanvasKit.onRuntimeInitialized = function() {
9 // All calls to 'this' need to go in externs.js so closure doesn't minify them away.
Kevin Lubick1a05fce2018-11-20 12:51:16 -050010
Kevin Lubickfa5a1382019-10-09 10:46:14 -040011 // buffer is the underlying ArrayBuffer that is the WASM memory blob.
12 // It was removed from Emscripten proper in https://github.com/emscripten-core/emscripten/pull/8277
13 // but it is convenient to have a reference to, so we add it back in.
14 CanvasKit.buffer = CanvasKit.HEAPU8.buffer;
15
Kevin Lubickf5ea37f2019-02-28 10:06:18 -050016 // Add some helpers for matrices. This is ported from SkMatrix.cpp
17 // to save complexity and overhead of going back and forth between
18 // C++ and JS layers.
19 // I would have liked to use something like DOMMatrix, except it
20 // isn't widely supported (would need polyfills) and it doesn't
21 // have a mapPoints() function (which could maybe be tacked on here).
22 // If DOMMatrix catches on, it would be worth re-considering this usage.
23 CanvasKit.SkMatrix = {};
24 function sdot(a, b, c, d, e, f) {
25 e = e || 0;
26 f = f || 0;
27 return a * b + c * d + e * f;
28 }
29
30 CanvasKit.SkMatrix.identity = function() {
31 return [
32 1, 0, 0,
33 0, 1, 0,
34 0, 0, 1,
35 ];
36 };
37
38 // Return the inverse (if it exists) of this matrix.
39 // Otherwise, return the identity.
40 CanvasKit.SkMatrix.invert = function(m) {
41 var det = m[0]*m[4]*m[8] + m[1]*m[5]*m[6] + m[2]*m[3]*m[7]
42 - m[2]*m[4]*m[6] - m[1]*m[3]*m[8] - m[0]*m[5]*m[7];
43 if (!det) {
44 SkDebug('Warning, uninvertible matrix');
45 return CanvasKit.SkMatrix.identity();
Kevin Lubick1a05fce2018-11-20 12:51:16 -050046 }
Kevin Lubickf5ea37f2019-02-28 10:06:18 -050047 return [
48 (m[4]*m[8] - m[5]*m[7])/det, (m[2]*m[7] - m[1]*m[8])/det, (m[1]*m[5] - m[2]*m[4])/det,
49 (m[5]*m[6] - m[3]*m[8])/det, (m[0]*m[8] - m[2]*m[6])/det, (m[2]*m[3] - m[0]*m[5])/det,
50 (m[3]*m[7] - m[4]*m[6])/det, (m[1]*m[6] - m[0]*m[7])/det, (m[0]*m[4] - m[1]*m[3])/det,
51 ];
52 };
Kevin Lubick1a05fce2018-11-20 12:51:16 -050053
Kevin Lubickf5ea37f2019-02-28 10:06:18 -050054 // Maps the given points according to the passed in matrix.
55 // Results are done in place.
56 // See SkMatrix.h::mapPoints for the docs on the math.
57 CanvasKit.SkMatrix.mapPoints = function(matrix, ptArr) {
58 if (ptArr.length % 2) {
59 throw 'mapPoints requires an even length arr';
Kevin Lubickb9db3902018-11-26 11:47:54 -050060 }
Kevin Lubickf5ea37f2019-02-28 10:06:18 -050061 for (var i = 0; i < ptArr.length; i+=2) {
62 var x = ptArr[i], y = ptArr[i+1];
63 // Gx+Hy+I
64 var denom = matrix[6]*x + matrix[7]*y + matrix[8];
65 // Ax+By+C
66 var xTrans = matrix[0]*x + matrix[1]*y + matrix[2];
67 // Dx+Ey+F
68 var yTrans = matrix[3]*x + matrix[4]*y + matrix[5];
69 ptArr[i] = xTrans/denom;
70 ptArr[i+1] = yTrans/denom;
71 }
72 return ptArr;
73 };
Kevin Lubickb9db3902018-11-26 11:47:54 -050074
Kevin Lubickf5ea37f2019-02-28 10:06:18 -050075 CanvasKit.SkMatrix.multiply = function(m1, m2) {
76 var result = [0,0,0, 0,0,0, 0,0,0];
77 for (var r = 0; r < 3; r++) {
78 for (var c = 0; c < 3; c++) {
79 // m1 and m2 are 1D arrays pretending to be 2D arrays
80 result[3*r + c] = sdot(m1[3*r + 0], m2[3*0 + c],
81 m1[3*r + 1], m2[3*1 + c],
82 m1[3*r + 2], m2[3*2 + c]);
Kevin Lubick1a05fce2018-11-20 12:51:16 -050083 }
Kevin Lubickf5ea37f2019-02-28 10:06:18 -050084 }
85 return result;
86 }
Kevin Lubick1a05fce2018-11-20 12:51:16 -050087
Kevin Lubickf5ea37f2019-02-28 10:06:18 -050088 // Return a matrix representing a rotation by n radians.
89 // px, py optionally say which point the rotation should be around
90 // with the default being (0, 0);
91 CanvasKit.SkMatrix.rotated = function(radians, px, py) {
92 px = px || 0;
93 py = py || 0;
94 var sinV = Math.sin(radians);
95 var cosV = Math.cos(radians);
96 return [
97 cosV, -sinV, sdot( sinV, py, 1 - cosV, px),
98 sinV, cosV, sdot(-sinV, px, 1 - cosV, py),
99 0, 0, 1,
100 ];
101 };
Kevin Lubick217056c2018-09-20 17:39:31 -0400102
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500103 CanvasKit.SkMatrix.scaled = function(sx, sy, px, py) {
104 px = px || 0;
105 py = py || 0;
106 return [
107 sx, 0, px - sx * px,
108 0, sy, py - sy * py,
109 0, 0, 1,
110 ];
111 };
Kevin Lubickda3d8ac2019-01-07 11:08:55 -0500112
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500113 CanvasKit.SkMatrix.skewed = function(kx, ky, px, py) {
114 px = px || 0;
115 py = py || 0;
116 return [
117 1, kx, -kx * px,
118 ky, 1, -ky * py,
119 0, 0, 1,
120 ];
121 };
Alexander Khovansky3e119332018-11-15 02:01:19 +0300122
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500123 CanvasKit.SkMatrix.translated = function(dx, dy) {
124 return [
125 1, 0, dx,
126 0, 1, dy,
127 0, 0, 1,
128 ];
129 };
Kevin Lubick1646e7d2018-12-07 13:03:08 -0500130
Kevin Lubickd3729342019-09-12 11:11:25 -0400131 // An SkColorMatrix is a 4x4 color matrix that transforms the 4 color channels
132 // with a 1x4 matrix that post-translates those 4 channels.
133 // For example, the following is the layout with the scale (S) and post-transform
134 // (PT) items indicated.
135 // RS, 0, 0, 0 | RPT
136 // 0, GS, 0, 0 | GPT
137 // 0, 0, BS, 0 | BPT
138 // 0, 0, 0, AS | APT
139 //
140 // Much of this was hand-transcribed from SkColorMatrix.cpp, because it's easier to
141 // deal with a Float32Array of length 20 than to try to expose the SkColorMatrix object.
142
143 var rScale = 0;
144 var gScale = 6;
145 var bScale = 12;
146 var aScale = 18;
147
148 var rPostTrans = 4;
149 var gPostTrans = 9;
150 var bPostTrans = 14;
151 var aPostTrans = 19;
152
153 CanvasKit.SkColorMatrix = {};
154 CanvasKit.SkColorMatrix.identity = function() {
155 var m = new Float32Array(20);
156 m[rScale] = 1;
157 m[gScale] = 1;
158 m[bScale] = 1;
159 m[aScale] = 1;
160 return m;
161 }
162
163 CanvasKit.SkColorMatrix.scaled = function(rs, gs, bs, as) {
164 var m = new Float32Array(20);
165 m[rScale] = rs;
166 m[gScale] = gs;
167 m[bScale] = bs;
168 m[aScale] = as;
169 return m;
170 }
171
172 var rotateIndices = [
173 [6, 7, 11, 12],
174 [0, 10, 2, 12],
175 [0, 1, 5, 6],
176 ];
177 // axis should be 0, 1, 2 for r, g, b
178 CanvasKit.SkColorMatrix.rotated = function(axis, sine, cosine) {
179 var m = CanvasKit.SkColorMatrix.identity();
180 var indices = rotateIndices[axis];
181 m[indices[0]] = cosine;
182 m[indices[1]] = sine;
183 m[indices[2]] = -sine;
184 m[indices[3]] = cosine;
185 return m;
186 }
187
188 // m is a SkColorMatrix (i.e. a Float32Array), and this sets the 4 "special"
189 // params that will translate the colors after they are multiplied by the 4x4 matrix.
190 CanvasKit.SkColorMatrix.postTranslate = function(m, dr, dg, db, da) {
191 m[rPostTrans] += dr;
192 m[gPostTrans] += dg;
193 m[bPostTrans] += db;
194 m[aPostTrans] += da;
195 return m;
196 }
197
198 // concat returns a new SkColorMatrix that is the result of multiplying outer*inner;
199 CanvasKit.SkColorMatrix.concat = function(outer, inner) {
200 var m = new Float32Array(20);
201 var index = 0;
202 for (var j = 0; j < 20; j += 5) {
203 for (var i = 0; i < 4; i++) {
204 m[index++] = outer[j + 0] * inner[i + 0] +
205 outer[j + 1] * inner[i + 5] +
206 outer[j + 2] * inner[i + 10] +
207 outer[j + 3] * inner[i + 15];
208 }
209 m[index++] = outer[j + 0] * inner[4] +
210 outer[j + 1] * inner[9] +
211 outer[j + 2] * inner[14] +
212 outer[j + 3] * inner[19] +
213 outer[j + 4];
214 }
215
216 return m;
217 }
218
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500219 CanvasKit.SkPath.prototype.addArc = function(oval, startAngle, sweepAngle) {
220 // see arc() for the HTMLCanvas version
221 // note input angles are degrees.
222 this._addArc(oval, startAngle, sweepAngle);
223 return this;
224 };
Kevin Lubick217056c2018-09-20 17:39:31 -0400225
Kevin Lubicke384df42019-08-26 15:48:09 -0400226 CanvasKit.SkPath.prototype.addOval = function(oval, isCCW, startIndex) {
227 if (startIndex === undefined) {
228 startIndex = 1;
229 }
230 this._addOval(oval, !!isCCW, startIndex);
231 return this;
232 };
233
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500234 CanvasKit.SkPath.prototype.addPath = function() {
235 // Takes 1, 2, 7, or 10 required args, where the first arg is always the path.
236 // The last arg is optional and chooses between add or extend mode.
237 // The options for the remaining args are:
238 // - an array of 6 or 9 parameters (perspective is optional)
239 // - the 9 parameters of a full matrix or
240 // the 6 non-perspective params of a matrix.
241 var args = Array.prototype.slice.call(arguments);
242 var path = args[0];
243 var extend = false;
244 if (typeof args[args.length-1] === "boolean") {
245 extend = args.pop();
246 }
247 if (args.length === 1) {
248 // Add path, unchanged. Use identity matrix
249 this._addPath(path, 1, 0, 0,
250 0, 1, 0,
251 0, 0, 1,
252 extend);
253 } else if (args.length === 2) {
254 // User provided the 9 params of a full matrix as an array.
255 var a = args[1];
256 this._addPath(path, a[0], a[1], a[2],
257 a[3], a[4], a[5],
258 a[6] || 0, a[7] || 0, a[8] || 1,
259 extend);
260 } else if (args.length === 7 || args.length === 10) {
261 // User provided the 9 params of a (full) matrix directly.
262 // (or just the 6 non perspective ones)
263 // These are in the same order as what Skia expects.
264 var a = args;
265 this._addPath(path, a[1], a[2], a[3],
266 a[4], a[5], a[6],
267 a[7] || 0, a[8] || 0, a[9] || 1,
268 extend);
269 } else {
270 SkDebug('addPath expected to take 1, 2, 7, or 10 required args. Got ' + args.length);
Kevin Lubickb5ae3b52018-11-03 07:51:19 -0400271 return null;
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500272 }
273 return this;
274 };
Kevin Lubickb5ae3b52018-11-03 07:51:19 -0400275
Kevin Lubick37ab53e2019-11-11 10:06:08 -0500276 // points is either an array of [x, y] where x and y are numbers or
277 // a typed array from Malloc where the even indices will be treated
278 // as x coordinates and the odd indices will be treated as y coordinates.
279 CanvasKit.SkPath.prototype.addPoly = function(points, close) {
280 var ptr;
281 var n;
282 // This was created with CanvasKit.Malloc, so assume the user has
283 // already been filled with data.
284 if (points['_ck']) {
285 ptr = points.byteOffset;
286 n = points.length/2;
287 } else {
288 ptr = copy2dArray(points, CanvasKit.HEAPF32);
289 n = points.length;
290 }
291 this._addPoly(ptr, n, close);
292 CanvasKit._free(ptr);
293 return this;
294 };
295
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500296 CanvasKit.SkPath.prototype.addRect = function() {
297 // Takes 1, 2, 4 or 5 args
298 // - SkRect
299 // - SkRect, isCCW
300 // - left, top, right, bottom
301 // - left, top, right, bottom, isCCW
302 if (arguments.length === 1 || arguments.length === 2) {
303 var r = arguments[0];
304 var ccw = arguments[1] || false;
305 this._addRect(r.fLeft, r.fTop, r.fRight, r.fBottom, ccw);
306 } else if (arguments.length === 4 || arguments.length === 5) {
307 var a = arguments;
308 this._addRect(a[0], a[1], a[2], a[3], a[4] || false);
309 } else {
310 SkDebug('addRect expected to take 1, 2, 4, or 5 args. Got ' + arguments.length);
Kevin Lubick217056c2018-09-20 17:39:31 -0400311 return null;
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500312 }
313 return this;
314 };
Kevin Lubick217056c2018-09-20 17:39:31 -0400315
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500316 CanvasKit.SkPath.prototype.addRoundRect = function() {
317 // Takes 3, 4, 6 or 7 args
318 // - SkRect, radii, ccw
319 // - SkRect, rx, ry, ccw
320 // - left, top, right, bottom, radii, ccw
321 // - left, top, right, bottom, rx, ry, ccw
322 var args = arguments;
323 if (args.length === 3 || args.length === 6) {
324 var radii = args[args.length-2];
325 } else if (args.length === 6 || args.length === 7){
326 // duplicate the given (rx, ry) pairs for each corner.
327 var rx = args[args.length-3];
328 var ry = args[args.length-2];
329 var radii = [rx, ry, rx, ry, rx, ry, rx, ry];
330 } else {
331 SkDebug('addRoundRect expected to take 3, 4, 6, or 7 args. Got ' + args.length);
332 return null;
333 }
334 if (radii.length !== 8) {
335 SkDebug('addRoundRect needs 8 radii provided. Got ' + radii.length);
336 return null;
337 }
338 var rptr = copy1dArray(radii, CanvasKit.HEAPF32);
339 if (args.length === 3 || args.length === 4) {
340 var r = args[0];
341 var ccw = args[args.length - 1];
342 this._addRoundRect(r.fLeft, r.fTop, r.fRight, r.fBottom, rptr, ccw);
343 } else if (args.length === 6 || args.length === 7) {
344 var a = args;
345 this._addRoundRect(a[0], a[1], a[2], a[3], rptr, ccw);
346 }
347 CanvasKit._free(rptr);
348 return this;
349 };
350
351 CanvasKit.SkPath.prototype.arc = function(x, y, radius, startAngle, endAngle, ccw) {
352 // emulates the HTMLCanvas behavior. See addArc() for the SkPath version.
353 // Note input angles are radians.
354 var bounds = CanvasKit.LTRBRect(x-radius, y-radius, x+radius, y+radius);
355 var sweep = radiansToDegrees(endAngle - startAngle) - (360 * !!ccw);
356 var temp = new CanvasKit.SkPath();
357 temp.addArc(bounds, radiansToDegrees(startAngle), sweep);
358 this.addPath(temp, true);
359 temp.delete();
360 return this;
361 };
362
363 CanvasKit.SkPath.prototype.arcTo = function() {
364 // takes 4, 5 or 7 args
365 // - 5 x1, y1, x2, y2, radius
366 // - 4 oval (as Rect), startAngle, sweepAngle, forceMoveTo
Kevin Lubicke384df42019-08-26 15:48:09 -0400367 // - 7 rx, ry, xAxisRotate, useSmallArc, isCCW, x, y
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500368 var args = arguments;
369 if (args.length === 5) {
370 this._arcTo(args[0], args[1], args[2], args[3], args[4]);
371 } else if (args.length === 4) {
372 this._arcTo(args[0], args[1], args[2], args[3]);
373 } else if (args.length === 7) {
Kevin Lubicke384df42019-08-26 15:48:09 -0400374 this._arcTo(args[0], args[1], args[2], !!args[3], !!args[4], args[5], args[6]);
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500375 } else {
376 throw 'Invalid args for arcTo. Expected 4, 5, or 7, got '+ args.length;
377 }
378
379 return this;
380 };
381
382 CanvasKit.SkPath.prototype.close = function() {
383 this._close();
384 return this;
385 };
386
387 CanvasKit.SkPath.prototype.conicTo = function(x1, y1, x2, y2, w) {
388 this._conicTo(x1, y1, x2, y2, w);
389 return this;
390 };
391
392 CanvasKit.SkPath.prototype.cubicTo = function(cp1x, cp1y, cp2x, cp2y, x, y) {
393 this._cubicTo(cp1x, cp1y, cp2x, cp2y, x, y);
394 return this;
395 };
396
397 CanvasKit.SkPath.prototype.dash = function(on, off, phase) {
398 if (this._dash(on, off, phase)) {
Kevin Lubick217056c2018-09-20 17:39:31 -0400399 return this;
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500400 }
401 return null;
402 };
Kevin Lubick217056c2018-09-20 17:39:31 -0400403
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500404 CanvasKit.SkPath.prototype.lineTo = function(x, y) {
405 this._lineTo(x, y);
406 return this;
407 };
Kevin Lubick217056c2018-09-20 17:39:31 -0400408
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500409 CanvasKit.SkPath.prototype.moveTo = function(x, y) {
410 this._moveTo(x, y);
411 return this;
412 };
Kevin Lubickb5ae3b52018-11-03 07:51:19 -0400413
Kevin Lubicke384df42019-08-26 15:48:09 -0400414 CanvasKit.SkPath.prototype.offset = function(dx, dy) {
415 this._transform(1, 0, dx,
416 0, 1, dy,
417 0, 0, 1);
418 return this;
419 };
420
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500421 CanvasKit.SkPath.prototype.op = function(otherPath, op) {
422 if (this._op(otherPath, op)) {
Kevin Lubick217056c2018-09-20 17:39:31 -0400423 return this;
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500424 }
425 return null;
426 };
Kevin Lubickb5ae3b52018-11-03 07:51:19 -0400427
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500428 CanvasKit.SkPath.prototype.quadTo = function(cpx, cpy, x, y) {
429 this._quadTo(cpx, cpy, x, y);
430 return this;
431 };
432
Kevin Lubick79b71342019-11-01 14:36:52 -0400433 CanvasKit.SkPath.prototype.rArcTo = function(rx, ry, xAxisRotate, useSmallArc, isCCW, dx, dy) {
434 this._rArcTo(rx, ry, xAxisRotate, useSmallArc, isCCW, dx, dy);
435 return this;
436 };
437
438 CanvasKit.SkPath.prototype.rConicTo = function(dx1, dy1, dx2, dy2, w) {
439 this._rConicTo(dx1, dy1, dx2, dy2, w);
440 return this;
441 };
442
443 // These params are all relative
444 CanvasKit.SkPath.prototype.rCubicTo = function(cp1x, cp1y, cp2x, cp2y, x, y) {
445 this._rCubicTo(cp1x, cp1y, cp2x, cp2y, x, y);
446 return this;
447 };
448
449 CanvasKit.SkPath.prototype.rLineTo = function(dx, dy) {
450 this._rLineTo(dx, dy);
451 return this;
452 };
453
454 CanvasKit.SkPath.prototype.rMoveTo = function(dx, dy) {
455 this._rMoveTo(dx, dy);
456 return this;
457 };
458
459 // These params are all relative
460 CanvasKit.SkPath.prototype.rQuadTo = function(cpx, cpy, x, y) {
461 this._rQuadTo(cpx, cpy, x, y);
462 return this;
463 };
464
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500465 CanvasKit.SkPath.prototype.simplify = function() {
466 if (this._simplify()) {
467 return this;
468 }
469 return null;
470 };
471
472 CanvasKit.SkPath.prototype.stroke = function(opts) {
473 // Fill out any missing values with the default values.
474 /**
475 * See externs.js for this definition
476 * @type {StrokeOpts}
477 */
478 opts = opts || {};
479 opts.width = opts.width || 1;
480 opts.miter_limit = opts.miter_limit || 4;
481 opts.cap = opts.cap || CanvasKit.StrokeCap.Butt;
482 opts.join = opts.join || CanvasKit.StrokeJoin.Miter;
483 opts.precision = opts.precision || 1;
484 if (this._stroke(opts)) {
485 return this;
486 }
487 return null;
488 };
489
490 CanvasKit.SkPath.prototype.transform = function() {
491 // Takes 1 or 9 args
492 if (arguments.length === 1) {
493 // argument 1 should be a 6 or 9 element array.
494 var a = arguments[0];
495 this._transform(a[0], a[1], a[2],
496 a[3], a[4], a[5],
497 a[6] || 0, a[7] || 0, a[8] || 1);
498 } else if (arguments.length === 6 || arguments.length === 9) {
499 // these arguments are the 6 or 9 members of the matrix
500 var a = arguments;
501 this._transform(a[0], a[1], a[2],
502 a[3], a[4], a[5],
503 a[6] || 0, a[7] || 0, a[8] || 1);
504 } else {
505 throw 'transform expected to take 1 or 9 arguments. Got ' + arguments.length;
506 }
507 return this;
508 };
509 // isComplement is optional, defaults to false
510 CanvasKit.SkPath.prototype.trim = function(startT, stopT, isComplement) {
511 if (this._trim(startT, stopT, !!isComplement)) {
512 return this;
513 }
514 return null;
515 };
516
517 // bones should be a 3d array.
518 // Each bone is a 3x2 transformation matrix in column major order:
519 // | scaleX skewX transX |
520 // | skewY scaleY transY |
521 // and bones is an array of those matrices.
522 // Returns a copy of this (SkVertices) with the bones applied.
523 CanvasKit.SkVertices.prototype.applyBones = function(bones) {
524 var bPtr = copy3dArray(bones, CanvasKit.HEAPF32);
525 var vert = this._applyBones(bPtr, bones.length);
526 CanvasKit._free(bPtr);
527 return vert;
528 }
529
530 CanvasKit.SkImage.prototype.encodeToData = function() {
531 if (!arguments.length) {
532 return this._encodeToData();
Kevin Lubickb5ae3b52018-11-03 07:51:19 -0400533 }
Kevin Lubick53965c92018-10-11 08:51:55 -0400534
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500535 if (arguments.length === 2) {
536 var a = arguments;
537 return this._encodeToDataWithFormat(a[0], a[1]);
Alexander Khovansky3e119332018-11-15 02:01:19 +0300538 }
539
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500540 throw 'encodeToData expected to take 0 or 2 arguments. Got ' + arguments.length;
541 }
Kevin Lubick1ba9c4d2019-02-22 10:04:06 -0500542
Kevin Lubicka064c282019-04-04 09:28:53 -0400543 CanvasKit.SkImage.prototype.makeShader = function(xTileMode, yTileMode, localMatrix) {
544 if (localMatrix) {
545 // Add perspective args if not provided.
546 if (localMatrix.length === 6) {
547 localMatrix.push(0, 0, 1);
548 }
549 return this._makeShader(xTileMode, yTileMode, localMatrix);
550 } else {
551 return this._makeShader(xTileMode, yTileMode);
552 }
553 }
554
Kevin Lubickd6b32ed2019-05-06 13:04:03 -0400555 CanvasKit.SkImage.prototype.readPixels = function(imageInfo, srcX, srcY) {
556 var rowBytes;
557 switch (imageInfo.colorType){
558 case CanvasKit.ColorType.RGBA_8888:
559 rowBytes = imageInfo.width * 4; // 1 byte per channel == 4 bytes per pixel in 8888
560 break;
561 case CanvasKit.ColorType.RGBA_F32:
562 rowBytes = imageInfo.width * 16; // 4 bytes per channel == 16 bytes per pixel in F32
563 break;
564 default:
565 SkDebug("Colortype not yet supported");
566 return;
567 }
568 var pBytes = rowBytes * imageInfo.height;
569 var pPtr = CanvasKit._malloc(pBytes);
570
571 if (!this._readPixels(imageInfo, pPtr, rowBytes, srcX, srcY)) {
572 SkDebug("Could not read pixels with the given inputs");
573 return null;
574 }
575
576 // Put those pixels into a typed array of the right format and then
577 // make a copy with slice() that we can return.
578 var retVal = null;
579 switch (imageInfo.colorType){
580 case CanvasKit.ColorType.RGBA_8888:
581 retVal = new Uint8Array(CanvasKit.buffer, pPtr, pBytes).slice();
582 break;
583 case CanvasKit.ColorType.RGBA_F32:
584 retVal = new Float32Array(CanvasKit.buffer, pPtr, pBytes).slice();
585 break;
586 }
587
588 // Free the allocated pixels in the WASM memory
589 CanvasKit._free(pPtr);
590 return retVal;
591
592 }
593
Kevin Lubickee91c072019-03-29 10:39:52 -0400594 // atlas is an SkImage, e.g. from CanvasKit.MakeImageFromEncoded
595 // srcRects and dstXforms should be CanvasKit.SkRectBuilder and CanvasKit.RSXFormBuilder
596 // or just arrays of floats in groups of 4.
597 // colors, if provided, should be a CanvasKit.SkColorBuilder or array of SkColor
598 // (from CanvasKit.Color)
599 CanvasKit.SkCanvas.prototype.drawAtlas = function(atlas, srcRects, dstXforms, paint,
600 /*optional*/ blendMode, colors) {
601 if (!atlas || !paint || !srcRects || !dstXforms) {
602 SkDebug('Doing nothing since missing a required input');
603 return;
604 }
605 if (srcRects.length !== dstXforms.length || (colors && colors.length !== dstXforms.length)) {
606 SkDebug('Doing nothing since input arrays length mismatches');
607 }
608 if (!blendMode) {
609 blendMode = CanvasKit.BlendMode.SrcOver;
610 }
611
612 var srcRectPtr;
613 if (srcRects.build) {
614 srcRectPtr = srcRects.build();
615 } else {
616 srcRectPtr = copy1dArray(srcRects, CanvasKit.HEAPF32);
617 }
618
619 var dstXformPtr;
620 if (dstXforms.build) {
621 dstXformPtr = dstXforms.build();
622 } else {
623 dstXformPtr = copy1dArray(dstXforms, CanvasKit.HEAPF32);
624 }
625
626 var colorPtr = 0; // enscriptem doesn't like undefined for nullptr
627 if (colors) {
628 if (colors.build) {
629 colorPtr = colors.build();
630 } else {
631 colorPtr = copy1dArray(colors, CanvasKit.HEAPU32);
632 }
633 }
634
635 this._drawAtlas(atlas, dstXformPtr, srcRectPtr, colorPtr, dstXforms.length,
636 blendMode, paint);
637
638 if (srcRectPtr && !srcRects.build) {
639 CanvasKit._free(srcRectPtr);
640 }
641 if (dstXformPtr && !dstXforms.build) {
642 CanvasKit._free(dstXformPtr);
643 }
644 if (colorPtr && !colors.build) {
645 CanvasKit._free(colorPtr);
646 }
647
648 }
649
Kevin Lubick37ab53e2019-11-11 10:06:08 -0500650 // points is either an array of [x, y] where x and y are numbers or
651 // a typed array from Malloc where the even indices will be treated
652 // as x coordinates and the odd indices will be treated as y coordinates.
653 CanvasKit.SkCanvas.prototype.drawPoints = function(mode, points, paint) {
654 var ptr;
655 var n;
656 // This was created with CanvasKit.Malloc, so assume the user has
657 // already been filled with data.
658 if (points['_ck']) {
659 ptr = points.byteOffset;
660 n = points.length/2;
661 } else {
662 ptr = copy2dArray(points, CanvasKit.HEAPF32);
663 n = points.length;
664 }
665 this._drawPoints(mode, ptr, n, paint);
666 CanvasKit._free(ptr);
667 }
668
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500669 // str can be either a text string or a ShapedText object
670 CanvasKit.SkCanvas.prototype.drawText = function(str, x, y, paint, font) {
671 if (typeof str === 'string') {
Kevin Lubickec4903d2019-01-14 08:36:08 -0500672 // lengthBytesUTF8 and stringToUTF8Array are defined in the emscripten
673 // JS. See https://kripken.github.io/emscripten-site/docs/api_reference/preamble.js.html#stringToUTF8
Kevin Lubick16d998f2019-09-26 13:25:26 -0400674 var strLen = lengthBytesUTF8(str);
675 // Add 1 for null terminator, which we need when copying/converting, but can ignore
676 // when we call into Skia.
677 var strPtr = CanvasKit._malloc(strLen + 1);
678 stringToUTF8(str, strPtr, strLen + 1);
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500679 this._drawSimpleText(strPtr, strLen, x, y, font, paint);
Kevin Lubickda3d8ac2019-01-07 11:08:55 -0500680 } else {
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500681 this._drawShapedText(str, x, y, paint);
Kevin Lubickd29edd72018-12-07 08:29:52 -0500682 }
Kevin Lubickb5ae3b52018-11-03 07:51:19 -0400683 }
684
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500685 // returns Uint8Array
686 CanvasKit.SkCanvas.prototype.readPixels = function(x, y, w, h, alphaType,
687 colorType, dstRowBytes) {
688 // supply defaults (which are compatible with HTMLCanvas's getImageData)
689 alphaType = alphaType || CanvasKit.AlphaType.Unpremul;
690 colorType = colorType || CanvasKit.ColorType.RGBA_8888;
691 dstRowBytes = dstRowBytes || (4 * w);
692
693 var len = h * dstRowBytes
694 var pptr = CanvasKit._malloc(len);
695 var ok = this._readPixels({
696 'width': w,
697 'height': h,
Kevin Lubick52b9f372018-12-04 13:57:36 -0500698 'colorType': colorType,
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500699 'alphaType': alphaType,
700 }, pptr, dstRowBytes, x, y);
701 if (!ok) {
702 CanvasKit._free(pptr);
703 return null;
704 }
705
706 // The first typed array is just a view into memory. Because we will
707 // be free-ing that, we call slice to make a persistent copy.
Kevin Lubickfa5a1382019-10-09 10:46:14 -0400708 var pixels = new Uint8Array(CanvasKit.buffer, pptr, len).slice();
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500709 CanvasKit._free(pptr);
710 return pixels;
711 }
712
713 // pixels is a TypedArray. No matter the input size, it will be treated as
714 // a Uint8Array (essentially, a byte array).
715 CanvasKit.SkCanvas.prototype.writePixels = function(pixels, srcWidth, srcHeight,
716 destX, destY, alphaType, colorType) {
717 if (pixels.byteLength % (srcWidth * srcHeight)) {
718 throw 'pixels length must be a multiple of the srcWidth * srcHeight';
719 }
720 var bytesPerPixel = pixels.byteLength / (srcWidth * srcHeight);
721 // supply defaults (which are compatible with HTMLCanvas's putImageData)
722 alphaType = alphaType || CanvasKit.AlphaType.Unpremul;
723 colorType = colorType || CanvasKit.ColorType.RGBA_8888;
724 var srcRowBytes = bytesPerPixel * srcWidth;
725
Kevin Lubick52b9f372018-12-04 13:57:36 -0500726 var pptr = CanvasKit._malloc(pixels.byteLength);
727 CanvasKit.HEAPU8.set(pixels, pptr);
Kevin Lubick52b9f372018-12-04 13:57:36 -0500728
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500729 var ok = this._writePixels({
730 'width': srcWidth,
731 'height': srcHeight,
732 'colorType': colorType,
733 'alphaType': alphaType,
734 }, pptr, srcRowBytes, destX, destY);
735
736 CanvasKit._free(pptr);
737 return ok;
Kevin Lubick52b9f372018-12-04 13:57:36 -0500738 }
739
Kevin Lubickd3729342019-09-12 11:11:25 -0400740 // colorMatrix is an SkColorMatrix (e.g. Float32Array of length 20)
741 CanvasKit.SkColorFilter.MakeMatrix = function(colorMatrix) {
742 if (!colorMatrix || colorMatrix.length !== 20) {
743 SkDebug('ignoring invalid color matrix');
744 return;
745 }
746 var fptr = copy1dArray(colorMatrix, CanvasKit.HEAPF32);
747 // We know skia memcopies the floats, so we can free our memory after the call returns.
748 var m = CanvasKit.SkColorFilter._makeMatrix(fptr);
749 CanvasKit._free(fptr);
750 return m;
751 }
752
Kevin Lubickd3cfbca2019-03-15 15:36:29 -0400753 // Returns an array of the widths of the glyphs in this string.
754 CanvasKit.SkFont.prototype.getWidths = function(str) {
755 // add 1 for null terminator
756 var codePoints = str.length + 1;
757 // lengthBytesUTF8 and stringToUTF8Array are defined in the emscripten
758 // JS. See https://kripken.github.io/emscripten-site/docs/api_reference/preamble.js.html#stringToUTF8
759 // Add 1 for null terminator
760 var strBytes = lengthBytesUTF8(str) + 1;
761 var strPtr = CanvasKit._malloc(strBytes);
762 stringToUTF8(str, strPtr, strBytes);
763
764 var bytesPerFloat = 4;
765 // allocate widths == numCodePoints
766 var widthPtr = CanvasKit._malloc(codePoints * bytesPerFloat);
767 if (!this._getWidths(strPtr, strBytes, codePoints, widthPtr)) {
768 SkDebug('Could not compute widths');
769 CanvasKit._free(strPtr);
770 CanvasKit._free(widthPtr);
771 return null;
772 }
773 // reminder, this shouldn't copy the data, just is a nice way to
774 // wrap 4 bytes together into a float.
775 var widths = new Float32Array(CanvasKit.buffer, widthPtr, codePoints);
776 // This copies the data so we can free the CanvasKit memory
777 var retVal = Array.from(widths);
778 CanvasKit._free(strPtr);
779 CanvasKit._free(widthPtr);
780 return retVal;
781 }
782
Kevin Lubick369f6a52019-10-03 11:22:08 -0400783 // arguments should all be arrayBuffers or be an array of arrayBuffers.
Kevin Lubick61887c72019-09-26 13:20:50 -0400784 CanvasKit.SkFontMgr.FromData = function() {
785 if (!arguments.length) {
786 SkDebug('Could not make SkFontMgr from no font sources');
787 return null;
788 }
789 var fonts = arguments;
Kevin Lubick369f6a52019-10-03 11:22:08 -0400790 if (fonts.length === 1 && Array.isArray(fonts[0])) {
Kevin Lubick61887c72019-09-26 13:20:50 -0400791 fonts = arguments[0];
792 }
793 if (!fonts.length) {
794 SkDebug('Could not make SkFontMgr from no font sources');
795 return null;
796 }
797 var dPtrs = [];
798 var sizes = [];
799 for (var i = 0; i < fonts.length; i++) {
800 var data = new Uint8Array(fonts[i]);
801 var dptr = copy1dArray(data, CanvasKit.HEAPU8);
802 dPtrs.push(dptr);
803 sizes.push(data.byteLength);
804 }
805 // Pointers are 32 bit unsigned ints
806 var datasPtr = copy1dArray(dPtrs, CanvasKit.HEAPU32);
807 var sizesPtr = copy1dArray(sizes, CanvasKit.HEAPU32);
808 var fm = CanvasKit.SkFontMgr._fromData(datasPtr, sizesPtr, fonts.length);
809 // The SkFontMgr has taken ownership of the bytes we allocated in the for loop.
810 CanvasKit._free(datasPtr);
811 CanvasKit._free(sizesPtr);
812 return fm;
813 }
814
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500815 // fontData should be an arrayBuffer
816 CanvasKit.SkFontMgr.prototype.MakeTypefaceFromData = function(fontData) {
817 var data = new Uint8Array(fontData);
Kevin Lubickb5ae3b52018-11-03 07:51:19 -0400818
Kevin Lubick61887c72019-09-26 13:20:50 -0400819 var fptr = copy1dArray(data, CanvasKit.HEAPU8);
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500820 var font = this._makeTypefaceFromData(fptr, data.byteLength);
821 if (!font) {
822 SkDebug('Could not decode font data');
823 // We do not need to free the data since the C++ will do that for us
824 // when the font is deleted (or fails to decode);
825 return null;
826 }
827 return font;
828 }
829
Kevin Lubickcc13fd32019-04-05 13:00:01 -0400830 // The serialized format of an SkPicture (informally called an "skp"), is not something
831 // that clients should ever rely on. It is useful when filing bug reports, but that's
832 // about it. The format may change at anytime and no promises are made for backwards
833 // or forward compatibility.
834 CanvasKit.SkPicture.prototype.DEBUGONLY_saveAsFile = function(skpName) {
835 var data = this.DEBUGONLY_serialize();
836 if (!data) {
837 SkDebug('Could not serialize to skpicture.');
838 return;
839 }
840 var bytes = CanvasKit.getSkDataBytes(data);
841 saveBytesToFile(bytes, skpName);
842 data.delete();
843 }
844
845 CanvasKit.SkSurface.prototype.captureFrameAsSkPicture = function(drawFrame) {
846 // Set up SkPictureRecorder
847 var spr = new CanvasKit.SkPictureRecorder();
848 var canvas = spr.beginRecording(
849 CanvasKit.LTRBRect(0, 0, this.width(), this.height()));
850 drawFrame(canvas);
851 var pic = spr.finishRecordingAsPicture();
852 spr.delete();
853 // TODO: do we need to clean up the memory for canvas?
854 // If we delete it here, saveAsFile doesn't work correctly.
855 return pic;
856 }
857
Kevin Lubick359a7e32019-03-19 09:34:37 -0400858 CanvasKit.SkSurface.prototype.requestAnimationFrame = function(callback, dirtyRect) {
859 if (!this._cached_canvas) {
860 this._cached_canvas = this.getCanvas();
861 }
862 window.requestAnimationFrame(function() {
Kevin Lubick39026282019-03-28 12:46:40 -0400863 if (this._context !== undefined) {
864 CanvasKit.setCurrentContext(this._context);
865 }
Kevin Lubick359a7e32019-03-19 09:34:37 -0400866
867 callback(this._cached_canvas);
868
869 this.flush();
870 }.bind(this));
871 }
872
Kevin Lubickd3cfbca2019-03-15 15:36:29 -0400873 CanvasKit.SkTextBlob.MakeOnPath = function(str, path, font, initialOffset) {
874 if (!str || !str.length) {
875 SkDebug('ignoring 0 length string');
876 return;
877 }
878 if (!path || !path.countPoints()) {
879 SkDebug('ignoring empty path');
880 return;
881 }
882 if (path.countPoints() === 1) {
883 SkDebug('path has 1 point, returning normal textblob');
884 return this.MakeFromText(str, font);
885 }
886
887 if (!initialOffset) {
888 initialOffset = 0;
889 }
890
891 var widths = font.getWidths(str);
892
893 var rsx = new CanvasKit.RSXFormBuilder();
894 var meas = new CanvasKit.SkPathMeasure(path, false, 1);
895 var dist = initialOffset;
896 for (var i = 0; i < str.length; i++) {
897 var width = widths[i];
898 dist += width/2;
899 if (dist > meas.getLength()) {
900 // jump to next contour
901 if (!meas.nextContour()) {
902 // We have come to the end of the path - terminate the string
903 // right here.
904 str = str.substring(0, i);
905 break;
906 }
907 dist = width/2;
908 }
909
910 // Gives us the (x, y) coordinates as well as the cos/sin of the tangent
911 // line at that position.
912 var xycs = meas.getPosTan(dist);
913 var cx = xycs[0];
914 var cy = xycs[1];
915 var cosT = xycs[2];
916 var sinT = xycs[3];
917
918 var adjustedX = cx - (width/2 * cosT);
919 var adjustedY = cy - (width/2 * sinT);
920
921 rsx.push(cosT, sinT, adjustedX, adjustedY);
922 dist += width/2;
923 }
924 var retVal = this.MakeFromRSXform(str, rsx, font);
925 rsx.delete();
926 meas.delete();
927 return retVal;
928 }
929
930 CanvasKit.SkTextBlob.MakeFromRSXform = function(str, rsxBuilder, font) {
931 // lengthBytesUTF8 and stringToUTF8Array are defined in the emscripten
932 // JS. See https://kripken.github.io/emscripten-site/docs/api_reference/preamble.js.html#stringToUTF8
933 // Add 1 for null terminator
934 var strLen = lengthBytesUTF8(str) + 1;
935 var strPtr = CanvasKit._malloc(strLen);
936 // Add 1 for the null terminator.
937 stringToUTF8(str, strPtr, strLen);
938 var rptr = rsxBuilder.build();
939
940 var blob = CanvasKit.SkTextBlob._MakeFromRSXform(strPtr, strLen - 1,
941 rptr, font, CanvasKit.TextEncoding.UTF8);
942 if (!blob) {
943 SkDebug('Could not make textblob from string "' + str + '"');
944 return null;
945 }
946
947 var origDelete = blob.delete.bind(blob);
948 blob.delete = function() {
949 CanvasKit._free(strPtr);
950 origDelete();
951 }
952 return blob;
953 }
954
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500955 CanvasKit.SkTextBlob.MakeFromText = function(str, font) {
956 // lengthBytesUTF8 and stringToUTF8Array are defined in the emscripten
957 // JS. See https://kripken.github.io/emscripten-site/docs/api_reference/preamble.js.html#stringToUTF8
958 // Add 1 for null terminator
959 var strLen = lengthBytesUTF8(str) + 1;
960 var strPtr = CanvasKit._malloc(strLen);
961 // Add 1 for the null terminator.
962 stringToUTF8(str, strPtr, strLen);
963
964 var blob = CanvasKit.SkTextBlob._MakeFromText(strPtr, strLen - 1, font, CanvasKit.TextEncoding.UTF8);
965 if (!blob) {
966 SkDebug('Could not make textblob from string "' + str + '"');
967 return null;
Kevin Lubick217056c2018-09-20 17:39:31 -0400968 }
Kevin Lubickb5ae3b52018-11-03 07:51:19 -0400969
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500970 var origDelete = blob.delete.bind(blob);
971 blob.delete = function() {
972 CanvasKit._free(strPtr);
973 origDelete();
Kevin Lubickb5ae3b52018-11-03 07:51:19 -0400974 }
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500975 return blob;
Kevin Lubickb5ae3b52018-11-03 07:51:19 -0400976 }
977
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500978 // Run through the JS files that are added at compile time.
979 if (CanvasKit._extraInitializations) {
980 CanvasKit._extraInitializations.forEach(function(init) {
981 init();
982 });
Kevin Lubickeb2f6b02018-11-29 15:07:02 -0500983 }
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500984}; // end CanvasKit.onRuntimeInitialized, that is, anything changing prototypes or dynamic.
Kevin Lubickeb2f6b02018-11-29 15:07:02 -0500985
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500986CanvasKit.LTRBRect = function(l, t, r, b) {
987 return {
988 fLeft: l,
989 fTop: t,
990 fRight: r,
991 fBottom: b,
992 };
Kevin Lubick1a05fce2018-11-20 12:51:16 -0500993}
994
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500995CanvasKit.XYWHRect = function(x, y, w, h) {
996 return {
997 fLeft: x,
998 fTop: y,
999 fRight: x+w,
1000 fBottom: y+h,
1001 };
Kevin Lubick1a05fce2018-11-20 12:51:16 -05001002}
1003
Kevin Lubick7d644e12019-09-11 14:22:22 -04001004// RRectXY returns an RRect with the given rect and a radiusX and radiusY for
1005// all 4 corners.
1006CanvasKit.RRectXY = function(rect, rx, ry) {
1007 return {
1008 rect: rect,
1009 rx1: rx,
1010 ry1: ry,
1011 rx2: rx,
1012 ry2: ry,
1013 rx3: rx,
1014 ry3: ry,
1015 rx4: rx,
1016 ry4: ry,
1017 };
1018}
1019
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001020CanvasKit.MakePathFromCmds = function(cmds) {
1021 var ptrLen = loadCmdsTypedArray(cmds);
1022 var path = CanvasKit._MakePathFromCmds(ptrLen[0], ptrLen[1]);
1023 CanvasKit._free(ptrLen[0]);
1024 return path;
1025}
1026
1027CanvasKit.MakeSkDashPathEffect = function(intervals, phase) {
1028 if (!phase) {
1029 phase = 0;
1030 }
1031 if (!intervals.length || intervals.length % 2 === 1) {
1032 throw 'Intervals array must have even length';
1033 }
1034 var ptr = copy1dArray(intervals, CanvasKit.HEAPF32);
1035 var dpe = CanvasKit._MakeSkDashPathEffect(ptr, intervals.length, phase);
1036 CanvasKit._free(ptr);
1037 return dpe;
1038}
1039
1040// data is a TypedArray or ArrayBuffer e.g. from fetch().then(resp.arrayBuffer())
Kevin Lubick6b921b72019-09-18 16:18:17 -04001041CanvasKit.MakeAnimatedImageFromEncoded = function(data) {
1042 data = new Uint8Array(data);
1043
1044 var iptr = CanvasKit._malloc(data.byteLength);
1045 CanvasKit.HEAPU8.set(data, iptr);
1046 var img = CanvasKit._decodeAnimatedImage(iptr, data.byteLength);
1047 if (!img) {
1048 SkDebug('Could not decode animated image');
1049 return null;
1050 }
1051 return img;
1052}
1053
1054// data is a TypedArray or ArrayBuffer e.g. from fetch().then(resp.arrayBuffer())
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001055CanvasKit.MakeImageFromEncoded = function(data) {
1056 data = new Uint8Array(data);
1057
1058 var iptr = CanvasKit._malloc(data.byteLength);
1059 CanvasKit.HEAPU8.set(data, iptr);
1060 var img = CanvasKit._decodeImage(iptr, data.byteLength);
1061 if (!img) {
1062 SkDebug('Could not decode image');
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001063 return null;
1064 }
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001065 return img;
1066}
1067
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001068// pixels is a Uint8Array
1069CanvasKit.MakeImage = function(pixels, width, height, alphaType, colorType) {
1070 var bytesPerPixel = pixels.byteLength / (width * height);
1071 var info = {
1072 'width': width,
1073 'height': height,
1074 'alphaType': alphaType,
1075 'colorType': colorType,
1076 };
1077 var pptr = CanvasKit._malloc(pixels.byteLength);
1078 CanvasKit.HEAPU8.set(pixels, pptr);
1079 // No need to _free iptr, Image takes it with SkData::MakeFromMalloc
1080
1081 return CanvasKit._MakeImage(info, pptr, pixels.byteLength, width * bytesPerPixel);
1082}
1083
1084CanvasKit.MakeLinearGradientShader = function(start, end, colors, pos, mode, localMatrix, flags) {
Kevin Lubickee91c072019-03-29 10:39:52 -04001085 var colorPtr = copy1dArray(colors, CanvasKit.HEAPU32);
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001086 var posPtr = copy1dArray(pos, CanvasKit.HEAPF32);
1087 flags = flags || 0;
1088
1089 if (localMatrix) {
1090 // Add perspective args if not provided.
1091 if (localMatrix.length === 6) {
1092 localMatrix.push(0, 0, 1);
1093 }
1094 var lgs = CanvasKit._MakeLinearGradientShader(start, end, colorPtr, posPtr,
1095 colors.length, mode, flags, localMatrix);
1096 } else {
1097 var lgs = CanvasKit._MakeLinearGradientShader(start, end, colorPtr, posPtr,
1098 colors.length, mode, flags);
1099 }
1100
1101 CanvasKit._free(colorPtr);
1102 CanvasKit._free(posPtr);
1103 return lgs;
1104}
1105
1106CanvasKit.MakeRadialGradientShader = function(center, radius, colors, pos, mode, localMatrix, flags) {
Kevin Lubickee91c072019-03-29 10:39:52 -04001107 var colorPtr = copy1dArray(colors, CanvasKit.HEAPU32);
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001108 var posPtr = copy1dArray(pos, CanvasKit.HEAPF32);
1109 flags = flags || 0;
1110
1111 if (localMatrix) {
1112 // Add perspective args if not provided.
1113 if (localMatrix.length === 6) {
1114 localMatrix.push(0, 0, 1);
1115 }
1116 var rgs = CanvasKit._MakeRadialGradientShader(center, radius, colorPtr, posPtr,
1117 colors.length, mode, flags, localMatrix);
1118 } else {
1119 var rgs = CanvasKit._MakeRadialGradientShader(center, radius, colorPtr, posPtr,
1120 colors.length, mode, flags);
1121 }
1122
1123 CanvasKit._free(colorPtr);
1124 CanvasKit._free(posPtr);
1125 return rgs;
1126}
1127
1128CanvasKit.MakeTwoPointConicalGradientShader = function(start, startRadius, end, endRadius,
1129 colors, pos, mode, localMatrix, flags) {
Kevin Lubickee91c072019-03-29 10:39:52 -04001130 var colorPtr = copy1dArray(colors, CanvasKit.HEAPU32);
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001131 var posPtr = copy1dArray(pos, CanvasKit.HEAPF32);
1132 flags = flags || 0;
1133
1134 if (localMatrix) {
1135 // Add perspective args if not provided.
1136 if (localMatrix.length === 6) {
1137 localMatrix.push(0, 0, 1);
1138 }
1139 var rgs = CanvasKit._MakeTwoPointConicalGradientShader(
1140 start, startRadius, end, endRadius,
1141 colorPtr, posPtr, colors.length, mode, flags, localMatrix);
1142 } else {
1143 var rgs = CanvasKit._MakeTwoPointConicalGradientShader(
1144 start, startRadius, end, endRadius,
1145 colorPtr, posPtr, colors.length, mode, flags);
1146 }
1147
1148 CanvasKit._free(colorPtr);
1149 CanvasKit._free(posPtr);
1150 return rgs;
1151}
1152
1153CanvasKit.MakeSkVertices = function(mode, positions, textureCoordinates, colors,
Kevin Lubickb3574c92019-03-06 08:25:36 -05001154 boneIndices, boneWeights, indices, isVolatile) {
Kevin Lubickb3574c92019-03-06 08:25:36 -05001155 // Default isVolitile to true if not set
1156 isVolatile = isVolatile === undefined ? true : isVolatile;
Kevin Lubickd6ba7252019-06-03 14:38:05 -04001157 var idxCount = (indices && indices.length) || 0;
1158
1159 var flags = 0;
1160 // These flags are from SkVertices.h and should be kept in sync with those.
1161 if (textureCoordinates && textureCoordinates.length) {
1162 flags |= (1 << 0);
1163 }
1164 if (colors && colors.length) {
1165 flags |= (1 << 1);
1166 }
1167 if (boneIndices && boneIndices.length) {
1168 flags |= (1 << 2);
1169 }
1170 if (!isVolatile) {
1171 flags |= (1 << 3);
1172 }
1173
1174 var builder = new CanvasKit._SkVerticesBuilder(mode, positions.length, idxCount, flags);
1175
1176 copy2dArray(positions, CanvasKit.HEAPF32, builder.positions());
1177 if (builder.texCoords()) {
1178 copy2dArray(textureCoordinates, CanvasKit.HEAPF32, builder.texCoords());
1179 }
1180 if (builder.colors()) {
1181 copy1dArray(colors, CanvasKit.HEAPU32, builder.colors());
1182 }
1183 if (builder.boneIndices()) {
1184 copy2dArray(boneIndices, CanvasKit.HEAP32, builder.boneIndices());
1185 }
1186 if (builder.boneWeights()) {
1187 copy2dArray(boneWeights, CanvasKit.HEAPF32, builder.boneWeights());
1188 }
1189 if (builder.indices()) {
1190 copy1dArray(indices, CanvasKit.HEAPU16, builder.indices());
1191 }
Kevin Lubickb3574c92019-03-06 08:25:36 -05001192
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001193 var idxCount = (indices && indices.length) || 0;
Kevin Lubickd6ba7252019-06-03 14:38:05 -04001194 // Create the vertices, which owns the memory that the builder had allocated.
1195 return builder.detach();
Kevin Lubicka064c282019-04-04 09:28:53 -04001196};