blob: 815335bd4d53d4bf4c0735f15941476874feec69 [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 Lubickf5ea37f2019-02-28 10:06:18 -050011 // Add some helpers for matrices. This is ported from SkMatrix.cpp
12 // to save complexity and overhead of going back and forth between
13 // C++ and JS layers.
14 // I would have liked to use something like DOMMatrix, except it
15 // isn't widely supported (would need polyfills) and it doesn't
16 // have a mapPoints() function (which could maybe be tacked on here).
17 // If DOMMatrix catches on, it would be worth re-considering this usage.
18 CanvasKit.SkMatrix = {};
Nathaniel Nifong77798b42020-02-21 17:15:22 -050019 function sdot() { // to be called with an even number of scalar args
20 var acc = 0;
21 for (var i=0; i < arguments.length-1; i+=2) {
22 acc += arguments[i] * arguments[i+1];
23 }
24 return acc;
25 }
26
27
28 // Private general matrix functions used in both 3x3s and 4x4s.
29 // Return a square identity matrix of size n.
30 var identityN = function(n) {
31 var size = n*n;
32 var m = new Array(size);
33 while(size--) {
34 m[size] = size%(n+1) == 0 ? 1.0 : 0.0;
35 }
36 return m;
37 }
38
39 // Stride, a function for compactly representing several ways of copying an array into another.
40 // Write vector `v` into matrix `m`. `m` is a matrix encoded as an array in row-major
41 // order. Its width is passed as `width`. `v` is an array with length < (m.length/width).
42 // An element of `v` is copied into `m` starting at `offset` and moving `colStride` cols right
43 // each row.
44 //
45 // For example, a width of 4, offset of 3, and stride of -1 would put the vector here.
46 // _ _ 0 _
47 // _ 1 _ _
48 // 2 _ _ _
49 // _ _ _ 3
50 //
51 var stride = function(v, m, width, offset, colStride) {
52 for (var i=0; i<v.length; i++) {
53 m[i * width + // column
54 (i * colStride + offset + width) % width // row
55 ] = v[i];
56 }
57 return m;
Kevin Lubickf5ea37f2019-02-28 10:06:18 -050058 }
59
60 CanvasKit.SkMatrix.identity = function() {
Nathaniel Nifong77798b42020-02-21 17:15:22 -050061 return identityN(3);
Kevin Lubickf5ea37f2019-02-28 10:06:18 -050062 };
63
64 // Return the inverse (if it exists) of this matrix.
65 // Otherwise, return the identity.
66 CanvasKit.SkMatrix.invert = function(m) {
Nathaniel Nifong77798b42020-02-21 17:15:22 -050067 // Find the determinant by the sarrus rule. https://en.wikipedia.org/wiki/Rule_of_Sarrus
Kevin Lubickf5ea37f2019-02-28 10:06:18 -050068 var det = m[0]*m[4]*m[8] + m[1]*m[5]*m[6] + m[2]*m[3]*m[7]
69 - m[2]*m[4]*m[6] - m[1]*m[3]*m[8] - m[0]*m[5]*m[7];
70 if (!det) {
71 SkDebug('Warning, uninvertible matrix');
Nathaniel Nifong77798b42020-02-21 17:15:22 -050072 return null;
Kevin Lubick1a05fce2018-11-20 12:51:16 -050073 }
Nathaniel Nifong77798b42020-02-21 17:15:22 -050074 // Return the inverse by the formula adj(m)/det.
75 // adj (adjugate) of a 3x3 is the transpose of it's cofactor matrix.
76 // a cofactor matrix is a matrix where each term is +-det(N) where matrix N is the 2x2 formed
77 // by removing the row and column we're currently setting from the source.
78 // the sign alternates in a checkerboard pattern with a `+` at the top left.
79 // that's all been combined here into one expression.
Kevin Lubickf5ea37f2019-02-28 10:06:18 -050080 return [
81 (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,
82 (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,
83 (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,
84 ];
85 };
Kevin Lubick1a05fce2018-11-20 12:51:16 -050086
Kevin Lubickf5ea37f2019-02-28 10:06:18 -050087 // Maps the given points according to the passed in matrix.
88 // Results are done in place.
89 // See SkMatrix.h::mapPoints for the docs on the math.
90 CanvasKit.SkMatrix.mapPoints = function(matrix, ptArr) {
Nathaniel Nifong77798b42020-02-21 17:15:22 -050091 if (skIsDebug && (ptArr.length % 2)) {
Kevin Lubickf5ea37f2019-02-28 10:06:18 -050092 throw 'mapPoints requires an even length arr';
Kevin Lubickb9db3902018-11-26 11:47:54 -050093 }
Kevin Lubickf5ea37f2019-02-28 10:06:18 -050094 for (var i = 0; i < ptArr.length; i+=2) {
95 var x = ptArr[i], y = ptArr[i+1];
96 // Gx+Hy+I
97 var denom = matrix[6]*x + matrix[7]*y + matrix[8];
98 // Ax+By+C
99 var xTrans = matrix[0]*x + matrix[1]*y + matrix[2];
100 // Dx+Ey+F
101 var yTrans = matrix[3]*x + matrix[4]*y + matrix[5];
102 ptArr[i] = xTrans/denom;
103 ptArr[i+1] = yTrans/denom;
104 }
105 return ptArr;
106 };
Kevin Lubickb9db3902018-11-26 11:47:54 -0500107
Nathaniel Nifong77798b42020-02-21 17:15:22 -0500108 function isnumber(val) { return val !== NaN; };
109
110 // gereralized iterative algorithm for multiplying two matrices.
111 function multiply(m1, m2, size) {
112
113 if (skIsDebug && (!m1.every(isnumber) || !m2.every(isnumber))) {
114 throw 'Some members of matrices are NaN m1='+m1+', m2='+m2+'';
115 }
116 if (skIsDebug && (m1.length !== m2.length)) {
117 throw 'Undefined for matrices of different sizes. m1.length='+m1.length+', m2.length='+m2.length;
118 }
119 if (skIsDebug && (size*size !== m1.length)) {
120 throw 'Undefined for non-square matrices. array size was '+size;
121 }
122
123 var result = Array(m1.length);
124 for (var r = 0; r < size; r++) {
125 for (var c = 0; c < size; c++) {
126 // accumulate a sum of m1[r,k]*m2[k, c]
127 var acc = 0;
128 for (var k = 0; k < size; k++) {
129 acc += m1[size * r + k] * m2[size * k + c];
130 }
131 result[r * size + c] = acc;
Kevin Lubick1a05fce2018-11-20 12:51:16 -0500132 }
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500133 }
134 return result;
Nathaniel Nifong77798b42020-02-21 17:15:22 -0500135 };
136
137 // Accept an integer indicating the size of the matrices being multiplied (3 for 3x3), and any
138 // number of matrices following it.
139 function multiplyMany(size, listOfMatrices) {
140 if (skIsDebug && (listOfMatrices.length < 2)) {
141 throw 'multiplication expected two or more matrices';
142 }
143 var result = multiply(listOfMatrices[0], listOfMatrices[1], size);
144 var next = 2;
145 while (next < listOfMatrices.length) {
146 result = multiply(result, listOfMatrices[next], size);
147 next++;
148 }
149 return result;
150 };
151
152 // Accept any number 3x3 of matrices as arguments, multiply them together.
153 // Matrix multiplication is associative but not commutatieve. the order of the arguments
154 // matters, but it does not matter that this implementation multiplies them left to right.
155 CanvasKit.SkMatrix.multiply = function() {
156 return multiplyMany(3, arguments);
157 };
Kevin Lubick1a05fce2018-11-20 12:51:16 -0500158
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500159 // Return a matrix representing a rotation by n radians.
160 // px, py optionally say which point the rotation should be around
161 // with the default being (0, 0);
162 CanvasKit.SkMatrix.rotated = function(radians, px, py) {
163 px = px || 0;
164 py = py || 0;
165 var sinV = Math.sin(radians);
166 var cosV = Math.cos(radians);
167 return [
168 cosV, -sinV, sdot( sinV, py, 1 - cosV, px),
169 sinV, cosV, sdot(-sinV, px, 1 - cosV, py),
170 0, 0, 1,
171 ];
172 };
Kevin Lubick217056c2018-09-20 17:39:31 -0400173
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500174 CanvasKit.SkMatrix.scaled = function(sx, sy, px, py) {
175 px = px || 0;
176 py = py || 0;
Nathaniel Nifong77798b42020-02-21 17:15:22 -0500177 var m = stride([sx, sy], identityN(3), 3, 0, 1);
178 return stride([px-sx*px, py-sy*py], m, 3, 2, 0);
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500179 };
Kevin Lubickda3d8ac2019-01-07 11:08:55 -0500180
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500181 CanvasKit.SkMatrix.skewed = function(kx, ky, px, py) {
182 px = px || 0;
183 py = py || 0;
Nathaniel Nifong77798b42020-02-21 17:15:22 -0500184 var m = stride([kx, ky], identityN(3), 3, 1, -1);
185 return stride([-kx*px, -ky*py], m, 3, 2, 0);
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500186 };
Alexander Khovansky3e119332018-11-15 02:01:19 +0300187
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500188 CanvasKit.SkMatrix.translated = function(dx, dy) {
Nathaniel Nifong77798b42020-02-21 17:15:22 -0500189 return stride(arguments, identityN(3), 3, 2, 0);
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500190 };
Kevin Lubick1646e7d2018-12-07 13:03:08 -0500191
Nathaniel Nifong77798b42020-02-21 17:15:22 -0500192 // Functions for manipulating vectors.
193 // Loosely based off of SkV3 in SkM44.h but skia also has SkVec2 and Skv4. This combines them and
194 // works on vectors of any length.
195 CanvasKit.SkVector = {};
196 CanvasKit.SkVector.dot = function(a, b) {
197 if (skIsDebug && (a.length !== b.length)) {
198 throw 'Cannot perform dot product on arrays of different length ('+a.length+' vs '+b.length+')';
199 }
200 return a.map(function(v, i) { return v*b[i] }).reduce(function(acc, cur) { return acc + cur; });
201 }
202 CanvasKit.SkVector.lengthSquared = function(v) {
203 return CanvasKit.SkVector.dot(v, v);
204 }
205 CanvasKit.SkVector.length = function(v) {
206 return Math.sqrt(CanvasKit.SkVector.lengthSquared(v));
207 }
208 CanvasKit.SkVector.mulScalar = function(v, s) {
209 return v.map(function(i) { return i*s });
210 }
211 CanvasKit.SkVector.add = function(a, b) {
212 return a.map(function(v, i) { return v+b[i] });
213 }
214 CanvasKit.SkVector.sub = function(a, b) {
215 return a.map(function(v, i) { return v-b[i]; });
216 }
Nathaniel Nifongcc5415a2020-02-23 14:26:33 -0500217 CanvasKit.SkVector.dist = function(a, b) {
218 return CanvasKit.SkVector.length(CanvasKit.SkVector.sub(a, b));
219 }
Nathaniel Nifong77798b42020-02-21 17:15:22 -0500220 CanvasKit.SkVector.normalize = function(v) {
221 return CanvasKit.SkVector.mulScalar(v, 1/CanvasKit.SkVector.length(v));
222 }
223 CanvasKit.SkVector.cross = function(a, b) {
224 if (skIsDebug && (a.length !== 3 || a.length !== 3)) {
225 throw 'Cross product is only defined for 3-dimensional vectors (a.length='+a.length+', b.length='+b.length+')';
226 }
227 return [
228 a[1]*b[2] - a[2]*b[1],
229 a[2]*b[0] - a[0]*b[2],
230 a[0]*b[1] - a[1]*b[0],
231 ];
232 }
233
234 // Functions for creating and manipulating 4x4 matrices. Accepted in place of SkM44 in canvas
235 // methods, for the same reasons as the 3x3 matrices above.
236 // ported from C++ code in SkM44.cpp
237 CanvasKit.SkM44 = {};
238 // Create a 4x4 identity matrix
239 CanvasKit.SkM44.identity = function() {
240 return identityN(4);
241 }
242
243 // Anything named vec below is an array of length 3 representing a vector/point in 3D space.
244 // Create a 4x4 matrix representing a translate by the provided 3-vec
245 CanvasKit.SkM44.translated = function(vec) {
246 return stride(vec, identityN(4), 4, 3, 0);
247 }
248 // Create a 4x4 matrix representing a scaling by the provided 3-vec
249 CanvasKit.SkM44.scaled = function(vec) {
250 return stride(vec, identityN(4), 4, 0, 1);
251 }
252 // Create a 4x4 matrix representing a rotation about the provided axis 3-vec.
253 // axis does not need to be normalized.
254 CanvasKit.SkM44.rotated = function(axisVec, radians) {
255 return CanvasKit.SkM44.rotatedUnitSinCos(
256 CanvasKit.SkVector.normalize(axisVec), Math.sin(radians), Math.cos(radians));
257 }
258 // Create a 4x4 matrix representing a rotation about the provided normalized axis 3-vec.
259 // Rotation is provided redundantly as both sin and cos values.
260 // This rotate can be used when you already have the cosAngle and sinAngle values
261 // so you don't have to atan(cos/sin) to call roatated() which expects an angle in radians.
262 // this does no checking! Behavior for invalid sin or cos values or non-normalized axis vectors
263 // is incorrect. Prefer rotate().
264 CanvasKit.SkM44.rotatedUnitSinCos = function(axisVec, sinAngle, cosAngle) {
265 var x = axisVec[0];
266 var y = axisVec[1];
267 var z = axisVec[2];
268 var c = cosAngle;
269 var s = sinAngle;
270 var t = 1 - c;
271 return [
272 t*x*x + c, t*x*y - s*z, t*x*z + s*y, 0,
273 t*x*y + s*z, t*y*y + c, t*y*z - s*x, 0,
274 t*x*z - s*y, t*y*z + s*x, t*z*z + c, 0,
275 0, 0, 0, 1
276 ];
277 }
278 // Create a 4x4 matrix representing a camera at eyeVec, pointed at centerVec.
279 CanvasKit.SkM44.lookat = function(eyeVec, centerVec, upVec) {
280 var f = CanvasKit.SkVector.normalize(CanvasKit.SkVector.sub(centerVec, eyeVec));
281 var u = CanvasKit.SkVector.normalize(upVec);
282 var s = CanvasKit.SkVector.normalize(CanvasKit.SkVector.cross(f, u));
283
284 var m = CanvasKit.SkM44.identity();
285 // set each column's top three numbers
286 stride(s, m, 4, 0, 0);
287 stride(CanvasKit.SkVector.cross(s, f), m, 4, 1, 0);
288 stride(CanvasKit.SkVector.mulScalar(f, -1), m, 4, 2, 0);
289 stride(eyeVec, m, 4, 3, 0);
290
291 var m2 = CanvasKit.SkM44.invert(m);
292 if (m2 === null) {
293 return CanvasKit.SkM44.identity();
294 }
295 return m2;
296 }
297 // Create a 4x4 matrix representing a perspective. All arguments are scalars.
298 // angle is in radians.
299 CanvasKit.SkM44.perspective = function(near, far, angle) {
300 if (skIsDebug && (far <= near)) {
301 throw "far must be greater than near when constructing SkM44 using perspective.";
302 }
303 var dInv = 1 / (far - near);
304 var halfAngle = angle / 2;
305 var cot = Math.cos(halfAngle) / Math.sin(halfAngle);
306 return [
307 cot, 0, 0, 0,
308 0, cot, 0, 0,
309 0, 0, (far+near)*dInv, 2*far*near*dInv,
310 0, 0, -1, 1,
311 ];
312 }
313 // Returns the number at the given row and column in matrix m.
314 CanvasKit.SkM44.rc = function(m, r, c) {
315 return m[r*4+c];
316 }
317 // Accepts any number of 4x4 matrix arguments, multiplies them left to right.
318 CanvasKit.SkM44.multiply = function() {
319 return multiplyMany(4, arguments);
320 }
321
322 // Invert the 4x4 matrix if it is invertible and return it. if not, return null.
323 // taken from SkM44.cpp (altered to use row-major order)
324 // m is not altered.
325 CanvasKit.SkM44.invert = function(m) {
326 if (skIsDebug && !m.every(isnumber)) {
327 throw 'some members of matrix are NaN m='+m;
328 }
329
330 var a00 = m[0];
331 var a01 = m[4];
332 var a02 = m[8];
333 var a03 = m[12];
334 var a10 = m[1];
335 var a11 = m[5];
336 var a12 = m[9];
337 var a13 = m[13];
338 var a20 = m[2];
339 var a21 = m[6];
340 var a22 = m[10];
341 var a23 = m[14];
342 var a30 = m[3];
343 var a31 = m[7];
344 var a32 = m[11];
345 var a33 = m[15];
346
347 var b00 = a00 * a11 - a01 * a10;
348 var b01 = a00 * a12 - a02 * a10;
349 var b02 = a00 * a13 - a03 * a10;
350 var b03 = a01 * a12 - a02 * a11;
351 var b04 = a01 * a13 - a03 * a11;
352 var b05 = a02 * a13 - a03 * a12;
353 var b06 = a20 * a31 - a21 * a30;
354 var b07 = a20 * a32 - a22 * a30;
355 var b08 = a20 * a33 - a23 * a30;
356 var b09 = a21 * a32 - a22 * a31;
357 var b10 = a21 * a33 - a23 * a31;
358 var b11 = a22 * a33 - a23 * a32;
359
360 // calculate determinate
361 var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
362 var invdet = 1.0 / det;
363
364 // bail out if the matrix is not invertible
365 if (det === 0 || invdet === Infinity) {
366 SkDebug('Warning, uninvertible matrix');
367 return null;
368 }
369
370 b00 *= invdet;
371 b01 *= invdet;
372 b02 *= invdet;
373 b03 *= invdet;
374 b04 *= invdet;
375 b05 *= invdet;
376 b06 *= invdet;
377 b07 *= invdet;
378 b08 *= invdet;
379 b09 *= invdet;
380 b10 *= invdet;
381 b11 *= invdet;
382
383 // store result in row major order
384 var tmp = [
385 a11 * b11 - a12 * b10 + a13 * b09,
386 a12 * b08 - a10 * b11 - a13 * b07,
387 a10 * b10 - a11 * b08 + a13 * b06,
388 a11 * b07 - a10 * b09 - a12 * b06,
389
390 a02 * b10 - a01 * b11 - a03 * b09,
391 a00 * b11 - a02 * b08 + a03 * b07,
392 a01 * b08 - a00 * b10 - a03 * b06,
393 a00 * b09 - a01 * b07 + a02 * b06,
394
395 a31 * b05 - a32 * b04 + a33 * b03,
396 a32 * b02 - a30 * b05 - a33 * b01,
397 a30 * b04 - a31 * b02 + a33 * b00,
398 a31 * b01 - a30 * b03 - a32 * b00,
399
400 a22 * b04 - a21 * b05 - a23 * b03,
401 a20 * b05 - a22 * b02 + a23 * b01,
402 a21 * b02 - a20 * b04 - a23 * b00,
403 a20 * b03 - a21 * b01 + a22 * b00,
404 ];
405
406
407 if (!tmp.every(function(val) { return val !== NaN && val !== Infinity && val !== -Infinity; })) {
408 SkDebug('inverted matrix contains infinities or NaN '+tmp);
409 return null;
410 }
411 return tmp;
412 }
413
Nathaniel Nifongcc5415a2020-02-23 14:26:33 -0500414 CanvasKit.SkM44.transpose = function(m) {
415 return [
416 m[0], m[4], m[8], m[12],
417 m[1], m[5], m[9], m[13],
418 m[2], m[6], m[10], m[14],
419 m[3], m[7], m[11], m[15],
420 ];
421 }
Nathaniel Nifong77798b42020-02-21 17:15:22 -0500422
Kevin Lubickd3729342019-09-12 11:11:25 -0400423 // An SkColorMatrix is a 4x4 color matrix that transforms the 4 color channels
424 // with a 1x4 matrix that post-translates those 4 channels.
425 // For example, the following is the layout with the scale (S) and post-transform
426 // (PT) items indicated.
427 // RS, 0, 0, 0 | RPT
428 // 0, GS, 0, 0 | GPT
429 // 0, 0, BS, 0 | BPT
430 // 0, 0, 0, AS | APT
431 //
432 // Much of this was hand-transcribed from SkColorMatrix.cpp, because it's easier to
433 // deal with a Float32Array of length 20 than to try to expose the SkColorMatrix object.
434
Nathaniel Nifongcc5415a2020-02-23 14:26:33 -0500435 var rScale = 0;
436 var gScale = 6;
437 var bScale = 12;
438 var aScale = 18;
439
Kevin Lubickd3729342019-09-12 11:11:25 -0400440 var rPostTrans = 4;
441 var gPostTrans = 9;
442 var bPostTrans = 14;
443 var aPostTrans = 19;
444
445 CanvasKit.SkColorMatrix = {};
446 CanvasKit.SkColorMatrix.identity = function() {
Nathaniel Nifongcc5415a2020-02-23 14:26:33 -0500447 var m = new Float32Array(20);
448 m[rScale] = 1;
449 m[gScale] = 1;
450 m[bScale] = 1;
451 m[aScale] = 1;
452 return m;
Kevin Lubickd3729342019-09-12 11:11:25 -0400453 }
454
455 CanvasKit.SkColorMatrix.scaled = function(rs, gs, bs, as) {
Nathaniel Nifongcc5415a2020-02-23 14:26:33 -0500456 var m = new Float32Array(20);
457 m[rScale] = rs;
458 m[gScale] = gs;
459 m[bScale] = bs;
460 m[aScale] = as;
461 return m;
Kevin Lubickd3729342019-09-12 11:11:25 -0400462 }
463
464 var rotateIndices = [
465 [6, 7, 11, 12],
466 [0, 10, 2, 12],
467 [0, 1, 5, 6],
468 ];
469 // axis should be 0, 1, 2 for r, g, b
470 CanvasKit.SkColorMatrix.rotated = function(axis, sine, cosine) {
471 var m = CanvasKit.SkColorMatrix.identity();
472 var indices = rotateIndices[axis];
473 m[indices[0]] = cosine;
474 m[indices[1]] = sine;
475 m[indices[2]] = -sine;
476 m[indices[3]] = cosine;
477 return m;
478 }
479
480 // m is a SkColorMatrix (i.e. a Float32Array), and this sets the 4 "special"
481 // params that will translate the colors after they are multiplied by the 4x4 matrix.
482 CanvasKit.SkColorMatrix.postTranslate = function(m, dr, dg, db, da) {
483 m[rPostTrans] += dr;
484 m[gPostTrans] += dg;
485 m[bPostTrans] += db;
486 m[aPostTrans] += da;
487 return m;
488 }
489
490 // concat returns a new SkColorMatrix that is the result of multiplying outer*inner;
491 CanvasKit.SkColorMatrix.concat = function(outer, inner) {
492 var m = new Float32Array(20);
493 var index = 0;
494 for (var j = 0; j < 20; j += 5) {
495 for (var i = 0; i < 4; i++) {
496 m[index++] = outer[j + 0] * inner[i + 0] +
497 outer[j + 1] * inner[i + 5] +
498 outer[j + 2] * inner[i + 10] +
499 outer[j + 3] * inner[i + 15];
500 }
501 m[index++] = outer[j + 0] * inner[4] +
502 outer[j + 1] * inner[9] +
503 outer[j + 2] * inner[14] +
504 outer[j + 3] * inner[19] +
505 outer[j + 4];
506 }
507
508 return m;
509 }
510
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500511 CanvasKit.SkPath.prototype.addArc = function(oval, startAngle, sweepAngle) {
512 // see arc() for the HTMLCanvas version
513 // note input angles are degrees.
514 this._addArc(oval, startAngle, sweepAngle);
515 return this;
516 };
Kevin Lubick217056c2018-09-20 17:39:31 -0400517
Kevin Lubicke384df42019-08-26 15:48:09 -0400518 CanvasKit.SkPath.prototype.addOval = function(oval, isCCW, startIndex) {
519 if (startIndex === undefined) {
520 startIndex = 1;
521 }
522 this._addOval(oval, !!isCCW, startIndex);
523 return this;
524 };
525
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500526 CanvasKit.SkPath.prototype.addPath = function() {
527 // Takes 1, 2, 7, or 10 required args, where the first arg is always the path.
528 // The last arg is optional and chooses between add or extend mode.
529 // The options for the remaining args are:
530 // - an array of 6 or 9 parameters (perspective is optional)
531 // - the 9 parameters of a full matrix or
532 // the 6 non-perspective params of a matrix.
533 var args = Array.prototype.slice.call(arguments);
534 var path = args[0];
535 var extend = false;
536 if (typeof args[args.length-1] === "boolean") {
537 extend = args.pop();
538 }
539 if (args.length === 1) {
540 // Add path, unchanged. Use identity matrix
541 this._addPath(path, 1, 0, 0,
542 0, 1, 0,
543 0, 0, 1,
544 extend);
545 } else if (args.length === 2) {
546 // User provided the 9 params of a full matrix as an array.
547 var a = args[1];
548 this._addPath(path, a[0], a[1], a[2],
549 a[3], a[4], a[5],
550 a[6] || 0, a[7] || 0, a[8] || 1,
551 extend);
552 } else if (args.length === 7 || args.length === 10) {
553 // User provided the 9 params of a (full) matrix directly.
554 // (or just the 6 non perspective ones)
555 // These are in the same order as what Skia expects.
556 var a = args;
557 this._addPath(path, a[1], a[2], a[3],
558 a[4], a[5], a[6],
559 a[7] || 0, a[8] || 0, a[9] || 1,
560 extend);
561 } else {
562 SkDebug('addPath expected to take 1, 2, 7, or 10 required args. Got ' + args.length);
Kevin Lubickb5ae3b52018-11-03 07:51:19 -0400563 return null;
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500564 }
565 return this;
566 };
Kevin Lubickb5ae3b52018-11-03 07:51:19 -0400567
Kevin Lubick37ab53e2019-11-11 10:06:08 -0500568 // points is either an array of [x, y] where x and y are numbers or
569 // a typed array from Malloc where the even indices will be treated
570 // as x coordinates and the odd indices will be treated as y coordinates.
571 CanvasKit.SkPath.prototype.addPoly = function(points, close) {
572 var ptr;
573 var n;
574 // This was created with CanvasKit.Malloc, so assume the user has
575 // already been filled with data.
576 if (points['_ck']) {
577 ptr = points.byteOffset;
578 n = points.length/2;
579 } else {
580 ptr = copy2dArray(points, CanvasKit.HEAPF32);
581 n = points.length;
582 }
583 this._addPoly(ptr, n, close);
584 CanvasKit._free(ptr);
585 return this;
586 };
587
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500588 CanvasKit.SkPath.prototype.addRect = function() {
589 // Takes 1, 2, 4 or 5 args
590 // - SkRect
591 // - SkRect, isCCW
592 // - left, top, right, bottom
593 // - left, top, right, bottom, isCCW
594 if (arguments.length === 1 || arguments.length === 2) {
595 var r = arguments[0];
596 var ccw = arguments[1] || false;
597 this._addRect(r.fLeft, r.fTop, r.fRight, r.fBottom, ccw);
598 } else if (arguments.length === 4 || arguments.length === 5) {
599 var a = arguments;
600 this._addRect(a[0], a[1], a[2], a[3], a[4] || false);
601 } else {
602 SkDebug('addRect expected to take 1, 2, 4, or 5 args. Got ' + arguments.length);
Kevin Lubick217056c2018-09-20 17:39:31 -0400603 return null;
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500604 }
605 return this;
606 };
Kevin Lubick217056c2018-09-20 17:39:31 -0400607
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500608 CanvasKit.SkPath.prototype.addRoundRect = function() {
609 // Takes 3, 4, 6 or 7 args
610 // - SkRect, radii, ccw
611 // - SkRect, rx, ry, ccw
612 // - left, top, right, bottom, radii, ccw
613 // - left, top, right, bottom, rx, ry, ccw
614 var args = arguments;
615 if (args.length === 3 || args.length === 6) {
616 var radii = args[args.length-2];
617 } else if (args.length === 6 || args.length === 7){
618 // duplicate the given (rx, ry) pairs for each corner.
619 var rx = args[args.length-3];
620 var ry = args[args.length-2];
621 var radii = [rx, ry, rx, ry, rx, ry, rx, ry];
622 } else {
623 SkDebug('addRoundRect expected to take 3, 4, 6, or 7 args. Got ' + args.length);
624 return null;
625 }
626 if (radii.length !== 8) {
627 SkDebug('addRoundRect needs 8 radii provided. Got ' + radii.length);
628 return null;
629 }
630 var rptr = copy1dArray(radii, CanvasKit.HEAPF32);
631 if (args.length === 3 || args.length === 4) {
632 var r = args[0];
633 var ccw = args[args.length - 1];
634 this._addRoundRect(r.fLeft, r.fTop, r.fRight, r.fBottom, rptr, ccw);
635 } else if (args.length === 6 || args.length === 7) {
636 var a = args;
637 this._addRoundRect(a[0], a[1], a[2], a[3], rptr, ccw);
638 }
639 CanvasKit._free(rptr);
640 return this;
641 };
642
643 CanvasKit.SkPath.prototype.arc = function(x, y, radius, startAngle, endAngle, ccw) {
644 // emulates the HTMLCanvas behavior. See addArc() for the SkPath version.
645 // Note input angles are radians.
646 var bounds = CanvasKit.LTRBRect(x-radius, y-radius, x+radius, y+radius);
647 var sweep = radiansToDegrees(endAngle - startAngle) - (360 * !!ccw);
648 var temp = new CanvasKit.SkPath();
649 temp.addArc(bounds, radiansToDegrees(startAngle), sweep);
650 this.addPath(temp, true);
651 temp.delete();
652 return this;
653 };
654
655 CanvasKit.SkPath.prototype.arcTo = function() {
656 // takes 4, 5 or 7 args
657 // - 5 x1, y1, x2, y2, radius
658 // - 4 oval (as Rect), startAngle, sweepAngle, forceMoveTo
Kevin Lubicke384df42019-08-26 15:48:09 -0400659 // - 7 rx, ry, xAxisRotate, useSmallArc, isCCW, x, y
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500660 var args = arguments;
661 if (args.length === 5) {
662 this._arcTo(args[0], args[1], args[2], args[3], args[4]);
663 } else if (args.length === 4) {
664 this._arcTo(args[0], args[1], args[2], args[3]);
665 } else if (args.length === 7) {
Kevin Lubicke384df42019-08-26 15:48:09 -0400666 this._arcTo(args[0], args[1], args[2], !!args[3], !!args[4], args[5], args[6]);
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500667 } else {
668 throw 'Invalid args for arcTo. Expected 4, 5, or 7, got '+ args.length;
669 }
670
671 return this;
672 };
673
674 CanvasKit.SkPath.prototype.close = function() {
675 this._close();
676 return this;
677 };
678
679 CanvasKit.SkPath.prototype.conicTo = function(x1, y1, x2, y2, w) {
680 this._conicTo(x1, y1, x2, y2, w);
681 return this;
682 };
683
684 CanvasKit.SkPath.prototype.cubicTo = function(cp1x, cp1y, cp2x, cp2y, x, y) {
685 this._cubicTo(cp1x, cp1y, cp2x, cp2y, x, y);
686 return this;
687 };
688
689 CanvasKit.SkPath.prototype.dash = function(on, off, phase) {
690 if (this._dash(on, off, phase)) {
Kevin Lubick217056c2018-09-20 17:39:31 -0400691 return this;
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500692 }
693 return null;
694 };
Kevin Lubick217056c2018-09-20 17:39:31 -0400695
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500696 CanvasKit.SkPath.prototype.lineTo = function(x, y) {
697 this._lineTo(x, y);
698 return this;
699 };
Kevin Lubick217056c2018-09-20 17:39:31 -0400700
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500701 CanvasKit.SkPath.prototype.moveTo = function(x, y) {
702 this._moveTo(x, y);
703 return this;
704 };
Kevin Lubickb5ae3b52018-11-03 07:51:19 -0400705
Kevin Lubicke384df42019-08-26 15:48:09 -0400706 CanvasKit.SkPath.prototype.offset = function(dx, dy) {
707 this._transform(1, 0, dx,
708 0, 1, dy,
709 0, 0, 1);
710 return this;
711 };
712
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500713 CanvasKit.SkPath.prototype.quadTo = function(cpx, cpy, x, y) {
714 this._quadTo(cpx, cpy, x, y);
715 return this;
716 };
717
Kevin Lubick79b71342019-11-01 14:36:52 -0400718 CanvasKit.SkPath.prototype.rArcTo = function(rx, ry, xAxisRotate, useSmallArc, isCCW, dx, dy) {
719 this._rArcTo(rx, ry, xAxisRotate, useSmallArc, isCCW, dx, dy);
720 return this;
721 };
722
723 CanvasKit.SkPath.prototype.rConicTo = function(dx1, dy1, dx2, dy2, w) {
724 this._rConicTo(dx1, dy1, dx2, dy2, w);
725 return this;
726 };
727
728 // These params are all relative
729 CanvasKit.SkPath.prototype.rCubicTo = function(cp1x, cp1y, cp2x, cp2y, x, y) {
730 this._rCubicTo(cp1x, cp1y, cp2x, cp2y, x, y);
731 return this;
732 };
733
734 CanvasKit.SkPath.prototype.rLineTo = function(dx, dy) {
735 this._rLineTo(dx, dy);
736 return this;
737 };
738
739 CanvasKit.SkPath.prototype.rMoveTo = function(dx, dy) {
740 this._rMoveTo(dx, dy);
741 return this;
742 };
743
744 // These params are all relative
745 CanvasKit.SkPath.prototype.rQuadTo = function(cpx, cpy, x, y) {
746 this._rQuadTo(cpx, cpy, x, y);
747 return this;
748 };
749
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500750 CanvasKit.SkPath.prototype.stroke = function(opts) {
751 // Fill out any missing values with the default values.
752 /**
753 * See externs.js for this definition
754 * @type {StrokeOpts}
755 */
756 opts = opts || {};
757 opts.width = opts.width || 1;
758 opts.miter_limit = opts.miter_limit || 4;
759 opts.cap = opts.cap || CanvasKit.StrokeCap.Butt;
760 opts.join = opts.join || CanvasKit.StrokeJoin.Miter;
761 opts.precision = opts.precision || 1;
762 if (this._stroke(opts)) {
763 return this;
764 }
765 return null;
766 };
767
768 CanvasKit.SkPath.prototype.transform = function() {
769 // Takes 1 or 9 args
770 if (arguments.length === 1) {
771 // argument 1 should be a 6 or 9 element array.
772 var a = arguments[0];
773 this._transform(a[0], a[1], a[2],
774 a[3], a[4], a[5],
775 a[6] || 0, a[7] || 0, a[8] || 1);
776 } else if (arguments.length === 6 || arguments.length === 9) {
777 // these arguments are the 6 or 9 members of the matrix
778 var a = arguments;
779 this._transform(a[0], a[1], a[2],
780 a[3], a[4], a[5],
781 a[6] || 0, a[7] || 0, a[8] || 1);
782 } else {
783 throw 'transform expected to take 1 or 9 arguments. Got ' + arguments.length;
784 }
785 return this;
786 };
787 // isComplement is optional, defaults to false
788 CanvasKit.SkPath.prototype.trim = function(startT, stopT, isComplement) {
789 if (this._trim(startT, stopT, !!isComplement)) {
790 return this;
791 }
792 return null;
793 };
794
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500795 CanvasKit.SkImage.prototype.encodeToData = function() {
796 if (!arguments.length) {
797 return this._encodeToData();
Kevin Lubickb5ae3b52018-11-03 07:51:19 -0400798 }
Kevin Lubick53965c92018-10-11 08:51:55 -0400799
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500800 if (arguments.length === 2) {
801 var a = arguments;
802 return this._encodeToDataWithFormat(a[0], a[1]);
Alexander Khovansky3e119332018-11-15 02:01:19 +0300803 }
804
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500805 throw 'encodeToData expected to take 0 or 2 arguments. Got ' + arguments.length;
806 }
Kevin Lubick1ba9c4d2019-02-22 10:04:06 -0500807
Kevin Lubicka064c282019-04-04 09:28:53 -0400808 CanvasKit.SkImage.prototype.makeShader = function(xTileMode, yTileMode, localMatrix) {
809 if (localMatrix) {
810 // Add perspective args if not provided.
811 if (localMatrix.length === 6) {
812 localMatrix.push(0, 0, 1);
813 }
814 return this._makeShader(xTileMode, yTileMode, localMatrix);
815 } else {
816 return this._makeShader(xTileMode, yTileMode);
817 }
818 }
819
Kevin Lubickd6b32ed2019-05-06 13:04:03 -0400820 CanvasKit.SkImage.prototype.readPixels = function(imageInfo, srcX, srcY) {
821 var rowBytes;
Kevin Lubick319524b2020-01-22 15:29:14 -0500822 // Important to use ["string"] notation here, otherwise the closure compiler will
823 // minify away the colorType.
824 switch (imageInfo["colorType"]) {
Kevin Lubickd6b32ed2019-05-06 13:04:03 -0400825 case CanvasKit.ColorType.RGBA_8888:
826 rowBytes = imageInfo.width * 4; // 1 byte per channel == 4 bytes per pixel in 8888
827 break;
828 case CanvasKit.ColorType.RGBA_F32:
829 rowBytes = imageInfo.width * 16; // 4 bytes per channel == 16 bytes per pixel in F32
830 break;
831 default:
832 SkDebug("Colortype not yet supported");
833 return;
834 }
835 var pBytes = rowBytes * imageInfo.height;
836 var pPtr = CanvasKit._malloc(pBytes);
837
838 if (!this._readPixels(imageInfo, pPtr, rowBytes, srcX, srcY)) {
839 SkDebug("Could not read pixels with the given inputs");
840 return null;
841 }
842
843 // Put those pixels into a typed array of the right format and then
844 // make a copy with slice() that we can return.
845 var retVal = null;
Kevin Lubick319524b2020-01-22 15:29:14 -0500846 switch (imageInfo["colorType"]) {
Kevin Lubickd6b32ed2019-05-06 13:04:03 -0400847 case CanvasKit.ColorType.RGBA_8888:
Bryce Thomas1fa54042020-01-14 13:46:30 -0800848 retVal = new Uint8Array(CanvasKit.HEAPU8.buffer, pPtr, pBytes).slice();
Kevin Lubickd6b32ed2019-05-06 13:04:03 -0400849 break;
850 case CanvasKit.ColorType.RGBA_F32:
Bryce Thomas1fa54042020-01-14 13:46:30 -0800851 retVal = new Float32Array(CanvasKit.HEAPU8.buffer, pPtr, pBytes).slice();
Kevin Lubickd6b32ed2019-05-06 13:04:03 -0400852 break;
853 }
854
855 // Free the allocated pixels in the WASM memory
856 CanvasKit._free(pPtr);
857 return retVal;
858
859 }
860
Kevin Lubickee91c072019-03-29 10:39:52 -0400861 // atlas is an SkImage, e.g. from CanvasKit.MakeImageFromEncoded
862 // srcRects and dstXforms should be CanvasKit.SkRectBuilder and CanvasKit.RSXFormBuilder
863 // or just arrays of floats in groups of 4.
864 // colors, if provided, should be a CanvasKit.SkColorBuilder or array of SkColor
865 // (from CanvasKit.Color)
866 CanvasKit.SkCanvas.prototype.drawAtlas = function(atlas, srcRects, dstXforms, paint,
867 /*optional*/ blendMode, colors) {
868 if (!atlas || !paint || !srcRects || !dstXforms) {
869 SkDebug('Doing nothing since missing a required input');
870 return;
871 }
872 if (srcRects.length !== dstXforms.length || (colors && colors.length !== dstXforms.length)) {
873 SkDebug('Doing nothing since input arrays length mismatches');
874 }
875 if (!blendMode) {
876 blendMode = CanvasKit.BlendMode.SrcOver;
877 }
878
879 var srcRectPtr;
880 if (srcRects.build) {
881 srcRectPtr = srcRects.build();
882 } else {
883 srcRectPtr = copy1dArray(srcRects, CanvasKit.HEAPF32);
884 }
885
886 var dstXformPtr;
887 if (dstXforms.build) {
888 dstXformPtr = dstXforms.build();
889 } else {
890 dstXformPtr = copy1dArray(dstXforms, CanvasKit.HEAPF32);
891 }
892
893 var colorPtr = 0; // enscriptem doesn't like undefined for nullptr
894 if (colors) {
895 if (colors.build) {
896 colorPtr = colors.build();
897 } else {
898 colorPtr = copy1dArray(colors, CanvasKit.HEAPU32);
899 }
900 }
901
902 this._drawAtlas(atlas, dstXformPtr, srcRectPtr, colorPtr, dstXforms.length,
903 blendMode, paint);
904
905 if (srcRectPtr && !srcRects.build) {
906 CanvasKit._free(srcRectPtr);
907 }
908 if (dstXformPtr && !dstXforms.build) {
909 CanvasKit._free(dstXformPtr);
910 }
911 if (colorPtr && !colors.build) {
912 CanvasKit._free(colorPtr);
913 }
914
915 }
916
Kevin Lubick37ab53e2019-11-11 10:06:08 -0500917 // points is either an array of [x, y] where x and y are numbers or
918 // a typed array from Malloc where the even indices will be treated
919 // as x coordinates and the odd indices will be treated as y coordinates.
920 CanvasKit.SkCanvas.prototype.drawPoints = function(mode, points, paint) {
921 var ptr;
922 var n;
923 // This was created with CanvasKit.Malloc, so assume the user has
924 // already been filled with data.
925 if (points['_ck']) {
926 ptr = points.byteOffset;
927 n = points.length/2;
928 } else {
929 ptr = copy2dArray(points, CanvasKit.HEAPF32);
930 n = points.length;
931 }
932 this._drawPoints(mode, ptr, n, paint);
933 CanvasKit._free(ptr);
934 }
935
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500936 // returns Uint8Array
937 CanvasKit.SkCanvas.prototype.readPixels = function(x, y, w, h, alphaType,
938 colorType, dstRowBytes) {
939 // supply defaults (which are compatible with HTMLCanvas's getImageData)
940 alphaType = alphaType || CanvasKit.AlphaType.Unpremul;
941 colorType = colorType || CanvasKit.ColorType.RGBA_8888;
942 dstRowBytes = dstRowBytes || (4 * w);
943
944 var len = h * dstRowBytes
945 var pptr = CanvasKit._malloc(len);
946 var ok = this._readPixels({
947 'width': w,
948 'height': h,
Kevin Lubick52b9f372018-12-04 13:57:36 -0500949 'colorType': colorType,
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500950 'alphaType': alphaType,
951 }, pptr, dstRowBytes, x, y);
952 if (!ok) {
953 CanvasKit._free(pptr);
954 return null;
955 }
956
957 // The first typed array is just a view into memory. Because we will
958 // be free-ing that, we call slice to make a persistent copy.
Bryce Thomas1fa54042020-01-14 13:46:30 -0800959 var pixels = new Uint8Array(CanvasKit.HEAPU8.buffer, pptr, len).slice();
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500960 CanvasKit._free(pptr);
961 return pixels;
962 }
963
964 // pixels is a TypedArray. No matter the input size, it will be treated as
965 // a Uint8Array (essentially, a byte array).
966 CanvasKit.SkCanvas.prototype.writePixels = function(pixels, srcWidth, srcHeight,
967 destX, destY, alphaType, colorType) {
968 if (pixels.byteLength % (srcWidth * srcHeight)) {
969 throw 'pixels length must be a multiple of the srcWidth * srcHeight';
970 }
971 var bytesPerPixel = pixels.byteLength / (srcWidth * srcHeight);
972 // supply defaults (which are compatible with HTMLCanvas's putImageData)
973 alphaType = alphaType || CanvasKit.AlphaType.Unpremul;
974 colorType = colorType || CanvasKit.ColorType.RGBA_8888;
975 var srcRowBytes = bytesPerPixel * srcWidth;
976
Kevin Lubick52b9f372018-12-04 13:57:36 -0500977 var pptr = CanvasKit._malloc(pixels.byteLength);
978 CanvasKit.HEAPU8.set(pixels, pptr);
Kevin Lubick52b9f372018-12-04 13:57:36 -0500979
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500980 var ok = this._writePixels({
981 'width': srcWidth,
982 'height': srcHeight,
983 'colorType': colorType,
984 'alphaType': alphaType,
985 }, pptr, srcRowBytes, destX, destY);
986
987 CanvasKit._free(pptr);
988 return ok;
Kevin Lubick52b9f372018-12-04 13:57:36 -0500989 }
990
Kevin Lubickd3729342019-09-12 11:11:25 -0400991 // colorMatrix is an SkColorMatrix (e.g. Float32Array of length 20)
992 CanvasKit.SkColorFilter.MakeMatrix = function(colorMatrix) {
993 if (!colorMatrix || colorMatrix.length !== 20) {
994 SkDebug('ignoring invalid color matrix');
995 return;
996 }
997 var fptr = copy1dArray(colorMatrix, CanvasKit.HEAPF32);
998 // We know skia memcopies the floats, so we can free our memory after the call returns.
999 var m = CanvasKit.SkColorFilter._makeMatrix(fptr);
1000 CanvasKit._free(fptr);
1001 return m;
1002 }
1003
Kevin Lubick62836902019-12-09 09:04:26 -05001004 CanvasKit.SkShader.Blend = function(mode, dst, src, localMatrix) {
1005 if (!localMatrix) {
1006 return this._Blend(mode, dst, src);
1007 }
1008 return this._Blend(mode, dst, src, localMatrix);
1009 }
1010
1011 CanvasKit.SkShader.Lerp = function(t, dst, src, localMatrix) {
1012 if (!localMatrix) {
1013 return this._Lerp(t, dst, src);
1014 }
1015 return this._Lerp(t, dst, src, localMatrix);
1016 }
1017
Kevin Lubickcc13fd32019-04-05 13:00:01 -04001018 CanvasKit.SkSurface.prototype.captureFrameAsSkPicture = function(drawFrame) {
1019 // Set up SkPictureRecorder
1020 var spr = new CanvasKit.SkPictureRecorder();
1021 var canvas = spr.beginRecording(
1022 CanvasKit.LTRBRect(0, 0, this.width(), this.height()));
1023 drawFrame(canvas);
1024 var pic = spr.finishRecordingAsPicture();
1025 spr.delete();
1026 // TODO: do we need to clean up the memory for canvas?
1027 // If we delete it here, saveAsFile doesn't work correctly.
1028 return pic;
1029 }
1030
Kevin Lubick359a7e32019-03-19 09:34:37 -04001031 CanvasKit.SkSurface.prototype.requestAnimationFrame = function(callback, dirtyRect) {
1032 if (!this._cached_canvas) {
1033 this._cached_canvas = this.getCanvas();
1034 }
1035 window.requestAnimationFrame(function() {
Kevin Lubick39026282019-03-28 12:46:40 -04001036 if (this._context !== undefined) {
1037 CanvasKit.setCurrentContext(this._context);
1038 }
Kevin Lubick359a7e32019-03-19 09:34:37 -04001039
1040 callback(this._cached_canvas);
1041
Bryce Thomas2c5b8562020-01-22 13:49:41 -08001042 // We do not dispose() of the SkSurface here, as the client will typically
1043 // call requestAnimationFrame again from within the supplied callback.
1044 // For drawing a single frame, prefer drawOnce().
Kevin Lubick359a7e32019-03-19 09:34:37 -04001045 this.flush();
1046 }.bind(this));
1047 }
1048
Kevin Lubick52379332020-01-27 10:01:25 -05001049 // drawOnce will dispose of the surface after drawing the frame using the provided
1050 // callback.
Bryce Thomas2c5b8562020-01-22 13:49:41 -08001051 CanvasKit.SkSurface.prototype.drawOnce = function(callback, dirtyRect) {
1052 if (!this._cached_canvas) {
1053 this._cached_canvas = this.getCanvas();
1054 }
1055 window.requestAnimationFrame(function() {
1056 if (this._context !== undefined) {
1057 CanvasKit.setCurrentContext(this._context);
1058 }
1059 callback(this._cached_canvas);
1060
1061 this.flush();
1062 this.dispose();
1063 }.bind(this));
1064 }
1065
Nathaniel Nifong23b0ed92020-03-04 15:43:50 -05001066 CanvasKit.SkPathEffect.MakeDash = function(intervals, phase) {
1067 if (!phase) {
1068 phase = 0;
1069 }
1070 if (!intervals.length || intervals.length % 2 === 1) {
1071 throw 'Intervals array must have even length';
1072 }
1073 var ptr = copy1dArray(intervals, CanvasKit.HEAPF32);
1074 var dpe = CanvasKit._MakeSkDashPathEffect(ptr, intervals.length, phase);
1075 CanvasKit._free(ptr);
1076 return dpe;
1077 }
1078
1079 CanvasKit.SkShader.MakeLinearGradient = function(start, end, colors, pos, mode, localMatrix, flags) {
1080 var colorPtr = copy1dArray(colors, CanvasKit.HEAPU32);
1081 var posPtr = copy1dArray(pos, CanvasKit.HEAPF32);
1082 flags = flags || 0;
1083
1084 if (localMatrix) {
1085 // Add perspective args if not provided.
1086 if (localMatrix.length === 6) {
1087 localMatrix.push(0, 0, 1);
1088 }
1089 var lgs = CanvasKit._MakeLinearGradientShader(start, end, colorPtr, posPtr,
1090 colors.length, mode, flags, localMatrix);
1091 } else {
1092 var lgs = CanvasKit._MakeLinearGradientShader(start, end, colorPtr, posPtr,
1093 colors.length, mode, flags);
1094 }
1095
1096 CanvasKit._free(colorPtr);
1097 CanvasKit._free(posPtr);
1098 return lgs;
1099 }
1100
1101 CanvasKit.SkShader.MakeRadialGradient = function(center, radius, colors, pos, mode, localMatrix, flags) {
1102 var colorPtr = copy1dArray(colors, CanvasKit.HEAPU32);
1103 var posPtr = copy1dArray(pos, CanvasKit.HEAPF32);
1104 flags = flags || 0;
1105
1106 if (localMatrix) {
1107 // Add perspective args if not provided.
1108 if (localMatrix.length === 6) {
1109 localMatrix.push(0, 0, 1);
1110 }
1111 var rgs = CanvasKit._MakeRadialGradientShader(center, radius, colorPtr, posPtr,
1112 colors.length, mode, flags, localMatrix);
1113 } else {
1114 var rgs = CanvasKit._MakeRadialGradientShader(center, radius, colorPtr, posPtr,
1115 colors.length, mode, flags);
1116 }
1117
1118 CanvasKit._free(colorPtr);
1119 CanvasKit._free(posPtr);
1120 return rgs;
1121 }
1122
1123 CanvasKit.SkShader.MakeTwoPointConicalGradient = function(start, startRadius, end, endRadius,
1124 colors, pos, mode, localMatrix, flags) {
1125 var colorPtr = copy1dArray(colors, CanvasKit.HEAPU32);
1126 var posPtr = copy1dArray(pos, CanvasKit.HEAPF32);
1127 flags = flags || 0;
1128
1129 if (localMatrix) {
1130 // Add perspective args if not provided.
1131 if (localMatrix.length === 6) {
1132 localMatrix.push(0, 0, 1);
1133 }
1134 var rgs = CanvasKit._MakeTwoPointConicalGradientShader(
1135 start, startRadius, end, endRadius,
1136 colorPtr, posPtr, colors.length, mode, flags, localMatrix);
1137 } else {
1138 var rgs = CanvasKit._MakeTwoPointConicalGradientShader(
1139 start, startRadius, end, endRadius,
1140 colorPtr, posPtr, colors.length, mode, flags);
1141 }
1142
1143 CanvasKit._free(colorPtr);
1144 CanvasKit._free(posPtr);
1145 return rgs;
1146 }
1147
1148 // temporary support for deprecated names.
1149 CanvasKit.MakeSkDashPathEffect = CanvasKit.SkPathEffect.prototype.MakeDash;
1150 CanvasKit.MakeLinearGradientShader = CanvasKit.SkShader.prototype.MakeLinearGradient;
1151 CanvasKit.MakeRadialGradientShader = CanvasKit.SkShader.prototype.MakeRadialGradient;
1152 CanvasKit.MakeTwoPointConicalGradientShader = CanvasKit.SkShader.prototype.MakeTwoPointConicalGradient;
1153
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001154 // Run through the JS files that are added at compile time.
1155 if (CanvasKit._extraInitializations) {
1156 CanvasKit._extraInitializations.forEach(function(init) {
1157 init();
1158 });
Kevin Lubickeb2f6b02018-11-29 15:07:02 -05001159 }
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001160}; // end CanvasKit.onRuntimeInitialized, that is, anything changing prototypes or dynamic.
Kevin Lubickeb2f6b02018-11-29 15:07:02 -05001161
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001162CanvasKit.LTRBRect = function(l, t, r, b) {
1163 return {
1164 fLeft: l,
1165 fTop: t,
1166 fRight: r,
1167 fBottom: b,
1168 };
Kevin Lubick1a05fce2018-11-20 12:51:16 -05001169}
1170
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001171CanvasKit.XYWHRect = function(x, y, w, h) {
1172 return {
1173 fLeft: x,
1174 fTop: y,
1175 fRight: x+w,
1176 fBottom: y+h,
1177 };
Kevin Lubick1a05fce2018-11-20 12:51:16 -05001178}
1179
Kevin Lubick7d644e12019-09-11 14:22:22 -04001180// RRectXY returns an RRect with the given rect and a radiusX and radiusY for
1181// all 4 corners.
1182CanvasKit.RRectXY = function(rect, rx, ry) {
1183 return {
1184 rect: rect,
1185 rx1: rx,
1186 ry1: ry,
1187 rx2: rx,
1188 ry2: ry,
1189 rx3: rx,
1190 ry3: ry,
1191 rx4: rx,
1192 ry4: ry,
1193 };
1194}
1195
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001196CanvasKit.MakePathFromCmds = function(cmds) {
1197 var ptrLen = loadCmdsTypedArray(cmds);
1198 var path = CanvasKit._MakePathFromCmds(ptrLen[0], ptrLen[1]);
1199 CanvasKit._free(ptrLen[0]);
1200 return path;
1201}
1202
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001203// data is a TypedArray or ArrayBuffer e.g. from fetch().then(resp.arrayBuffer())
Kevin Lubick6b921b72019-09-18 16:18:17 -04001204CanvasKit.MakeAnimatedImageFromEncoded = function(data) {
1205 data = new Uint8Array(data);
1206
1207 var iptr = CanvasKit._malloc(data.byteLength);
1208 CanvasKit.HEAPU8.set(data, iptr);
1209 var img = CanvasKit._decodeAnimatedImage(iptr, data.byteLength);
1210 if (!img) {
1211 SkDebug('Could not decode animated image');
1212 return null;
1213 }
1214 return img;
1215}
1216
1217// data is a TypedArray or ArrayBuffer e.g. from fetch().then(resp.arrayBuffer())
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001218CanvasKit.MakeImageFromEncoded = function(data) {
1219 data = new Uint8Array(data);
1220
1221 var iptr = CanvasKit._malloc(data.byteLength);
1222 CanvasKit.HEAPU8.set(data, iptr);
1223 var img = CanvasKit._decodeImage(iptr, data.byteLength);
1224 if (!img) {
1225 SkDebug('Could not decode image');
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001226 return null;
1227 }
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001228 return img;
1229}
1230
Kevin Lubickeda0b432019-12-02 08:26:48 -05001231// pixels must be a Uint8Array with bytes representing the pixel values
1232// (e.g. each set of 4 bytes could represent RGBA values for a single pixel).
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001233CanvasKit.MakeImage = function(pixels, width, height, alphaType, colorType) {
Kevin Lubickeda0b432019-12-02 08:26:48 -05001234 var bytesPerPixel = pixels.length / (width * height);
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001235 var info = {
1236 'width': width,
1237 'height': height,
1238 'alphaType': alphaType,
1239 'colorType': colorType,
1240 };
Kevin Lubickeda0b432019-12-02 08:26:48 -05001241 var pptr = copy1dArray(pixels, CanvasKit.HEAPU8);
1242 // No need to _free pptr, Image takes it with SkData::MakeFromMalloc
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001243
Kevin Lubickeda0b432019-12-02 08:26:48 -05001244 return CanvasKit._MakeImage(info, pptr, pixels.length, width * bytesPerPixel);
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001245}
1246
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001247CanvasKit.MakeSkVertices = function(mode, positions, textureCoordinates, colors,
Mike Reed5caf9352020-03-02 14:57:09 -05001248 indices, isVolatile) {
Kevin Lubickb3574c92019-03-06 08:25:36 -05001249 // Default isVolitile to true if not set
1250 isVolatile = isVolatile === undefined ? true : isVolatile;
Kevin Lubickd6ba7252019-06-03 14:38:05 -04001251 var idxCount = (indices && indices.length) || 0;
1252
1253 var flags = 0;
1254 // These flags are from SkVertices.h and should be kept in sync with those.
1255 if (textureCoordinates && textureCoordinates.length) {
1256 flags |= (1 << 0);
1257 }
1258 if (colors && colors.length) {
1259 flags |= (1 << 1);
1260 }
Kevin Lubickd6ba7252019-06-03 14:38:05 -04001261 if (!isVolatile) {
Mike Reed5caf9352020-03-02 14:57:09 -05001262 flags |= (1 << 2);
Kevin Lubickd6ba7252019-06-03 14:38:05 -04001263 }
1264
1265 var builder = new CanvasKit._SkVerticesBuilder(mode, positions.length, idxCount, flags);
1266
1267 copy2dArray(positions, CanvasKit.HEAPF32, builder.positions());
1268 if (builder.texCoords()) {
1269 copy2dArray(textureCoordinates, CanvasKit.HEAPF32, builder.texCoords());
1270 }
1271 if (builder.colors()) {
1272 copy1dArray(colors, CanvasKit.HEAPU32, builder.colors());
1273 }
Kevin Lubickd6ba7252019-06-03 14:38:05 -04001274 if (builder.indices()) {
1275 copy1dArray(indices, CanvasKit.HEAPU16, builder.indices());
1276 }
Kevin Lubickb3574c92019-03-06 08:25:36 -05001277
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001278 var idxCount = (indices && indices.length) || 0;
Kevin Lubickd6ba7252019-06-03 14:38:05 -04001279 // Create the vertices, which owns the memory that the builder had allocated.
1280 return builder.detach();
Kevin Lubicka4f218d2020-01-14 08:39:09 -05001281};