blob: 0b95c69098a5e600f9efcb270b855b7cd0870d67 [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 }
217 CanvasKit.SkVector.normalize = function(v) {
218 return CanvasKit.SkVector.mulScalar(v, 1/CanvasKit.SkVector.length(v));
219 }
220 CanvasKit.SkVector.cross = function(a, b) {
221 if (skIsDebug && (a.length !== 3 || a.length !== 3)) {
222 throw 'Cross product is only defined for 3-dimensional vectors (a.length='+a.length+', b.length='+b.length+')';
223 }
224 return [
225 a[1]*b[2] - a[2]*b[1],
226 a[2]*b[0] - a[0]*b[2],
227 a[0]*b[1] - a[1]*b[0],
228 ];
229 }
230
231 // Functions for creating and manipulating 4x4 matrices. Accepted in place of SkM44 in canvas
232 // methods, for the same reasons as the 3x3 matrices above.
233 // ported from C++ code in SkM44.cpp
234 CanvasKit.SkM44 = {};
235 // Create a 4x4 identity matrix
236 CanvasKit.SkM44.identity = function() {
237 return identityN(4);
238 }
239
240 // Anything named vec below is an array of length 3 representing a vector/point in 3D space.
241 // Create a 4x4 matrix representing a translate by the provided 3-vec
242 CanvasKit.SkM44.translated = function(vec) {
243 return stride(vec, identityN(4), 4, 3, 0);
244 }
245 // Create a 4x4 matrix representing a scaling by the provided 3-vec
246 CanvasKit.SkM44.scaled = function(vec) {
247 return stride(vec, identityN(4), 4, 0, 1);
248 }
249 // Create a 4x4 matrix representing a rotation about the provided axis 3-vec.
250 // axis does not need to be normalized.
251 CanvasKit.SkM44.rotated = function(axisVec, radians) {
252 return CanvasKit.SkM44.rotatedUnitSinCos(
253 CanvasKit.SkVector.normalize(axisVec), Math.sin(radians), Math.cos(radians));
254 }
255 // Create a 4x4 matrix representing a rotation about the provided normalized axis 3-vec.
256 // Rotation is provided redundantly as both sin and cos values.
257 // This rotate can be used when you already have the cosAngle and sinAngle values
258 // so you don't have to atan(cos/sin) to call roatated() which expects an angle in radians.
259 // this does no checking! Behavior for invalid sin or cos values or non-normalized axis vectors
260 // is incorrect. Prefer rotate().
261 CanvasKit.SkM44.rotatedUnitSinCos = function(axisVec, sinAngle, cosAngle) {
262 var x = axisVec[0];
263 var y = axisVec[1];
264 var z = axisVec[2];
265 var c = cosAngle;
266 var s = sinAngle;
267 var t = 1 - c;
268 return [
269 t*x*x + c, t*x*y - s*z, t*x*z + s*y, 0,
270 t*x*y + s*z, t*y*y + c, t*y*z - s*x, 0,
271 t*x*z - s*y, t*y*z + s*x, t*z*z + c, 0,
272 0, 0, 0, 1
273 ];
274 }
275 // Create a 4x4 matrix representing a camera at eyeVec, pointed at centerVec.
276 CanvasKit.SkM44.lookat = function(eyeVec, centerVec, upVec) {
277 var f = CanvasKit.SkVector.normalize(CanvasKit.SkVector.sub(centerVec, eyeVec));
278 var u = CanvasKit.SkVector.normalize(upVec);
279 var s = CanvasKit.SkVector.normalize(CanvasKit.SkVector.cross(f, u));
280
281 var m = CanvasKit.SkM44.identity();
282 // set each column's top three numbers
283 stride(s, m, 4, 0, 0);
284 stride(CanvasKit.SkVector.cross(s, f), m, 4, 1, 0);
285 stride(CanvasKit.SkVector.mulScalar(f, -1), m, 4, 2, 0);
286 stride(eyeVec, m, 4, 3, 0);
287
288 var m2 = CanvasKit.SkM44.invert(m);
289 if (m2 === null) {
290 return CanvasKit.SkM44.identity();
291 }
292 return m2;
293 }
294 // Create a 4x4 matrix representing a perspective. All arguments are scalars.
295 // angle is in radians.
296 CanvasKit.SkM44.perspective = function(near, far, angle) {
297 if (skIsDebug && (far <= near)) {
298 throw "far must be greater than near when constructing SkM44 using perspective.";
299 }
300 var dInv = 1 / (far - near);
301 var halfAngle = angle / 2;
302 var cot = Math.cos(halfAngle) / Math.sin(halfAngle);
303 return [
304 cot, 0, 0, 0,
305 0, cot, 0, 0,
306 0, 0, (far+near)*dInv, 2*far*near*dInv,
307 0, 0, -1, 1,
308 ];
309 }
310 // Returns the number at the given row and column in matrix m.
311 CanvasKit.SkM44.rc = function(m, r, c) {
312 return m[r*4+c];
313 }
314 // Accepts any number of 4x4 matrix arguments, multiplies them left to right.
315 CanvasKit.SkM44.multiply = function() {
316 return multiplyMany(4, arguments);
317 }
318
319 // Invert the 4x4 matrix if it is invertible and return it. if not, return null.
320 // taken from SkM44.cpp (altered to use row-major order)
321 // m is not altered.
322 CanvasKit.SkM44.invert = function(m) {
323 if (skIsDebug && !m.every(isnumber)) {
324 throw 'some members of matrix are NaN m='+m;
325 }
326
327 var a00 = m[0];
328 var a01 = m[4];
329 var a02 = m[8];
330 var a03 = m[12];
331 var a10 = m[1];
332 var a11 = m[5];
333 var a12 = m[9];
334 var a13 = m[13];
335 var a20 = m[2];
336 var a21 = m[6];
337 var a22 = m[10];
338 var a23 = m[14];
339 var a30 = m[3];
340 var a31 = m[7];
341 var a32 = m[11];
342 var a33 = m[15];
343
344 var b00 = a00 * a11 - a01 * a10;
345 var b01 = a00 * a12 - a02 * a10;
346 var b02 = a00 * a13 - a03 * a10;
347 var b03 = a01 * a12 - a02 * a11;
348 var b04 = a01 * a13 - a03 * a11;
349 var b05 = a02 * a13 - a03 * a12;
350 var b06 = a20 * a31 - a21 * a30;
351 var b07 = a20 * a32 - a22 * a30;
352 var b08 = a20 * a33 - a23 * a30;
353 var b09 = a21 * a32 - a22 * a31;
354 var b10 = a21 * a33 - a23 * a31;
355 var b11 = a22 * a33 - a23 * a32;
356
357 // calculate determinate
358 var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
359 var invdet = 1.0 / det;
360
361 // bail out if the matrix is not invertible
362 if (det === 0 || invdet === Infinity) {
363 SkDebug('Warning, uninvertible matrix');
364 return null;
365 }
366
367 b00 *= invdet;
368 b01 *= invdet;
369 b02 *= invdet;
370 b03 *= invdet;
371 b04 *= invdet;
372 b05 *= invdet;
373 b06 *= invdet;
374 b07 *= invdet;
375 b08 *= invdet;
376 b09 *= invdet;
377 b10 *= invdet;
378 b11 *= invdet;
379
380 // store result in row major order
381 var tmp = [
382 a11 * b11 - a12 * b10 + a13 * b09,
383 a12 * b08 - a10 * b11 - a13 * b07,
384 a10 * b10 - a11 * b08 + a13 * b06,
385 a11 * b07 - a10 * b09 - a12 * b06,
386
387 a02 * b10 - a01 * b11 - a03 * b09,
388 a00 * b11 - a02 * b08 + a03 * b07,
389 a01 * b08 - a00 * b10 - a03 * b06,
390 a00 * b09 - a01 * b07 + a02 * b06,
391
392 a31 * b05 - a32 * b04 + a33 * b03,
393 a32 * b02 - a30 * b05 - a33 * b01,
394 a30 * b04 - a31 * b02 + a33 * b00,
395 a31 * b01 - a30 * b03 - a32 * b00,
396
397 a22 * b04 - a21 * b05 - a23 * b03,
398 a20 * b05 - a22 * b02 + a23 * b01,
399 a21 * b02 - a20 * b04 - a23 * b00,
400 a20 * b03 - a21 * b01 + a22 * b00,
401 ];
402
403
404 if (!tmp.every(function(val) { return val !== NaN && val !== Infinity && val !== -Infinity; })) {
405 SkDebug('inverted matrix contains infinities or NaN '+tmp);
406 return null;
407 }
408 return tmp;
409 }
410
411
Kevin Lubickd3729342019-09-12 11:11:25 -0400412 // An SkColorMatrix is a 4x4 color matrix that transforms the 4 color channels
413 // with a 1x4 matrix that post-translates those 4 channels.
414 // For example, the following is the layout with the scale (S) and post-transform
415 // (PT) items indicated.
416 // RS, 0, 0, 0 | RPT
417 // 0, GS, 0, 0 | GPT
418 // 0, 0, BS, 0 | BPT
419 // 0, 0, 0, AS | APT
420 //
421 // Much of this was hand-transcribed from SkColorMatrix.cpp, because it's easier to
422 // deal with a Float32Array of length 20 than to try to expose the SkColorMatrix object.
423
Kevin Lubickd3729342019-09-12 11:11:25 -0400424 var rPostTrans = 4;
425 var gPostTrans = 9;
426 var bPostTrans = 14;
427 var aPostTrans = 19;
428
429 CanvasKit.SkColorMatrix = {};
430 CanvasKit.SkColorMatrix.identity = function() {
Nathaniel Nifong77798b42020-02-21 17:15:22 -0500431 return Float32Array.of([
432 1, 0, 0, 0, 0,
433 0, 1, 0, 0, 0,
434 0, 0, 1, 0, 0,
435 0, 0, 0, 1, 0,
436 ]);
Kevin Lubickd3729342019-09-12 11:11:25 -0400437 }
438
439 CanvasKit.SkColorMatrix.scaled = function(rs, gs, bs, as) {
Nathaniel Nifong77798b42020-02-21 17:15:22 -0500440 return Float32Array.of([
441 rs, 0, 0, 0, 0,
442 0, gs, 0, 0, 0,
443 0, 0, bs, 0, 0,
444 0, 0, 0, as, 0,
445 ]);
Kevin Lubickd3729342019-09-12 11:11:25 -0400446 }
447
448 var rotateIndices = [
449 [6, 7, 11, 12],
450 [0, 10, 2, 12],
451 [0, 1, 5, 6],
452 ];
453 // axis should be 0, 1, 2 for r, g, b
454 CanvasKit.SkColorMatrix.rotated = function(axis, sine, cosine) {
455 var m = CanvasKit.SkColorMatrix.identity();
456 var indices = rotateIndices[axis];
457 m[indices[0]] = cosine;
458 m[indices[1]] = sine;
459 m[indices[2]] = -sine;
460 m[indices[3]] = cosine;
461 return m;
462 }
463
464 // m is a SkColorMatrix (i.e. a Float32Array), and this sets the 4 "special"
465 // params that will translate the colors after they are multiplied by the 4x4 matrix.
466 CanvasKit.SkColorMatrix.postTranslate = function(m, dr, dg, db, da) {
467 m[rPostTrans] += dr;
468 m[gPostTrans] += dg;
469 m[bPostTrans] += db;
470 m[aPostTrans] += da;
471 return m;
472 }
473
474 // concat returns a new SkColorMatrix that is the result of multiplying outer*inner;
475 CanvasKit.SkColorMatrix.concat = function(outer, inner) {
476 var m = new Float32Array(20);
477 var index = 0;
478 for (var j = 0; j < 20; j += 5) {
479 for (var i = 0; i < 4; i++) {
480 m[index++] = outer[j + 0] * inner[i + 0] +
481 outer[j + 1] * inner[i + 5] +
482 outer[j + 2] * inner[i + 10] +
483 outer[j + 3] * inner[i + 15];
484 }
485 m[index++] = outer[j + 0] * inner[4] +
486 outer[j + 1] * inner[9] +
487 outer[j + 2] * inner[14] +
488 outer[j + 3] * inner[19] +
489 outer[j + 4];
490 }
491
492 return m;
493 }
494
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500495 CanvasKit.SkPath.prototype.addArc = function(oval, startAngle, sweepAngle) {
496 // see arc() for the HTMLCanvas version
497 // note input angles are degrees.
498 this._addArc(oval, startAngle, sweepAngle);
499 return this;
500 };
Kevin Lubick217056c2018-09-20 17:39:31 -0400501
Kevin Lubicke384df42019-08-26 15:48:09 -0400502 CanvasKit.SkPath.prototype.addOval = function(oval, isCCW, startIndex) {
503 if (startIndex === undefined) {
504 startIndex = 1;
505 }
506 this._addOval(oval, !!isCCW, startIndex);
507 return this;
508 };
509
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500510 CanvasKit.SkPath.prototype.addPath = function() {
511 // Takes 1, 2, 7, or 10 required args, where the first arg is always the path.
512 // The last arg is optional and chooses between add or extend mode.
513 // The options for the remaining args are:
514 // - an array of 6 or 9 parameters (perspective is optional)
515 // - the 9 parameters of a full matrix or
516 // the 6 non-perspective params of a matrix.
517 var args = Array.prototype.slice.call(arguments);
518 var path = args[0];
519 var extend = false;
520 if (typeof args[args.length-1] === "boolean") {
521 extend = args.pop();
522 }
523 if (args.length === 1) {
524 // Add path, unchanged. Use identity matrix
525 this._addPath(path, 1, 0, 0,
526 0, 1, 0,
527 0, 0, 1,
528 extend);
529 } else if (args.length === 2) {
530 // User provided the 9 params of a full matrix as an array.
531 var a = args[1];
532 this._addPath(path, a[0], a[1], a[2],
533 a[3], a[4], a[5],
534 a[6] || 0, a[7] || 0, a[8] || 1,
535 extend);
536 } else if (args.length === 7 || args.length === 10) {
537 // User provided the 9 params of a (full) matrix directly.
538 // (or just the 6 non perspective ones)
539 // These are in the same order as what Skia expects.
540 var a = args;
541 this._addPath(path, a[1], a[2], a[3],
542 a[4], a[5], a[6],
543 a[7] || 0, a[8] || 0, a[9] || 1,
544 extend);
545 } else {
546 SkDebug('addPath expected to take 1, 2, 7, or 10 required args. Got ' + args.length);
Kevin Lubickb5ae3b52018-11-03 07:51:19 -0400547 return null;
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500548 }
549 return this;
550 };
Kevin Lubickb5ae3b52018-11-03 07:51:19 -0400551
Kevin Lubick37ab53e2019-11-11 10:06:08 -0500552 // points is either an array of [x, y] where x and y are numbers or
553 // a typed array from Malloc where the even indices will be treated
554 // as x coordinates and the odd indices will be treated as y coordinates.
555 CanvasKit.SkPath.prototype.addPoly = function(points, close) {
556 var ptr;
557 var n;
558 // This was created with CanvasKit.Malloc, so assume the user has
559 // already been filled with data.
560 if (points['_ck']) {
561 ptr = points.byteOffset;
562 n = points.length/2;
563 } else {
564 ptr = copy2dArray(points, CanvasKit.HEAPF32);
565 n = points.length;
566 }
567 this._addPoly(ptr, n, close);
568 CanvasKit._free(ptr);
569 return this;
570 };
571
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500572 CanvasKit.SkPath.prototype.addRect = function() {
573 // Takes 1, 2, 4 or 5 args
574 // - SkRect
575 // - SkRect, isCCW
576 // - left, top, right, bottom
577 // - left, top, right, bottom, isCCW
578 if (arguments.length === 1 || arguments.length === 2) {
579 var r = arguments[0];
580 var ccw = arguments[1] || false;
581 this._addRect(r.fLeft, r.fTop, r.fRight, r.fBottom, ccw);
582 } else if (arguments.length === 4 || arguments.length === 5) {
583 var a = arguments;
584 this._addRect(a[0], a[1], a[2], a[3], a[4] || false);
585 } else {
586 SkDebug('addRect expected to take 1, 2, 4, or 5 args. Got ' + arguments.length);
Kevin Lubick217056c2018-09-20 17:39:31 -0400587 return null;
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500588 }
589 return this;
590 };
Kevin Lubick217056c2018-09-20 17:39:31 -0400591
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500592 CanvasKit.SkPath.prototype.addRoundRect = function() {
593 // Takes 3, 4, 6 or 7 args
594 // - SkRect, radii, ccw
595 // - SkRect, rx, ry, ccw
596 // - left, top, right, bottom, radii, ccw
597 // - left, top, right, bottom, rx, ry, ccw
598 var args = arguments;
599 if (args.length === 3 || args.length === 6) {
600 var radii = args[args.length-2];
601 } else if (args.length === 6 || args.length === 7){
602 // duplicate the given (rx, ry) pairs for each corner.
603 var rx = args[args.length-3];
604 var ry = args[args.length-2];
605 var radii = [rx, ry, rx, ry, rx, ry, rx, ry];
606 } else {
607 SkDebug('addRoundRect expected to take 3, 4, 6, or 7 args. Got ' + args.length);
608 return null;
609 }
610 if (radii.length !== 8) {
611 SkDebug('addRoundRect needs 8 radii provided. Got ' + radii.length);
612 return null;
613 }
614 var rptr = copy1dArray(radii, CanvasKit.HEAPF32);
615 if (args.length === 3 || args.length === 4) {
616 var r = args[0];
617 var ccw = args[args.length - 1];
618 this._addRoundRect(r.fLeft, r.fTop, r.fRight, r.fBottom, rptr, ccw);
619 } else if (args.length === 6 || args.length === 7) {
620 var a = args;
621 this._addRoundRect(a[0], a[1], a[2], a[3], rptr, ccw);
622 }
623 CanvasKit._free(rptr);
624 return this;
625 };
626
627 CanvasKit.SkPath.prototype.arc = function(x, y, radius, startAngle, endAngle, ccw) {
628 // emulates the HTMLCanvas behavior. See addArc() for the SkPath version.
629 // Note input angles are radians.
630 var bounds = CanvasKit.LTRBRect(x-radius, y-radius, x+radius, y+radius);
631 var sweep = radiansToDegrees(endAngle - startAngle) - (360 * !!ccw);
632 var temp = new CanvasKit.SkPath();
633 temp.addArc(bounds, radiansToDegrees(startAngle), sweep);
634 this.addPath(temp, true);
635 temp.delete();
636 return this;
637 };
638
639 CanvasKit.SkPath.prototype.arcTo = function() {
640 // takes 4, 5 or 7 args
641 // - 5 x1, y1, x2, y2, radius
642 // - 4 oval (as Rect), startAngle, sweepAngle, forceMoveTo
Kevin Lubicke384df42019-08-26 15:48:09 -0400643 // - 7 rx, ry, xAxisRotate, useSmallArc, isCCW, x, y
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500644 var args = arguments;
645 if (args.length === 5) {
646 this._arcTo(args[0], args[1], args[2], args[3], args[4]);
647 } else if (args.length === 4) {
648 this._arcTo(args[0], args[1], args[2], args[3]);
649 } else if (args.length === 7) {
Kevin Lubicke384df42019-08-26 15:48:09 -0400650 this._arcTo(args[0], args[1], args[2], !!args[3], !!args[4], args[5], args[6]);
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500651 } else {
652 throw 'Invalid args for arcTo. Expected 4, 5, or 7, got '+ args.length;
653 }
654
655 return this;
656 };
657
658 CanvasKit.SkPath.prototype.close = function() {
659 this._close();
660 return this;
661 };
662
663 CanvasKit.SkPath.prototype.conicTo = function(x1, y1, x2, y2, w) {
664 this._conicTo(x1, y1, x2, y2, w);
665 return this;
666 };
667
668 CanvasKit.SkPath.prototype.cubicTo = function(cp1x, cp1y, cp2x, cp2y, x, y) {
669 this._cubicTo(cp1x, cp1y, cp2x, cp2y, x, y);
670 return this;
671 };
672
673 CanvasKit.SkPath.prototype.dash = function(on, off, phase) {
674 if (this._dash(on, off, phase)) {
Kevin Lubick217056c2018-09-20 17:39:31 -0400675 return this;
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500676 }
677 return null;
678 };
Kevin Lubick217056c2018-09-20 17:39:31 -0400679
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500680 CanvasKit.SkPath.prototype.lineTo = function(x, y) {
681 this._lineTo(x, y);
682 return this;
683 };
Kevin Lubick217056c2018-09-20 17:39:31 -0400684
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500685 CanvasKit.SkPath.prototype.moveTo = function(x, y) {
686 this._moveTo(x, y);
687 return this;
688 };
Kevin Lubickb5ae3b52018-11-03 07:51:19 -0400689
Kevin Lubicke384df42019-08-26 15:48:09 -0400690 CanvasKit.SkPath.prototype.offset = function(dx, dy) {
691 this._transform(1, 0, dx,
692 0, 1, dy,
693 0, 0, 1);
694 return this;
695 };
696
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500697 CanvasKit.SkPath.prototype.quadTo = function(cpx, cpy, x, y) {
698 this._quadTo(cpx, cpy, x, y);
699 return this;
700 };
701
Kevin Lubick79b71342019-11-01 14:36:52 -0400702 CanvasKit.SkPath.prototype.rArcTo = function(rx, ry, xAxisRotate, useSmallArc, isCCW, dx, dy) {
703 this._rArcTo(rx, ry, xAxisRotate, useSmallArc, isCCW, dx, dy);
704 return this;
705 };
706
707 CanvasKit.SkPath.prototype.rConicTo = function(dx1, dy1, dx2, dy2, w) {
708 this._rConicTo(dx1, dy1, dx2, dy2, w);
709 return this;
710 };
711
712 // These params are all relative
713 CanvasKit.SkPath.prototype.rCubicTo = function(cp1x, cp1y, cp2x, cp2y, x, y) {
714 this._rCubicTo(cp1x, cp1y, cp2x, cp2y, x, y);
715 return this;
716 };
717
718 CanvasKit.SkPath.prototype.rLineTo = function(dx, dy) {
719 this._rLineTo(dx, dy);
720 return this;
721 };
722
723 CanvasKit.SkPath.prototype.rMoveTo = function(dx, dy) {
724 this._rMoveTo(dx, dy);
725 return this;
726 };
727
728 // These params are all relative
729 CanvasKit.SkPath.prototype.rQuadTo = function(cpx, cpy, x, y) {
730 this._rQuadTo(cpx, cpy, x, y);
731 return this;
732 };
733
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500734 CanvasKit.SkPath.prototype.stroke = function(opts) {
735 // Fill out any missing values with the default values.
736 /**
737 * See externs.js for this definition
738 * @type {StrokeOpts}
739 */
740 opts = opts || {};
741 opts.width = opts.width || 1;
742 opts.miter_limit = opts.miter_limit || 4;
743 opts.cap = opts.cap || CanvasKit.StrokeCap.Butt;
744 opts.join = opts.join || CanvasKit.StrokeJoin.Miter;
745 opts.precision = opts.precision || 1;
746 if (this._stroke(opts)) {
747 return this;
748 }
749 return null;
750 };
751
752 CanvasKit.SkPath.prototype.transform = function() {
753 // Takes 1 or 9 args
754 if (arguments.length === 1) {
755 // argument 1 should be a 6 or 9 element array.
756 var a = arguments[0];
757 this._transform(a[0], a[1], a[2],
758 a[3], a[4], a[5],
759 a[6] || 0, a[7] || 0, a[8] || 1);
760 } else if (arguments.length === 6 || arguments.length === 9) {
761 // these arguments are the 6 or 9 members of the matrix
762 var a = arguments;
763 this._transform(a[0], a[1], a[2],
764 a[3], a[4], a[5],
765 a[6] || 0, a[7] || 0, a[8] || 1);
766 } else {
767 throw 'transform expected to take 1 or 9 arguments. Got ' + arguments.length;
768 }
769 return this;
770 };
771 // isComplement is optional, defaults to false
772 CanvasKit.SkPath.prototype.trim = function(startT, stopT, isComplement) {
773 if (this._trim(startT, stopT, !!isComplement)) {
774 return this;
775 }
776 return null;
777 };
778
779 // bones should be a 3d array.
780 // Each bone is a 3x2 transformation matrix in column major order:
781 // | scaleX skewX transX |
782 // | skewY scaleY transY |
783 // and bones is an array of those matrices.
784 // Returns a copy of this (SkVertices) with the bones applied.
785 CanvasKit.SkVertices.prototype.applyBones = function(bones) {
786 var bPtr = copy3dArray(bones, CanvasKit.HEAPF32);
787 var vert = this._applyBones(bPtr, bones.length);
788 CanvasKit._free(bPtr);
789 return vert;
790 }
791
792 CanvasKit.SkImage.prototype.encodeToData = function() {
793 if (!arguments.length) {
794 return this._encodeToData();
Kevin Lubickb5ae3b52018-11-03 07:51:19 -0400795 }
Kevin Lubick53965c92018-10-11 08:51:55 -0400796
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500797 if (arguments.length === 2) {
798 var a = arguments;
799 return this._encodeToDataWithFormat(a[0], a[1]);
Alexander Khovansky3e119332018-11-15 02:01:19 +0300800 }
801
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500802 throw 'encodeToData expected to take 0 or 2 arguments. Got ' + arguments.length;
803 }
Kevin Lubick1ba9c4d2019-02-22 10:04:06 -0500804
Kevin Lubicka064c282019-04-04 09:28:53 -0400805 CanvasKit.SkImage.prototype.makeShader = function(xTileMode, yTileMode, localMatrix) {
806 if (localMatrix) {
807 // Add perspective args if not provided.
808 if (localMatrix.length === 6) {
809 localMatrix.push(0, 0, 1);
810 }
811 return this._makeShader(xTileMode, yTileMode, localMatrix);
812 } else {
813 return this._makeShader(xTileMode, yTileMode);
814 }
815 }
816
Kevin Lubickd6b32ed2019-05-06 13:04:03 -0400817 CanvasKit.SkImage.prototype.readPixels = function(imageInfo, srcX, srcY) {
818 var rowBytes;
Kevin Lubick319524b2020-01-22 15:29:14 -0500819 // Important to use ["string"] notation here, otherwise the closure compiler will
820 // minify away the colorType.
821 switch (imageInfo["colorType"]) {
Kevin Lubickd6b32ed2019-05-06 13:04:03 -0400822 case CanvasKit.ColorType.RGBA_8888:
823 rowBytes = imageInfo.width * 4; // 1 byte per channel == 4 bytes per pixel in 8888
824 break;
825 case CanvasKit.ColorType.RGBA_F32:
826 rowBytes = imageInfo.width * 16; // 4 bytes per channel == 16 bytes per pixel in F32
827 break;
828 default:
829 SkDebug("Colortype not yet supported");
830 return;
831 }
832 var pBytes = rowBytes * imageInfo.height;
833 var pPtr = CanvasKit._malloc(pBytes);
834
835 if (!this._readPixels(imageInfo, pPtr, rowBytes, srcX, srcY)) {
836 SkDebug("Could not read pixels with the given inputs");
837 return null;
838 }
839
840 // Put those pixels into a typed array of the right format and then
841 // make a copy with slice() that we can return.
842 var retVal = null;
Kevin Lubick319524b2020-01-22 15:29:14 -0500843 switch (imageInfo["colorType"]) {
Kevin Lubickd6b32ed2019-05-06 13:04:03 -0400844 case CanvasKit.ColorType.RGBA_8888:
Bryce Thomas1fa54042020-01-14 13:46:30 -0800845 retVal = new Uint8Array(CanvasKit.HEAPU8.buffer, pPtr, pBytes).slice();
Kevin Lubickd6b32ed2019-05-06 13:04:03 -0400846 break;
847 case CanvasKit.ColorType.RGBA_F32:
Bryce Thomas1fa54042020-01-14 13:46:30 -0800848 retVal = new Float32Array(CanvasKit.HEAPU8.buffer, pPtr, pBytes).slice();
Kevin Lubickd6b32ed2019-05-06 13:04:03 -0400849 break;
850 }
851
852 // Free the allocated pixels in the WASM memory
853 CanvasKit._free(pPtr);
854 return retVal;
855
856 }
857
Kevin Lubickee91c072019-03-29 10:39:52 -0400858 // atlas is an SkImage, e.g. from CanvasKit.MakeImageFromEncoded
859 // srcRects and dstXforms should be CanvasKit.SkRectBuilder and CanvasKit.RSXFormBuilder
860 // or just arrays of floats in groups of 4.
861 // colors, if provided, should be a CanvasKit.SkColorBuilder or array of SkColor
862 // (from CanvasKit.Color)
863 CanvasKit.SkCanvas.prototype.drawAtlas = function(atlas, srcRects, dstXforms, paint,
864 /*optional*/ blendMode, colors) {
865 if (!atlas || !paint || !srcRects || !dstXforms) {
866 SkDebug('Doing nothing since missing a required input');
867 return;
868 }
869 if (srcRects.length !== dstXforms.length || (colors && colors.length !== dstXforms.length)) {
870 SkDebug('Doing nothing since input arrays length mismatches');
871 }
872 if (!blendMode) {
873 blendMode = CanvasKit.BlendMode.SrcOver;
874 }
875
876 var srcRectPtr;
877 if (srcRects.build) {
878 srcRectPtr = srcRects.build();
879 } else {
880 srcRectPtr = copy1dArray(srcRects, CanvasKit.HEAPF32);
881 }
882
883 var dstXformPtr;
884 if (dstXforms.build) {
885 dstXformPtr = dstXforms.build();
886 } else {
887 dstXformPtr = copy1dArray(dstXforms, CanvasKit.HEAPF32);
888 }
889
890 var colorPtr = 0; // enscriptem doesn't like undefined for nullptr
891 if (colors) {
892 if (colors.build) {
893 colorPtr = colors.build();
894 } else {
895 colorPtr = copy1dArray(colors, CanvasKit.HEAPU32);
896 }
897 }
898
899 this._drawAtlas(atlas, dstXformPtr, srcRectPtr, colorPtr, dstXforms.length,
900 blendMode, paint);
901
902 if (srcRectPtr && !srcRects.build) {
903 CanvasKit._free(srcRectPtr);
904 }
905 if (dstXformPtr && !dstXforms.build) {
906 CanvasKit._free(dstXformPtr);
907 }
908 if (colorPtr && !colors.build) {
909 CanvasKit._free(colorPtr);
910 }
911
912 }
913
Kevin Lubick37ab53e2019-11-11 10:06:08 -0500914 // points is either an array of [x, y] where x and y are numbers or
915 // a typed array from Malloc where the even indices will be treated
916 // as x coordinates and the odd indices will be treated as y coordinates.
917 CanvasKit.SkCanvas.prototype.drawPoints = function(mode, points, paint) {
918 var ptr;
919 var n;
920 // This was created with CanvasKit.Malloc, so assume the user has
921 // already been filled with data.
922 if (points['_ck']) {
923 ptr = points.byteOffset;
924 n = points.length/2;
925 } else {
926 ptr = copy2dArray(points, CanvasKit.HEAPF32);
927 n = points.length;
928 }
929 this._drawPoints(mode, ptr, n, paint);
930 CanvasKit._free(ptr);
931 }
932
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500933 // returns Uint8Array
934 CanvasKit.SkCanvas.prototype.readPixels = function(x, y, w, h, alphaType,
935 colorType, dstRowBytes) {
936 // supply defaults (which are compatible with HTMLCanvas's getImageData)
937 alphaType = alphaType || CanvasKit.AlphaType.Unpremul;
938 colorType = colorType || CanvasKit.ColorType.RGBA_8888;
939 dstRowBytes = dstRowBytes || (4 * w);
940
941 var len = h * dstRowBytes
942 var pptr = CanvasKit._malloc(len);
943 var ok = this._readPixels({
944 'width': w,
945 'height': h,
Kevin Lubick52b9f372018-12-04 13:57:36 -0500946 'colorType': colorType,
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500947 'alphaType': alphaType,
948 }, pptr, dstRowBytes, x, y);
949 if (!ok) {
950 CanvasKit._free(pptr);
951 return null;
952 }
953
954 // The first typed array is just a view into memory. Because we will
955 // be free-ing that, we call slice to make a persistent copy.
Bryce Thomas1fa54042020-01-14 13:46:30 -0800956 var pixels = new Uint8Array(CanvasKit.HEAPU8.buffer, pptr, len).slice();
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500957 CanvasKit._free(pptr);
958 return pixels;
959 }
960
961 // pixels is a TypedArray. No matter the input size, it will be treated as
962 // a Uint8Array (essentially, a byte array).
963 CanvasKit.SkCanvas.prototype.writePixels = function(pixels, srcWidth, srcHeight,
964 destX, destY, alphaType, colorType) {
965 if (pixels.byteLength % (srcWidth * srcHeight)) {
966 throw 'pixels length must be a multiple of the srcWidth * srcHeight';
967 }
968 var bytesPerPixel = pixels.byteLength / (srcWidth * srcHeight);
969 // supply defaults (which are compatible with HTMLCanvas's putImageData)
970 alphaType = alphaType || CanvasKit.AlphaType.Unpremul;
971 colorType = colorType || CanvasKit.ColorType.RGBA_8888;
972 var srcRowBytes = bytesPerPixel * srcWidth;
973
Kevin Lubick52b9f372018-12-04 13:57:36 -0500974 var pptr = CanvasKit._malloc(pixels.byteLength);
975 CanvasKit.HEAPU8.set(pixels, pptr);
Kevin Lubick52b9f372018-12-04 13:57:36 -0500976
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500977 var ok = this._writePixels({
978 'width': srcWidth,
979 'height': srcHeight,
980 'colorType': colorType,
981 'alphaType': alphaType,
982 }, pptr, srcRowBytes, destX, destY);
983
984 CanvasKit._free(pptr);
985 return ok;
Kevin Lubick52b9f372018-12-04 13:57:36 -0500986 }
987
Kevin Lubickd3729342019-09-12 11:11:25 -0400988 // colorMatrix is an SkColorMatrix (e.g. Float32Array of length 20)
989 CanvasKit.SkColorFilter.MakeMatrix = function(colorMatrix) {
990 if (!colorMatrix || colorMatrix.length !== 20) {
991 SkDebug('ignoring invalid color matrix');
992 return;
993 }
994 var fptr = copy1dArray(colorMatrix, CanvasKit.HEAPF32);
995 // We know skia memcopies the floats, so we can free our memory after the call returns.
996 var m = CanvasKit.SkColorFilter._makeMatrix(fptr);
997 CanvasKit._free(fptr);
998 return m;
999 }
1000
Kevin Lubick62836902019-12-09 09:04:26 -05001001 CanvasKit.SkShader.Blend = function(mode, dst, src, localMatrix) {
1002 if (!localMatrix) {
1003 return this._Blend(mode, dst, src);
1004 }
1005 return this._Blend(mode, dst, src, localMatrix);
1006 }
1007
1008 CanvasKit.SkShader.Lerp = function(t, dst, src, localMatrix) {
1009 if (!localMatrix) {
1010 return this._Lerp(t, dst, src);
1011 }
1012 return this._Lerp(t, dst, src, localMatrix);
1013 }
1014
Kevin Lubickcc13fd32019-04-05 13:00:01 -04001015 CanvasKit.SkSurface.prototype.captureFrameAsSkPicture = function(drawFrame) {
1016 // Set up SkPictureRecorder
1017 var spr = new CanvasKit.SkPictureRecorder();
1018 var canvas = spr.beginRecording(
1019 CanvasKit.LTRBRect(0, 0, this.width(), this.height()));
1020 drawFrame(canvas);
1021 var pic = spr.finishRecordingAsPicture();
1022 spr.delete();
1023 // TODO: do we need to clean up the memory for canvas?
1024 // If we delete it here, saveAsFile doesn't work correctly.
1025 return pic;
1026 }
1027
Kevin Lubick359a7e32019-03-19 09:34:37 -04001028 CanvasKit.SkSurface.prototype.requestAnimationFrame = function(callback, dirtyRect) {
1029 if (!this._cached_canvas) {
1030 this._cached_canvas = this.getCanvas();
1031 }
1032 window.requestAnimationFrame(function() {
Kevin Lubick39026282019-03-28 12:46:40 -04001033 if (this._context !== undefined) {
1034 CanvasKit.setCurrentContext(this._context);
1035 }
Kevin Lubick359a7e32019-03-19 09:34:37 -04001036
1037 callback(this._cached_canvas);
1038
Bryce Thomas2c5b8562020-01-22 13:49:41 -08001039 // We do not dispose() of the SkSurface here, as the client will typically
1040 // call requestAnimationFrame again from within the supplied callback.
1041 // For drawing a single frame, prefer drawOnce().
Kevin Lubick359a7e32019-03-19 09:34:37 -04001042 this.flush();
1043 }.bind(this));
1044 }
1045
Kevin Lubick52379332020-01-27 10:01:25 -05001046 // drawOnce will dispose of the surface after drawing the frame using the provided
1047 // callback.
Bryce Thomas2c5b8562020-01-22 13:49:41 -08001048 CanvasKit.SkSurface.prototype.drawOnce = function(callback, dirtyRect) {
1049 if (!this._cached_canvas) {
1050 this._cached_canvas = this.getCanvas();
1051 }
1052 window.requestAnimationFrame(function() {
1053 if (this._context !== undefined) {
1054 CanvasKit.setCurrentContext(this._context);
1055 }
1056 callback(this._cached_canvas);
1057
1058 this.flush();
1059 this.dispose();
1060 }.bind(this));
1061 }
1062
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001063 // Run through the JS files that are added at compile time.
1064 if (CanvasKit._extraInitializations) {
1065 CanvasKit._extraInitializations.forEach(function(init) {
1066 init();
1067 });
Kevin Lubickeb2f6b02018-11-29 15:07:02 -05001068 }
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001069}; // end CanvasKit.onRuntimeInitialized, that is, anything changing prototypes or dynamic.
Kevin Lubickeb2f6b02018-11-29 15:07:02 -05001070
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001071CanvasKit.LTRBRect = function(l, t, r, b) {
1072 return {
1073 fLeft: l,
1074 fTop: t,
1075 fRight: r,
1076 fBottom: b,
1077 };
Kevin Lubick1a05fce2018-11-20 12:51:16 -05001078}
1079
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001080CanvasKit.XYWHRect = function(x, y, w, h) {
1081 return {
1082 fLeft: x,
1083 fTop: y,
1084 fRight: x+w,
1085 fBottom: y+h,
1086 };
Kevin Lubick1a05fce2018-11-20 12:51:16 -05001087}
1088
Kevin Lubick7d644e12019-09-11 14:22:22 -04001089// RRectXY returns an RRect with the given rect and a radiusX and radiusY for
1090// all 4 corners.
1091CanvasKit.RRectXY = function(rect, rx, ry) {
1092 return {
1093 rect: rect,
1094 rx1: rx,
1095 ry1: ry,
1096 rx2: rx,
1097 ry2: ry,
1098 rx3: rx,
1099 ry3: ry,
1100 rx4: rx,
1101 ry4: ry,
1102 };
1103}
1104
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001105CanvasKit.MakePathFromCmds = function(cmds) {
1106 var ptrLen = loadCmdsTypedArray(cmds);
1107 var path = CanvasKit._MakePathFromCmds(ptrLen[0], ptrLen[1]);
1108 CanvasKit._free(ptrLen[0]);
1109 return path;
1110}
1111
1112CanvasKit.MakeSkDashPathEffect = function(intervals, phase) {
1113 if (!phase) {
1114 phase = 0;
1115 }
1116 if (!intervals.length || intervals.length % 2 === 1) {
1117 throw 'Intervals array must have even length';
1118 }
1119 var ptr = copy1dArray(intervals, CanvasKit.HEAPF32);
1120 var dpe = CanvasKit._MakeSkDashPathEffect(ptr, intervals.length, phase);
1121 CanvasKit._free(ptr);
1122 return dpe;
1123}
1124
1125// data is a TypedArray or ArrayBuffer e.g. from fetch().then(resp.arrayBuffer())
Kevin Lubick6b921b72019-09-18 16:18:17 -04001126CanvasKit.MakeAnimatedImageFromEncoded = function(data) {
1127 data = new Uint8Array(data);
1128
1129 var iptr = CanvasKit._malloc(data.byteLength);
1130 CanvasKit.HEAPU8.set(data, iptr);
1131 var img = CanvasKit._decodeAnimatedImage(iptr, data.byteLength);
1132 if (!img) {
1133 SkDebug('Could not decode animated image');
1134 return null;
1135 }
1136 return img;
1137}
1138
1139// data is a TypedArray or ArrayBuffer e.g. from fetch().then(resp.arrayBuffer())
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001140CanvasKit.MakeImageFromEncoded = function(data) {
1141 data = new Uint8Array(data);
1142
1143 var iptr = CanvasKit._malloc(data.byteLength);
1144 CanvasKit.HEAPU8.set(data, iptr);
1145 var img = CanvasKit._decodeImage(iptr, data.byteLength);
1146 if (!img) {
1147 SkDebug('Could not decode image');
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001148 return null;
1149 }
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001150 return img;
1151}
1152
Kevin Lubickeda0b432019-12-02 08:26:48 -05001153// pixels must be a Uint8Array with bytes representing the pixel values
1154// (e.g. each set of 4 bytes could represent RGBA values for a single pixel).
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001155CanvasKit.MakeImage = function(pixels, width, height, alphaType, colorType) {
Kevin Lubickeda0b432019-12-02 08:26:48 -05001156 var bytesPerPixel = pixels.length / (width * height);
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001157 var info = {
1158 'width': width,
1159 'height': height,
1160 'alphaType': alphaType,
1161 'colorType': colorType,
1162 };
Kevin Lubickeda0b432019-12-02 08:26:48 -05001163 var pptr = copy1dArray(pixels, CanvasKit.HEAPU8);
1164 // No need to _free pptr, Image takes it with SkData::MakeFromMalloc
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001165
Kevin Lubickeda0b432019-12-02 08:26:48 -05001166 return CanvasKit._MakeImage(info, pptr, pixels.length, width * bytesPerPixel);
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001167}
1168
1169CanvasKit.MakeLinearGradientShader = function(start, end, colors, pos, mode, localMatrix, flags) {
Kevin Lubickee91c072019-03-29 10:39:52 -04001170 var colorPtr = copy1dArray(colors, CanvasKit.HEAPU32);
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001171 var posPtr = copy1dArray(pos, CanvasKit.HEAPF32);
1172 flags = flags || 0;
1173
1174 if (localMatrix) {
1175 // Add perspective args if not provided.
1176 if (localMatrix.length === 6) {
1177 localMatrix.push(0, 0, 1);
1178 }
1179 var lgs = CanvasKit._MakeLinearGradientShader(start, end, colorPtr, posPtr,
1180 colors.length, mode, flags, localMatrix);
1181 } else {
1182 var lgs = CanvasKit._MakeLinearGradientShader(start, end, colorPtr, posPtr,
1183 colors.length, mode, flags);
1184 }
1185
1186 CanvasKit._free(colorPtr);
1187 CanvasKit._free(posPtr);
1188 return lgs;
1189}
1190
1191CanvasKit.MakeRadialGradientShader = function(center, radius, colors, pos, mode, localMatrix, flags) {
Kevin Lubickee91c072019-03-29 10:39:52 -04001192 var colorPtr = copy1dArray(colors, CanvasKit.HEAPU32);
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001193 var posPtr = copy1dArray(pos, CanvasKit.HEAPF32);
1194 flags = flags || 0;
1195
1196 if (localMatrix) {
1197 // Add perspective args if not provided.
1198 if (localMatrix.length === 6) {
1199 localMatrix.push(0, 0, 1);
1200 }
1201 var rgs = CanvasKit._MakeRadialGradientShader(center, radius, colorPtr, posPtr,
1202 colors.length, mode, flags, localMatrix);
1203 } else {
1204 var rgs = CanvasKit._MakeRadialGradientShader(center, radius, colorPtr, posPtr,
1205 colors.length, mode, flags);
1206 }
1207
1208 CanvasKit._free(colorPtr);
1209 CanvasKit._free(posPtr);
1210 return rgs;
1211}
1212
1213CanvasKit.MakeTwoPointConicalGradientShader = function(start, startRadius, end, endRadius,
1214 colors, pos, mode, localMatrix, flags) {
Kevin Lubickee91c072019-03-29 10:39:52 -04001215 var colorPtr = copy1dArray(colors, CanvasKit.HEAPU32);
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001216 var posPtr = copy1dArray(pos, CanvasKit.HEAPF32);
1217 flags = flags || 0;
1218
1219 if (localMatrix) {
1220 // Add perspective args if not provided.
1221 if (localMatrix.length === 6) {
1222 localMatrix.push(0, 0, 1);
1223 }
1224 var rgs = CanvasKit._MakeTwoPointConicalGradientShader(
1225 start, startRadius, end, endRadius,
1226 colorPtr, posPtr, colors.length, mode, flags, localMatrix);
1227 } else {
1228 var rgs = CanvasKit._MakeTwoPointConicalGradientShader(
1229 start, startRadius, end, endRadius,
1230 colorPtr, posPtr, colors.length, mode, flags);
1231 }
1232
1233 CanvasKit._free(colorPtr);
1234 CanvasKit._free(posPtr);
1235 return rgs;
1236}
1237
1238CanvasKit.MakeSkVertices = function(mode, positions, textureCoordinates, colors,
Kevin Lubickb3574c92019-03-06 08:25:36 -05001239 boneIndices, boneWeights, indices, isVolatile) {
Kevin Lubickb3574c92019-03-06 08:25:36 -05001240 // Default isVolitile to true if not set
1241 isVolatile = isVolatile === undefined ? true : isVolatile;
Kevin Lubickd6ba7252019-06-03 14:38:05 -04001242 var idxCount = (indices && indices.length) || 0;
1243
1244 var flags = 0;
1245 // These flags are from SkVertices.h and should be kept in sync with those.
1246 if (textureCoordinates && textureCoordinates.length) {
1247 flags |= (1 << 0);
1248 }
1249 if (colors && colors.length) {
1250 flags |= (1 << 1);
1251 }
1252 if (boneIndices && boneIndices.length) {
1253 flags |= (1 << 2);
1254 }
1255 if (!isVolatile) {
1256 flags |= (1 << 3);
1257 }
1258
1259 var builder = new CanvasKit._SkVerticesBuilder(mode, positions.length, idxCount, flags);
1260
1261 copy2dArray(positions, CanvasKit.HEAPF32, builder.positions());
1262 if (builder.texCoords()) {
1263 copy2dArray(textureCoordinates, CanvasKit.HEAPF32, builder.texCoords());
1264 }
1265 if (builder.colors()) {
1266 copy1dArray(colors, CanvasKit.HEAPU32, builder.colors());
1267 }
1268 if (builder.boneIndices()) {
1269 copy2dArray(boneIndices, CanvasKit.HEAP32, builder.boneIndices());
1270 }
1271 if (builder.boneWeights()) {
1272 copy2dArray(boneWeights, CanvasKit.HEAPF32, builder.boneWeights());
1273 }
1274 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};