blob: ad3547f2275a15b14f7789f3996f2469b3025dc4 [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 Lubick93f1a382020-06-02 16:15:23 -040011 _scratchColor = CanvasKit.Malloc(Float32Array, 4); // 4 color scalars.
Kevin Lubickb42660f2020-06-03 09:58:27 -040012 _scratchColorPtr = _scratchColor['byteOffset'];
Kevin Lubick6aa38692020-06-01 11:25:47 -040013
14 _scratch4x4Matrix = CanvasKit.Malloc(Float32Array, 16); // 16 matrix scalars.
Kevin Lubickb42660f2020-06-03 09:58:27 -040015 _scratch4x4MatrixPtr = _scratch4x4Matrix['byteOffset'];
Kevin Lubick6aa38692020-06-01 11:25:47 -040016
17 _scratch3x3Matrix = CanvasKit.Malloc(Float32Array, 9); // 9 matrix scalars.
Kevin Lubickb42660f2020-06-03 09:58:27 -040018 _scratch3x3MatrixPtr = _scratch3x3Matrix['byteOffset'];
Nathaniel Nifongb1ebbb12020-05-26 13:10:20 -040019 // Create single copies of all three supported color spaces
20 // These are sk_sp<SkColorSpace>
21 CanvasKit.SkColorSpace.SRGB = CanvasKit.SkColorSpace._MakeSRGB();
22 CanvasKit.SkColorSpace.DISPLAY_P3 = CanvasKit.SkColorSpace._MakeDisplayP3();
23 CanvasKit.SkColorSpace.ADOBE_RGB = CanvasKit.SkColorSpace._MakeAdobeRGB();
24
Kevin Lubickf5ea37f2019-02-28 10:06:18 -050025 // Add some helpers for matrices. This is ported from SkMatrix.cpp
26 // to save complexity and overhead of going back and forth between
27 // C++ and JS layers.
28 // I would have liked to use something like DOMMatrix, except it
29 // isn't widely supported (would need polyfills) and it doesn't
30 // have a mapPoints() function (which could maybe be tacked on here).
31 // If DOMMatrix catches on, it would be worth re-considering this usage.
32 CanvasKit.SkMatrix = {};
Nathaniel Nifong77798b42020-02-21 17:15:22 -050033 function sdot() { // to be called with an even number of scalar args
34 var acc = 0;
35 for (var i=0; i < arguments.length-1; i+=2) {
36 acc += arguments[i] * arguments[i+1];
37 }
38 return acc;
39 }
40
41
42 // Private general matrix functions used in both 3x3s and 4x4s.
43 // Return a square identity matrix of size n.
44 var identityN = function(n) {
45 var size = n*n;
46 var m = new Array(size);
47 while(size--) {
48 m[size] = size%(n+1) == 0 ? 1.0 : 0.0;
49 }
50 return m;
51 }
52
53 // Stride, a function for compactly representing several ways of copying an array into another.
54 // Write vector `v` into matrix `m`. `m` is a matrix encoded as an array in row-major
55 // order. Its width is passed as `width`. `v` is an array with length < (m.length/width).
56 // An element of `v` is copied into `m` starting at `offset` and moving `colStride` cols right
57 // each row.
58 //
59 // For example, a width of 4, offset of 3, and stride of -1 would put the vector here.
60 // _ _ 0 _
61 // _ 1 _ _
62 // 2 _ _ _
63 // _ _ _ 3
64 //
65 var stride = function(v, m, width, offset, colStride) {
66 for (var i=0; i<v.length; i++) {
67 m[i * width + // column
68 (i * colStride + offset + width) % width // row
69 ] = v[i];
70 }
71 return m;
Kevin Lubickf5ea37f2019-02-28 10:06:18 -050072 }
73
74 CanvasKit.SkMatrix.identity = function() {
Nathaniel Nifong77798b42020-02-21 17:15:22 -050075 return identityN(3);
Kevin Lubickf5ea37f2019-02-28 10:06:18 -050076 };
77
78 // Return the inverse (if it exists) of this matrix.
Kevin Lubick9b56cea2020-04-06 08:16:18 -040079 // Otherwise, return null.
Kevin Lubickf5ea37f2019-02-28 10:06:18 -050080 CanvasKit.SkMatrix.invert = function(m) {
Nathaniel Nifong77798b42020-02-21 17:15:22 -050081 // Find the determinant by the sarrus rule. https://en.wikipedia.org/wiki/Rule_of_Sarrus
Kevin Lubickf5ea37f2019-02-28 10:06:18 -050082 var det = m[0]*m[4]*m[8] + m[1]*m[5]*m[6] + m[2]*m[3]*m[7]
83 - m[2]*m[4]*m[6] - m[1]*m[3]*m[8] - m[0]*m[5]*m[7];
84 if (!det) {
85 SkDebug('Warning, uninvertible matrix');
Nathaniel Nifong77798b42020-02-21 17:15:22 -050086 return null;
Kevin Lubick1a05fce2018-11-20 12:51:16 -050087 }
Nathaniel Nifong77798b42020-02-21 17:15:22 -050088 // Return the inverse by the formula adj(m)/det.
89 // adj (adjugate) of a 3x3 is the transpose of it's cofactor matrix.
90 // a cofactor matrix is a matrix where each term is +-det(N) where matrix N is the 2x2 formed
91 // by removing the row and column we're currently setting from the source.
92 // the sign alternates in a checkerboard pattern with a `+` at the top left.
93 // that's all been combined here into one expression.
Kevin Lubickf5ea37f2019-02-28 10:06:18 -050094 return [
95 (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,
96 (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,
97 (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,
98 ];
99 };
Kevin Lubick1a05fce2018-11-20 12:51:16 -0500100
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500101 // Maps the given points according to the passed in matrix.
102 // Results are done in place.
103 // See SkMatrix.h::mapPoints for the docs on the math.
104 CanvasKit.SkMatrix.mapPoints = function(matrix, ptArr) {
Nathaniel Nifong77798b42020-02-21 17:15:22 -0500105 if (skIsDebug && (ptArr.length % 2)) {
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500106 throw 'mapPoints requires an even length arr';
Kevin Lubickb9db3902018-11-26 11:47:54 -0500107 }
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500108 for (var i = 0; i < ptArr.length; i+=2) {
109 var x = ptArr[i], y = ptArr[i+1];
110 // Gx+Hy+I
111 var denom = matrix[6]*x + matrix[7]*y + matrix[8];
112 // Ax+By+C
113 var xTrans = matrix[0]*x + matrix[1]*y + matrix[2];
114 // Dx+Ey+F
115 var yTrans = matrix[3]*x + matrix[4]*y + matrix[5];
116 ptArr[i] = xTrans/denom;
117 ptArr[i+1] = yTrans/denom;
118 }
119 return ptArr;
120 };
Kevin Lubickb9db3902018-11-26 11:47:54 -0500121
Nathaniel Nifong77798b42020-02-21 17:15:22 -0500122 function isnumber(val) { return val !== NaN; };
123
Kevin Lubickc89ca0b2020-04-02 14:30:00 -0400124 // generalized iterative algorithm for multiplying two matrices.
Nathaniel Nifong77798b42020-02-21 17:15:22 -0500125 function multiply(m1, m2, size) {
126
127 if (skIsDebug && (!m1.every(isnumber) || !m2.every(isnumber))) {
128 throw 'Some members of matrices are NaN m1='+m1+', m2='+m2+'';
129 }
130 if (skIsDebug && (m1.length !== m2.length)) {
131 throw 'Undefined for matrices of different sizes. m1.length='+m1.length+', m2.length='+m2.length;
132 }
133 if (skIsDebug && (size*size !== m1.length)) {
134 throw 'Undefined for non-square matrices. array size was '+size;
135 }
136
137 var result = Array(m1.length);
138 for (var r = 0; r < size; r++) {
139 for (var c = 0; c < size; c++) {
140 // accumulate a sum of m1[r,k]*m2[k, c]
141 var acc = 0;
142 for (var k = 0; k < size; k++) {
143 acc += m1[size * r + k] * m2[size * k + c];
144 }
145 result[r * size + c] = acc;
Kevin Lubick1a05fce2018-11-20 12:51:16 -0500146 }
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500147 }
148 return result;
Nathaniel Nifong77798b42020-02-21 17:15:22 -0500149 };
150
151 // Accept an integer indicating the size of the matrices being multiplied (3 for 3x3), and any
152 // number of matrices following it.
153 function multiplyMany(size, listOfMatrices) {
154 if (skIsDebug && (listOfMatrices.length < 2)) {
155 throw 'multiplication expected two or more matrices';
156 }
157 var result = multiply(listOfMatrices[0], listOfMatrices[1], size);
158 var next = 2;
159 while (next < listOfMatrices.length) {
160 result = multiply(result, listOfMatrices[next], size);
161 next++;
162 }
163 return result;
164 };
165
166 // Accept any number 3x3 of matrices as arguments, multiply them together.
Kevin Lubick9e2d3842020-04-01 13:42:15 -0400167 // Matrix multiplication is associative but not commutative. the order of the arguments
Nathaniel Nifong77798b42020-02-21 17:15:22 -0500168 // matters, but it does not matter that this implementation multiplies them left to right.
169 CanvasKit.SkMatrix.multiply = function() {
170 return multiplyMany(3, arguments);
171 };
Kevin Lubick1a05fce2018-11-20 12:51:16 -0500172
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500173 // Return a matrix representing a rotation by n radians.
174 // px, py optionally say which point the rotation should be around
175 // with the default being (0, 0);
176 CanvasKit.SkMatrix.rotated = function(radians, px, py) {
177 px = px || 0;
178 py = py || 0;
179 var sinV = Math.sin(radians);
180 var cosV = Math.cos(radians);
181 return [
182 cosV, -sinV, sdot( sinV, py, 1 - cosV, px),
183 sinV, cosV, sdot(-sinV, px, 1 - cosV, py),
184 0, 0, 1,
185 ];
186 };
Kevin Lubick217056c2018-09-20 17:39:31 -0400187
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500188 CanvasKit.SkMatrix.scaled = function(sx, sy, px, py) {
189 px = px || 0;
190 py = py || 0;
Nathaniel Nifong77798b42020-02-21 17:15:22 -0500191 var m = stride([sx, sy], identityN(3), 3, 0, 1);
192 return stride([px-sx*px, py-sy*py], m, 3, 2, 0);
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500193 };
Kevin Lubickda3d8ac2019-01-07 11:08:55 -0500194
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500195 CanvasKit.SkMatrix.skewed = function(kx, ky, px, py) {
196 px = px || 0;
197 py = py || 0;
Nathaniel Nifong77798b42020-02-21 17:15:22 -0500198 var m = stride([kx, ky], identityN(3), 3, 1, -1);
199 return stride([-kx*px, -ky*py], m, 3, 2, 0);
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500200 };
Alexander Khovansky3e119332018-11-15 02:01:19 +0300201
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500202 CanvasKit.SkMatrix.translated = function(dx, dy) {
Nathaniel Nifong77798b42020-02-21 17:15:22 -0500203 return stride(arguments, identityN(3), 3, 2, 0);
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500204 };
Kevin Lubick1646e7d2018-12-07 13:03:08 -0500205
Nathaniel Nifong77798b42020-02-21 17:15:22 -0500206 // Functions for manipulating vectors.
207 // Loosely based off of SkV3 in SkM44.h but skia also has SkVec2 and Skv4. This combines them and
208 // works on vectors of any length.
209 CanvasKit.SkVector = {};
210 CanvasKit.SkVector.dot = function(a, b) {
211 if (skIsDebug && (a.length !== b.length)) {
212 throw 'Cannot perform dot product on arrays of different length ('+a.length+' vs '+b.length+')';
213 }
214 return a.map(function(v, i) { return v*b[i] }).reduce(function(acc, cur) { return acc + cur; });
215 }
216 CanvasKit.SkVector.lengthSquared = function(v) {
217 return CanvasKit.SkVector.dot(v, v);
218 }
219 CanvasKit.SkVector.length = function(v) {
220 return Math.sqrt(CanvasKit.SkVector.lengthSquared(v));
221 }
222 CanvasKit.SkVector.mulScalar = function(v, s) {
223 return v.map(function(i) { return i*s });
224 }
225 CanvasKit.SkVector.add = function(a, b) {
226 return a.map(function(v, i) { return v+b[i] });
227 }
228 CanvasKit.SkVector.sub = function(a, b) {
229 return a.map(function(v, i) { return v-b[i]; });
230 }
Nathaniel Nifongcc5415a2020-02-23 14:26:33 -0500231 CanvasKit.SkVector.dist = function(a, b) {
232 return CanvasKit.SkVector.length(CanvasKit.SkVector.sub(a, b));
233 }
Nathaniel Nifong77798b42020-02-21 17:15:22 -0500234 CanvasKit.SkVector.normalize = function(v) {
235 return CanvasKit.SkVector.mulScalar(v, 1/CanvasKit.SkVector.length(v));
236 }
237 CanvasKit.SkVector.cross = function(a, b) {
238 if (skIsDebug && (a.length !== 3 || a.length !== 3)) {
239 throw 'Cross product is only defined for 3-dimensional vectors (a.length='+a.length+', b.length='+b.length+')';
240 }
241 return [
242 a[1]*b[2] - a[2]*b[1],
243 a[2]*b[0] - a[0]*b[2],
244 a[0]*b[1] - a[1]*b[0],
245 ];
246 }
247
Kevin Lubickc1d08982020-04-06 13:52:15 -0400248 // Functions for creating and manipulating (row-major) 4x4 matrices. Accepted in place of
249 // SkM44 in canvas methods, for the same reasons as the 3x3 matrices above.
Nathaniel Nifong77798b42020-02-21 17:15:22 -0500250 // ported from C++ code in SkM44.cpp
251 CanvasKit.SkM44 = {};
252 // Create a 4x4 identity matrix
253 CanvasKit.SkM44.identity = function() {
254 return identityN(4);
255 }
256
257 // Anything named vec below is an array of length 3 representing a vector/point in 3D space.
258 // Create a 4x4 matrix representing a translate by the provided 3-vec
259 CanvasKit.SkM44.translated = function(vec) {
260 return stride(vec, identityN(4), 4, 3, 0);
261 }
262 // Create a 4x4 matrix representing a scaling by the provided 3-vec
263 CanvasKit.SkM44.scaled = function(vec) {
264 return stride(vec, identityN(4), 4, 0, 1);
265 }
266 // Create a 4x4 matrix representing a rotation about the provided axis 3-vec.
267 // axis does not need to be normalized.
268 CanvasKit.SkM44.rotated = function(axisVec, radians) {
269 return CanvasKit.SkM44.rotatedUnitSinCos(
270 CanvasKit.SkVector.normalize(axisVec), Math.sin(radians), Math.cos(radians));
271 }
272 // Create a 4x4 matrix representing a rotation about the provided normalized axis 3-vec.
273 // Rotation is provided redundantly as both sin and cos values.
274 // This rotate can be used when you already have the cosAngle and sinAngle values
275 // so you don't have to atan(cos/sin) to call roatated() which expects an angle in radians.
276 // this does no checking! Behavior for invalid sin or cos values or non-normalized axis vectors
Nathaniel Nifong3392ebe2020-06-01 09:21:36 -0400277 // is incorrect. Prefer rotated().
Nathaniel Nifong77798b42020-02-21 17:15:22 -0500278 CanvasKit.SkM44.rotatedUnitSinCos = function(axisVec, sinAngle, cosAngle) {
279 var x = axisVec[0];
280 var y = axisVec[1];
281 var z = axisVec[2];
282 var c = cosAngle;
283 var s = sinAngle;
284 var t = 1 - c;
285 return [
286 t*x*x + c, t*x*y - s*z, t*x*z + s*y, 0,
287 t*x*y + s*z, t*y*y + c, t*y*z - s*x, 0,
288 t*x*z - s*y, t*y*z + s*x, t*z*z + c, 0,
289 0, 0, 0, 1
290 ];
291 }
292 // Create a 4x4 matrix representing a camera at eyeVec, pointed at centerVec.
293 CanvasKit.SkM44.lookat = function(eyeVec, centerVec, upVec) {
294 var f = CanvasKit.SkVector.normalize(CanvasKit.SkVector.sub(centerVec, eyeVec));
295 var u = CanvasKit.SkVector.normalize(upVec);
296 var s = CanvasKit.SkVector.normalize(CanvasKit.SkVector.cross(f, u));
297
298 var m = CanvasKit.SkM44.identity();
299 // set each column's top three numbers
Kevin Lubickc1d08982020-04-06 13:52:15 -0400300 stride(s, m, 4, 0, 0);
Nathaniel Nifong77798b42020-02-21 17:15:22 -0500301 stride(CanvasKit.SkVector.cross(s, f), m, 4, 1, 0);
302 stride(CanvasKit.SkVector.mulScalar(f, -1), m, 4, 2, 0);
Kevin Lubickc1d08982020-04-06 13:52:15 -0400303 stride(eyeVec, m, 4, 3, 0);
Nathaniel Nifong77798b42020-02-21 17:15:22 -0500304
305 var m2 = CanvasKit.SkM44.invert(m);
306 if (m2 === null) {
307 return CanvasKit.SkM44.identity();
308 }
309 return m2;
310 }
311 // Create a 4x4 matrix representing a perspective. All arguments are scalars.
312 // angle is in radians.
313 CanvasKit.SkM44.perspective = function(near, far, angle) {
314 if (skIsDebug && (far <= near)) {
315 throw "far must be greater than near when constructing SkM44 using perspective.";
316 }
317 var dInv = 1 / (far - near);
318 var halfAngle = angle / 2;
319 var cot = Math.cos(halfAngle) / Math.sin(halfAngle);
320 return [
321 cot, 0, 0, 0,
322 0, cot, 0, 0,
323 0, 0, (far+near)*dInv, 2*far*near*dInv,
324 0, 0, -1, 1,
325 ];
326 }
327 // Returns the number at the given row and column in matrix m.
328 CanvasKit.SkM44.rc = function(m, r, c) {
329 return m[r*4+c];
330 }
331 // Accepts any number of 4x4 matrix arguments, multiplies them left to right.
332 CanvasKit.SkM44.multiply = function() {
333 return multiplyMany(4, arguments);
334 }
335
336 // Invert the 4x4 matrix if it is invertible and return it. if not, return null.
337 // taken from SkM44.cpp (altered to use row-major order)
338 // m is not altered.
339 CanvasKit.SkM44.invert = function(m) {
340 if (skIsDebug && !m.every(isnumber)) {
341 throw 'some members of matrix are NaN m='+m;
342 }
343
344 var a00 = m[0];
345 var a01 = m[4];
346 var a02 = m[8];
347 var a03 = m[12];
348 var a10 = m[1];
349 var a11 = m[5];
350 var a12 = m[9];
351 var a13 = m[13];
352 var a20 = m[2];
353 var a21 = m[6];
354 var a22 = m[10];
355 var a23 = m[14];
356 var a30 = m[3];
357 var a31 = m[7];
358 var a32 = m[11];
359 var a33 = m[15];
360
361 var b00 = a00 * a11 - a01 * a10;
362 var b01 = a00 * a12 - a02 * a10;
363 var b02 = a00 * a13 - a03 * a10;
364 var b03 = a01 * a12 - a02 * a11;
365 var b04 = a01 * a13 - a03 * a11;
366 var b05 = a02 * a13 - a03 * a12;
367 var b06 = a20 * a31 - a21 * a30;
368 var b07 = a20 * a32 - a22 * a30;
369 var b08 = a20 * a33 - a23 * a30;
370 var b09 = a21 * a32 - a22 * a31;
371 var b10 = a21 * a33 - a23 * a31;
372 var b11 = a22 * a33 - a23 * a32;
373
374 // calculate determinate
375 var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
376 var invdet = 1.0 / det;
377
378 // bail out if the matrix is not invertible
379 if (det === 0 || invdet === Infinity) {
380 SkDebug('Warning, uninvertible matrix');
381 return null;
382 }
383
384 b00 *= invdet;
385 b01 *= invdet;
386 b02 *= invdet;
387 b03 *= invdet;
388 b04 *= invdet;
389 b05 *= invdet;
390 b06 *= invdet;
391 b07 *= invdet;
392 b08 *= invdet;
393 b09 *= invdet;
394 b10 *= invdet;
395 b11 *= invdet;
396
397 // store result in row major order
398 var tmp = [
399 a11 * b11 - a12 * b10 + a13 * b09,
400 a12 * b08 - a10 * b11 - a13 * b07,
401 a10 * b10 - a11 * b08 + a13 * b06,
402 a11 * b07 - a10 * b09 - a12 * b06,
403
404 a02 * b10 - a01 * b11 - a03 * b09,
405 a00 * b11 - a02 * b08 + a03 * b07,
406 a01 * b08 - a00 * b10 - a03 * b06,
407 a00 * b09 - a01 * b07 + a02 * b06,
408
409 a31 * b05 - a32 * b04 + a33 * b03,
410 a32 * b02 - a30 * b05 - a33 * b01,
411 a30 * b04 - a31 * b02 + a33 * b00,
412 a31 * b01 - a30 * b03 - a32 * b00,
413
414 a22 * b04 - a21 * b05 - a23 * b03,
415 a20 * b05 - a22 * b02 + a23 * b01,
416 a21 * b02 - a20 * b04 - a23 * b00,
417 a20 * b03 - a21 * b01 + a22 * b00,
418 ];
419
420
421 if (!tmp.every(function(val) { return val !== NaN && val !== Infinity && val !== -Infinity; })) {
422 SkDebug('inverted matrix contains infinities or NaN '+tmp);
423 return null;
424 }
425 return tmp;
426 }
427
Nathaniel Nifongcc5415a2020-02-23 14:26:33 -0500428 CanvasKit.SkM44.transpose = function(m) {
429 return [
430 m[0], m[4], m[8], m[12],
431 m[1], m[5], m[9], m[13],
432 m[2], m[6], m[10], m[14],
433 m[3], m[7], m[11], m[15],
434 ];
435 }
Nathaniel Nifong77798b42020-02-21 17:15:22 -0500436
Kevin Lubickd3729342019-09-12 11:11:25 -0400437 // An SkColorMatrix is a 4x4 color matrix that transforms the 4 color channels
438 // with a 1x4 matrix that post-translates those 4 channels.
439 // For example, the following is the layout with the scale (S) and post-transform
440 // (PT) items indicated.
441 // RS, 0, 0, 0 | RPT
442 // 0, GS, 0, 0 | GPT
443 // 0, 0, BS, 0 | BPT
444 // 0, 0, 0, AS | APT
445 //
446 // Much of this was hand-transcribed from SkColorMatrix.cpp, because it's easier to
447 // deal with a Float32Array of length 20 than to try to expose the SkColorMatrix object.
448
Nathaniel Nifongcc5415a2020-02-23 14:26:33 -0500449 var rScale = 0;
450 var gScale = 6;
451 var bScale = 12;
452 var aScale = 18;
453
Kevin Lubickd3729342019-09-12 11:11:25 -0400454 var rPostTrans = 4;
455 var gPostTrans = 9;
456 var bPostTrans = 14;
457 var aPostTrans = 19;
458
459 CanvasKit.SkColorMatrix = {};
460 CanvasKit.SkColorMatrix.identity = function() {
Nathaniel Nifongcc5415a2020-02-23 14:26:33 -0500461 var m = new Float32Array(20);
462 m[rScale] = 1;
463 m[gScale] = 1;
464 m[bScale] = 1;
465 m[aScale] = 1;
466 return m;
Kevin Lubickd3729342019-09-12 11:11:25 -0400467 }
468
469 CanvasKit.SkColorMatrix.scaled = function(rs, gs, bs, as) {
Nathaniel Nifongcc5415a2020-02-23 14:26:33 -0500470 var m = new Float32Array(20);
471 m[rScale] = rs;
472 m[gScale] = gs;
473 m[bScale] = bs;
474 m[aScale] = as;
475 return m;
Kevin Lubickd3729342019-09-12 11:11:25 -0400476 }
477
478 var rotateIndices = [
479 [6, 7, 11, 12],
480 [0, 10, 2, 12],
481 [0, 1, 5, 6],
482 ];
483 // axis should be 0, 1, 2 for r, g, b
484 CanvasKit.SkColorMatrix.rotated = function(axis, sine, cosine) {
485 var m = CanvasKit.SkColorMatrix.identity();
486 var indices = rotateIndices[axis];
487 m[indices[0]] = cosine;
488 m[indices[1]] = sine;
489 m[indices[2]] = -sine;
490 m[indices[3]] = cosine;
491 return m;
492 }
493
494 // m is a SkColorMatrix (i.e. a Float32Array), and this sets the 4 "special"
495 // params that will translate the colors after they are multiplied by the 4x4 matrix.
496 CanvasKit.SkColorMatrix.postTranslate = function(m, dr, dg, db, da) {
497 m[rPostTrans] += dr;
498 m[gPostTrans] += dg;
499 m[bPostTrans] += db;
500 m[aPostTrans] += da;
501 return m;
502 }
503
504 // concat returns a new SkColorMatrix that is the result of multiplying outer*inner;
505 CanvasKit.SkColorMatrix.concat = function(outer, inner) {
506 var m = new Float32Array(20);
507 var index = 0;
508 for (var j = 0; j < 20; j += 5) {
509 for (var i = 0; i < 4; i++) {
510 m[index++] = outer[j + 0] * inner[i + 0] +
511 outer[j + 1] * inner[i + 5] +
512 outer[j + 2] * inner[i + 10] +
513 outer[j + 3] * inner[i + 15];
514 }
515 m[index++] = outer[j + 0] * inner[4] +
516 outer[j + 1] * inner[9] +
517 outer[j + 2] * inner[14] +
518 outer[j + 3] * inner[19] +
519 outer[j + 4];
520 }
521
522 return m;
523 }
524
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500525 CanvasKit.SkPath.prototype.addArc = function(oval, startAngle, sweepAngle) {
526 // see arc() for the HTMLCanvas version
527 // note input angles are degrees.
528 this._addArc(oval, startAngle, sweepAngle);
529 return this;
530 };
Kevin Lubick217056c2018-09-20 17:39:31 -0400531
Kevin Lubicke384df42019-08-26 15:48:09 -0400532 CanvasKit.SkPath.prototype.addOval = function(oval, isCCW, startIndex) {
533 if (startIndex === undefined) {
534 startIndex = 1;
535 }
536 this._addOval(oval, !!isCCW, startIndex);
537 return this;
538 };
539
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500540 CanvasKit.SkPath.prototype.addPath = function() {
541 // Takes 1, 2, 7, or 10 required args, where the first arg is always the path.
542 // The last arg is optional and chooses between add or extend mode.
543 // The options for the remaining args are:
544 // - an array of 6 or 9 parameters (perspective is optional)
545 // - the 9 parameters of a full matrix or
546 // the 6 non-perspective params of a matrix.
547 var args = Array.prototype.slice.call(arguments);
548 var path = args[0];
549 var extend = false;
550 if (typeof args[args.length-1] === "boolean") {
551 extend = args.pop();
552 }
553 if (args.length === 1) {
554 // Add path, unchanged. Use identity matrix
555 this._addPath(path, 1, 0, 0,
556 0, 1, 0,
557 0, 0, 1,
558 extend);
559 } else if (args.length === 2) {
560 // User provided the 9 params of a full matrix as an array.
561 var a = args[1];
562 this._addPath(path, a[0], a[1], a[2],
563 a[3], a[4], a[5],
564 a[6] || 0, a[7] || 0, a[8] || 1,
565 extend);
566 } else if (args.length === 7 || args.length === 10) {
567 // User provided the 9 params of a (full) matrix directly.
568 // (or just the 6 non perspective ones)
569 // These are in the same order as what Skia expects.
570 var a = args;
571 this._addPath(path, a[1], a[2], a[3],
572 a[4], a[5], a[6],
573 a[7] || 0, a[8] || 0, a[9] || 1,
574 extend);
575 } else {
576 SkDebug('addPath expected to take 1, 2, 7, or 10 required args. Got ' + args.length);
Kevin Lubickb5ae3b52018-11-03 07:51:19 -0400577 return null;
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500578 }
579 return this;
580 };
Kevin Lubickb5ae3b52018-11-03 07:51:19 -0400581
Kevin Lubick37ab53e2019-11-11 10:06:08 -0500582 // points is either an array of [x, y] where x and y are numbers or
583 // a typed array from Malloc where the even indices will be treated
584 // as x coordinates and the odd indices will be treated as y coordinates.
585 CanvasKit.SkPath.prototype.addPoly = function(points, close) {
586 var ptr;
587 var n;
588 // This was created with CanvasKit.Malloc, so assume the user has
589 // already been filled with data.
590 if (points['_ck']) {
591 ptr = points.byteOffset;
592 n = points.length/2;
593 } else {
Kevin Lubick69e46da2020-06-05 07:13:48 -0400594 ptr = copy2dArray(points, "HEAPF32");
Kevin Lubick37ab53e2019-11-11 10:06:08 -0500595 n = points.length;
596 }
597 this._addPoly(ptr, n, close);
Kevin Lubickcf118922020-05-28 14:43:38 -0400598 freeArraysThatAreNotMallocedByUsers(ptr, points);
Kevin Lubick37ab53e2019-11-11 10:06:08 -0500599 return this;
600 };
601
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500602 CanvasKit.SkPath.prototype.addRect = function() {
603 // Takes 1, 2, 4 or 5 args
604 // - SkRect
605 // - SkRect, isCCW
606 // - left, top, right, bottom
607 // - left, top, right, bottom, isCCW
608 if (arguments.length === 1 || arguments.length === 2) {
609 var r = arguments[0];
610 var ccw = arguments[1] || false;
611 this._addRect(r.fLeft, r.fTop, r.fRight, r.fBottom, ccw);
612 } else if (arguments.length === 4 || arguments.length === 5) {
613 var a = arguments;
614 this._addRect(a[0], a[1], a[2], a[3], a[4] || false);
615 } else {
616 SkDebug('addRect expected to take 1, 2, 4, or 5 args. Got ' + arguments.length);
Kevin Lubick217056c2018-09-20 17:39:31 -0400617 return null;
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500618 }
619 return this;
620 };
Kevin Lubick217056c2018-09-20 17:39:31 -0400621
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500622 CanvasKit.SkPath.prototype.addRoundRect = function() {
623 // Takes 3, 4, 6 or 7 args
Nathaniel Nifong3392ebe2020-06-01 09:21:36 -0400624 // - SkRect, radii (an array of 8 numbers), ccw
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500625 // - SkRect, rx, ry, ccw
626 // - left, top, right, bottom, radii, ccw
627 // - left, top, right, bottom, rx, ry, ccw
628 var args = arguments;
629 if (args.length === 3 || args.length === 6) {
630 var radii = args[args.length-2];
Kevin Lubickcf118922020-05-28 14:43:38 -0400631 } else if (args.length === 4 || args.length === 7){
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500632 // duplicate the given (rx, ry) pairs for each corner.
633 var rx = args[args.length-3];
634 var ry = args[args.length-2];
635 var radii = [rx, ry, rx, ry, rx, ry, rx, ry];
636 } else {
637 SkDebug('addRoundRect expected to take 3, 4, 6, or 7 args. Got ' + args.length);
638 return null;
639 }
640 if (radii.length !== 8) {
641 SkDebug('addRoundRect needs 8 radii provided. Got ' + radii.length);
642 return null;
643 }
Kevin Lubick69e46da2020-06-05 07:13:48 -0400644 var rptr = copy1dArray(radii, "HEAPF32");
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500645 if (args.length === 3 || args.length === 4) {
646 var r = args[0];
647 var ccw = args[args.length - 1];
648 this._addRoundRect(r.fLeft, r.fTop, r.fRight, r.fBottom, rptr, ccw);
649 } else if (args.length === 6 || args.length === 7) {
650 var a = args;
651 this._addRoundRect(a[0], a[1], a[2], a[3], rptr, ccw);
652 }
Kevin Lubickcf118922020-05-28 14:43:38 -0400653 freeArraysThatAreNotMallocedByUsers(rptr, radii);
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500654 return this;
655 };
656
657 CanvasKit.SkPath.prototype.arc = function(x, y, radius, startAngle, endAngle, ccw) {
658 // emulates the HTMLCanvas behavior. See addArc() for the SkPath version.
659 // Note input angles are radians.
660 var bounds = CanvasKit.LTRBRect(x-radius, y-radius, x+radius, y+radius);
661 var sweep = radiansToDegrees(endAngle - startAngle) - (360 * !!ccw);
662 var temp = new CanvasKit.SkPath();
663 temp.addArc(bounds, radiansToDegrees(startAngle), sweep);
664 this.addPath(temp, true);
665 temp.delete();
666 return this;
667 };
668
669 CanvasKit.SkPath.prototype.arcTo = function() {
670 // takes 4, 5 or 7 args
671 // - 5 x1, y1, x2, y2, radius
672 // - 4 oval (as Rect), startAngle, sweepAngle, forceMoveTo
Kevin Lubicke384df42019-08-26 15:48:09 -0400673 // - 7 rx, ry, xAxisRotate, useSmallArc, isCCW, x, y
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500674 var args = arguments;
675 if (args.length === 5) {
676 this._arcTo(args[0], args[1], args[2], args[3], args[4]);
677 } else if (args.length === 4) {
678 this._arcTo(args[0], args[1], args[2], args[3]);
679 } else if (args.length === 7) {
Kevin Lubicke384df42019-08-26 15:48:09 -0400680 this._arcTo(args[0], args[1], args[2], !!args[3], !!args[4], args[5], args[6]);
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500681 } else {
682 throw 'Invalid args for arcTo. Expected 4, 5, or 7, got '+ args.length;
683 }
684
685 return this;
686 };
687
688 CanvasKit.SkPath.prototype.close = function() {
689 this._close();
690 return this;
691 };
692
693 CanvasKit.SkPath.prototype.conicTo = function(x1, y1, x2, y2, w) {
694 this._conicTo(x1, y1, x2, y2, w);
695 return this;
696 };
697
698 CanvasKit.SkPath.prototype.cubicTo = function(cp1x, cp1y, cp2x, cp2y, x, y) {
699 this._cubicTo(cp1x, cp1y, cp2x, cp2y, x, y);
700 return this;
701 };
702
703 CanvasKit.SkPath.prototype.dash = function(on, off, phase) {
704 if (this._dash(on, off, phase)) {
Kevin Lubick217056c2018-09-20 17:39:31 -0400705 return this;
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500706 }
707 return null;
708 };
Kevin Lubick217056c2018-09-20 17:39:31 -0400709
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500710 CanvasKit.SkPath.prototype.lineTo = function(x, y) {
711 this._lineTo(x, y);
712 return this;
713 };
Kevin Lubick217056c2018-09-20 17:39:31 -0400714
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500715 CanvasKit.SkPath.prototype.moveTo = function(x, y) {
716 this._moveTo(x, y);
717 return this;
718 };
Kevin Lubickb5ae3b52018-11-03 07:51:19 -0400719
Kevin Lubicke384df42019-08-26 15:48:09 -0400720 CanvasKit.SkPath.prototype.offset = function(dx, dy) {
721 this._transform(1, 0, dx,
722 0, 1, dy,
723 0, 0, 1);
724 return this;
725 };
726
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500727 CanvasKit.SkPath.prototype.quadTo = function(cpx, cpy, x, y) {
728 this._quadTo(cpx, cpy, x, y);
729 return this;
730 };
731
Kevin Lubick79b71342019-11-01 14:36:52 -0400732 CanvasKit.SkPath.prototype.rArcTo = function(rx, ry, xAxisRotate, useSmallArc, isCCW, dx, dy) {
733 this._rArcTo(rx, ry, xAxisRotate, useSmallArc, isCCW, dx, dy);
734 return this;
735 };
736
737 CanvasKit.SkPath.prototype.rConicTo = function(dx1, dy1, dx2, dy2, w) {
738 this._rConicTo(dx1, dy1, dx2, dy2, w);
739 return this;
740 };
741
742 // These params are all relative
743 CanvasKit.SkPath.prototype.rCubicTo = function(cp1x, cp1y, cp2x, cp2y, x, y) {
744 this._rCubicTo(cp1x, cp1y, cp2x, cp2y, x, y);
745 return this;
746 };
747
748 CanvasKit.SkPath.prototype.rLineTo = function(dx, dy) {
749 this._rLineTo(dx, dy);
750 return this;
751 };
752
753 CanvasKit.SkPath.prototype.rMoveTo = function(dx, dy) {
754 this._rMoveTo(dx, dy);
755 return this;
756 };
757
758 // These params are all relative
759 CanvasKit.SkPath.prototype.rQuadTo = function(cpx, cpy, x, y) {
760 this._rQuadTo(cpx, cpy, x, y);
761 return this;
762 };
763
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500764 CanvasKit.SkPath.prototype.stroke = function(opts) {
765 // Fill out any missing values with the default values.
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500766 opts = opts || {};
Kevin Lubick6aa38692020-06-01 11:25:47 -0400767 opts['width'] = opts['width'] || 1;
768 opts['miter_limit'] = opts['miter_limit'] || 4;
769 opts['cap'] = opts['cap'] || CanvasKit.StrokeCap.Butt;
770 opts['join'] = opts['join'] || CanvasKit.StrokeJoin.Miter;
771 opts['precision'] = opts['precision'] || 1;
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500772 if (this._stroke(opts)) {
773 return this;
774 }
775 return null;
776 };
777
778 CanvasKit.SkPath.prototype.transform = function() {
779 // Takes 1 or 9 args
780 if (arguments.length === 1) {
781 // argument 1 should be a 6 or 9 element array.
782 var a = arguments[0];
783 this._transform(a[0], a[1], a[2],
784 a[3], a[4], a[5],
785 a[6] || 0, a[7] || 0, a[8] || 1);
786 } else if (arguments.length === 6 || arguments.length === 9) {
787 // these arguments are the 6 or 9 members of the matrix
788 var a = arguments;
789 this._transform(a[0], a[1], a[2],
790 a[3], a[4], a[5],
791 a[6] || 0, a[7] || 0, a[8] || 1);
792 } else {
793 throw 'transform expected to take 1 or 9 arguments. Got ' + arguments.length;
794 }
795 return this;
796 };
797 // isComplement is optional, defaults to false
798 CanvasKit.SkPath.prototype.trim = function(startT, stopT, isComplement) {
799 if (this._trim(startT, stopT, !!isComplement)) {
800 return this;
801 }
802 return null;
803 };
804
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500805 CanvasKit.SkImage.prototype.encodeToData = function() {
806 if (!arguments.length) {
807 return this._encodeToData();
Kevin Lubickb5ae3b52018-11-03 07:51:19 -0400808 }
Kevin Lubick53965c92018-10-11 08:51:55 -0400809
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500810 if (arguments.length === 2) {
811 var a = arguments;
812 return this._encodeToDataWithFormat(a[0], a[1]);
Alexander Khovansky3e119332018-11-15 02:01:19 +0300813 }
814
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500815 throw 'encodeToData expected to take 0 or 2 arguments. Got ' + arguments.length;
816 }
Kevin Lubick1ba9c4d2019-02-22 10:04:06 -0500817
Kevin Lubicka064c282019-04-04 09:28:53 -0400818 CanvasKit.SkImage.prototype.makeShader = function(xTileMode, yTileMode, localMatrix) {
Kevin Lubick6bffe392020-04-02 15:24:15 -0400819 var localMatrixPtr = copy3x3MatrixToWasm(localMatrix);
Kevin Lubick6aa38692020-06-01 11:25:47 -0400820 return this._makeShader(xTileMode, yTileMode, localMatrixPtr);
Kevin Lubicka064c282019-04-04 09:28:53 -0400821 }
822
Kevin Lubickd6b32ed2019-05-06 13:04:03 -0400823 CanvasKit.SkImage.prototype.readPixels = function(imageInfo, srcX, srcY) {
824 var rowBytes;
Kevin Lubick319524b2020-01-22 15:29:14 -0500825 // Important to use ["string"] notation here, otherwise the closure compiler will
826 // minify away the colorType.
827 switch (imageInfo["colorType"]) {
Kevin Lubickd6b32ed2019-05-06 13:04:03 -0400828 case CanvasKit.ColorType.RGBA_8888:
829 rowBytes = imageInfo.width * 4; // 1 byte per channel == 4 bytes per pixel in 8888
830 break;
831 case CanvasKit.ColorType.RGBA_F32:
832 rowBytes = imageInfo.width * 16; // 4 bytes per channel == 16 bytes per pixel in F32
833 break;
834 default:
835 SkDebug("Colortype not yet supported");
836 return;
837 }
838 var pBytes = rowBytes * imageInfo.height;
839 var pPtr = CanvasKit._malloc(pBytes);
840
841 if (!this._readPixels(imageInfo, pPtr, rowBytes, srcX, srcY)) {
842 SkDebug("Could not read pixels with the given inputs");
843 return null;
844 }
845
846 // Put those pixels into a typed array of the right format and then
847 // make a copy with slice() that we can return.
848 var retVal = null;
Kevin Lubick319524b2020-01-22 15:29:14 -0500849 switch (imageInfo["colorType"]) {
Kevin Lubickd6b32ed2019-05-06 13:04:03 -0400850 case CanvasKit.ColorType.RGBA_8888:
Bryce Thomas1fa54042020-01-14 13:46:30 -0800851 retVal = new Uint8Array(CanvasKit.HEAPU8.buffer, pPtr, pBytes).slice();
Kevin Lubickd6b32ed2019-05-06 13:04:03 -0400852 break;
853 case CanvasKit.ColorType.RGBA_F32:
Bryce Thomas1fa54042020-01-14 13:46:30 -0800854 retVal = new Float32Array(CanvasKit.HEAPU8.buffer, pPtr, pBytes).slice();
Kevin Lubickd6b32ed2019-05-06 13:04:03 -0400855 break;
856 }
857
858 // Free the allocated pixels in the WASM memory
859 CanvasKit._free(pPtr);
860 return retVal;
Kevin Lubick6bffe392020-04-02 15:24:15 -0400861 }
Kevin Lubickd6b32ed2019-05-06 13:04:03 -0400862
Nathaniel Nifong1bedbeb2020-05-04 16:46:17 -0400863 // Accepts an array of four numbers in the range of 0-1 representing a 4f color
864 CanvasKit.SkCanvas.prototype.clear = function (color4f) {
Kevin Lubick6aa38692020-06-01 11:25:47 -0400865 var cPtr = copyColorToWasm(color4f);
Nathaniel Nifong1bedbeb2020-05-04 16:46:17 -0400866 this._clear(cPtr);
Nathaniel Nifong1bedbeb2020-05-04 16:46:17 -0400867 }
868
Kevin Lubickc1d08982020-04-06 13:52:15 -0400869 // concat takes a 3x2, a 3x3, or a 4x4 matrix and upscales it (if needed) to 4x4. This is because
870 // under the hood, SkCanvas uses a 4x4 matrix.
Kevin Lubick6bffe392020-04-02 15:24:15 -0400871 CanvasKit.SkCanvas.prototype.concat = function(matr) {
Kevin Lubickc1d08982020-04-06 13:52:15 -0400872 var matrPtr = copy4x4MatrixToWasm(matr);
Kevin Lubick6bffe392020-04-02 15:24:15 -0400873 this._concat(matrPtr);
Kevin Lubickd6b32ed2019-05-06 13:04:03 -0400874 }
875
Kevin Lubickc1d08982020-04-06 13:52:15 -0400876 // Deprecated - just use concat
877 CanvasKit.SkCanvas.prototype.concat44 = CanvasKit.SkCanvas.prototype.concat;
878
Kevin Lubickee91c072019-03-29 10:39:52 -0400879 // atlas is an SkImage, e.g. from CanvasKit.MakeImageFromEncoded
Nathaniel Nifongcd75b172020-06-05 11:17:43 -0400880 // srcRects, dstXforms, and colors should be CanvasKit.SkRectBuilder, CanvasKit.RSXFormBuilder,
881 // and CanvasKit.SkColorBuilder (fastest)
882 // Or they can be an array of floats of length 4*number of destinations.
883 // colors are optional and used to tint the drawn images using the optional blend mode
884 // drawAtlas ONLY accepts uint colors such as those created with CanvasKit.ColorAsInt(r, g, b, a)
885 // whether they are provided as an array or a builder.
Kevin Lubickee91c072019-03-29 10:39:52 -0400886 CanvasKit.SkCanvas.prototype.drawAtlas = function(atlas, srcRects, dstXforms, paint,
887 /*optional*/ blendMode, colors) {
888 if (!atlas || !paint || !srcRects || !dstXforms) {
889 SkDebug('Doing nothing since missing a required input');
890 return;
891 }
Nathaniel Nifongcd75b172020-06-05 11:17:43 -0400892
893 // builder arguments report the length as the number of rects, but when passed as arrays
894 // their.length attribute is 4x higher because it's the number of total components of all rects.
895 // colors is always going to report the same length, at least until floats colors are supported
896 // by this function.
897 if (srcRects.length !== dstXforms.length) {
Kevin Lubickee91c072019-03-29 10:39:52 -0400898 SkDebug('Doing nothing since input arrays length mismatches');
Nathaniel Nifonge5d32542020-03-26 09:27:48 -0400899 return;
Kevin Lubickee91c072019-03-29 10:39:52 -0400900 }
901 if (!blendMode) {
902 blendMode = CanvasKit.BlendMode.SrcOver;
903 }
904
905 var srcRectPtr;
906 if (srcRects.build) {
907 srcRectPtr = srcRects.build();
908 } else {
Kevin Lubick69e46da2020-06-05 07:13:48 -0400909 srcRectPtr = copy1dArray(srcRects, "HEAPF32");
Kevin Lubickee91c072019-03-29 10:39:52 -0400910 }
911
Nathaniel Nifongcd75b172020-06-05 11:17:43 -0400912 var count = 1;
Kevin Lubickee91c072019-03-29 10:39:52 -0400913 var dstXformPtr;
914 if (dstXforms.build) {
915 dstXformPtr = dstXforms.build();
Nathaniel Nifongcd75b172020-06-05 11:17:43 -0400916 count = dstXforms.length;
Kevin Lubickee91c072019-03-29 10:39:52 -0400917 } else {
Kevin Lubick69e46da2020-06-05 07:13:48 -0400918 dstXformPtr = copy1dArray(dstXforms, "HEAPF32");
Nathaniel Nifongcd75b172020-06-05 11:17:43 -0400919 count = dstXforms.length / 4;
Kevin Lubickee91c072019-03-29 10:39:52 -0400920 }
921
Kevin Lubick6bffe392020-04-02 15:24:15 -0400922 var colorPtr = nullptr;
Kevin Lubickee91c072019-03-29 10:39:52 -0400923 if (colors) {
924 if (colors.build) {
925 colorPtr = colors.build();
926 } else {
Kevin Lubick69e46da2020-06-05 07:13:48 -0400927 colorPtr = copy1dArray(colors, "HEAPU32");
Kevin Lubickee91c072019-03-29 10:39:52 -0400928 }
929 }
930
Nathaniel Nifongcd75b172020-06-05 11:17:43 -0400931 this._drawAtlas(atlas, dstXformPtr, srcRectPtr, colorPtr, count, blendMode, paint);
Kevin Lubickee91c072019-03-29 10:39:52 -0400932
933 if (srcRectPtr && !srcRects.build) {
Kevin Lubickcf118922020-05-28 14:43:38 -0400934 freeArraysThatAreNotMallocedByUsers(srcRectPtr, srcRects);
Kevin Lubickee91c072019-03-29 10:39:52 -0400935 }
936 if (dstXformPtr && !dstXforms.build) {
Kevin Lubickcf118922020-05-28 14:43:38 -0400937 freeArraysThatAreNotMallocedByUsers(dstXformPtr, dstXforms);
Kevin Lubickee91c072019-03-29 10:39:52 -0400938 }
939 if (colorPtr && !colors.build) {
Kevin Lubickcf118922020-05-28 14:43:38 -0400940 freeArraysThatAreNotMallocedByUsers(colorPtr, colors);
Kevin Lubickee91c072019-03-29 10:39:52 -0400941 }
Kevin Lubickee91c072019-03-29 10:39:52 -0400942 }
943
Nathaniel Nifong1bedbeb2020-05-04 16:46:17 -0400944 CanvasKit.SkCanvas.prototype.drawColor = function (color4f, mode) {
Kevin Lubick6aa38692020-06-01 11:25:47 -0400945 var cPtr = copyColorToWasm(color4f);
Nathaniel Nifong1bedbeb2020-05-04 16:46:17 -0400946 if (mode !== undefined) {
947 this._drawColor(cPtr, mode);
948 } else {
949 this._drawColor(cPtr);
950 }
Nathaniel Nifong1bedbeb2020-05-04 16:46:17 -0400951 }
952
Kevin Lubick93f1a382020-06-02 16:15:23 -0400953 CanvasKit.SkCanvas.prototype.drawColorComponents = function (r, g, b, a, mode) {
954 var cPtr = copyColorComponentsToWasm(r, g, b, a);
955 if (mode !== undefined) {
956 this._drawColor(cPtr, mode);
957 } else {
958 this._drawColor(cPtr);
959 }
960 }
961
Kevin Lubick37ab53e2019-11-11 10:06:08 -0500962 // points is either an array of [x, y] where x and y are numbers or
963 // a typed array from Malloc where the even indices will be treated
964 // as x coordinates and the odd indices will be treated as y coordinates.
965 CanvasKit.SkCanvas.prototype.drawPoints = function(mode, points, paint) {
966 var ptr;
967 var n;
968 // This was created with CanvasKit.Malloc, so assume the user has
969 // already been filled with data.
970 if (points['_ck']) {
971 ptr = points.byteOffset;
972 n = points.length/2;
973 } else {
Kevin Lubick69e46da2020-06-05 07:13:48 -0400974 ptr = copy2dArray(points, "HEAPF32");
Kevin Lubick37ab53e2019-11-11 10:06:08 -0500975 n = points.length;
976 }
977 this._drawPoints(mode, ptr, n, paint);
Kevin Lubickcf118922020-05-28 14:43:38 -0400978 freeArraysThatAreNotMallocedByUsers(ptr, points);
Kevin Lubick37ab53e2019-11-11 10:06:08 -0500979 }
980
Nathaniel Nifong1bedbeb2020-05-04 16:46:17 -0400981 CanvasKit.SkCanvas.prototype.drawShadow = function(path, zPlaneParams, lightPos, lightRadius, ambientColor, spotColor, flags) {
Kevin Lubick6aa38692020-06-01 11:25:47 -0400982 var ambiPtr = copyColorToWasmNoScratch(ambientColor);
983 var spotPtr = copyColorToWasmNoScratch(spotColor);
Nathaniel Nifong1bedbeb2020-05-04 16:46:17 -0400984 this._drawShadow(path, zPlaneParams, lightPos, lightRadius, ambiPtr, spotPtr, flags);
Kevin Lubickcf118922020-05-28 14:43:38 -0400985 freeArraysThatAreNotMallocedByUsers(ambiPtr, ambientColor);
986 freeArraysThatAreNotMallocedByUsers(spotPtr, spotColor);
Nathaniel Nifong1bedbeb2020-05-04 16:46:17 -0400987 }
988
Kevin Lubickc1d08982020-04-06 13:52:15 -0400989 // getLocalToDevice returns a 4x4 matrix.
990 CanvasKit.SkCanvas.prototype.getLocalToDevice = function() {
Kevin Lubickc1d08982020-04-06 13:52:15 -0400991 // _getLocalToDevice will copy the values into the pointer.
Kevin Lubick6aa38692020-06-01 11:25:47 -0400992 this._getLocalToDevice(_scratch4x4MatrixPtr);
993 return copy4x4MatrixFromWasm(_scratch4x4MatrixPtr);
Kevin Lubickc1d08982020-04-06 13:52:15 -0400994 }
995
Nathaniel Nifong00de91c2020-05-06 16:22:33 -0400996 // findMarkedCTM returns a 4x4 matrix, or null if a matrix was not found at
997 // the provided marker.
998 CanvasKit.SkCanvas.prototype.findMarkedCTM = function(marker) {
Nathaniel Nifong00de91c2020-05-06 16:22:33 -0400999 // _getLocalToDevice will copy the values into the pointer.
Kevin Lubick6aa38692020-06-01 11:25:47 -04001000 var found = this._findMarkedCTM(marker, _scratch4x4MatrixPtr);
Nathaniel Nifong00de91c2020-05-06 16:22:33 -04001001 if (!found) {
1002 return null;
1003 }
Kevin Lubick6aa38692020-06-01 11:25:47 -04001004 return copy4x4MatrixFromWasm(_scratch4x4MatrixPtr);
Nathaniel Nifong00de91c2020-05-06 16:22:33 -04001005 }
1006
Kevin Lubickc1d08982020-04-06 13:52:15 -04001007 // getTotalMatrix returns the current matrix as a 3x3 matrix.
Kevin Lubick6bffe392020-04-02 15:24:15 -04001008 CanvasKit.SkCanvas.prototype.getTotalMatrix = function() {
Kevin Lubick6bffe392020-04-02 15:24:15 -04001009 // _getTotalMatrix will copy the values into the pointer.
Kevin Lubick6aa38692020-06-01 11:25:47 -04001010 this._getTotalMatrix(_scratch3x3MatrixPtr);
Kevin Lubick6bffe392020-04-02 15:24:15 -04001011 // read them out into an array. TODO(kjlubick): If we change SkMatrix to be
1012 // typedArrays, then we should return a typed array here too.
1013 var rv = new Array(9);
1014 for (var i = 0; i < 9; i++) {
Kevin Lubick6aa38692020-06-01 11:25:47 -04001015 rv[i] = CanvasKit.HEAPF32[_scratch3x3MatrixPtr/4 + i]; // divide by 4 to "cast" to float.
Kevin Lubick6bffe392020-04-02 15:24:15 -04001016 }
Kevin Lubick6bffe392020-04-02 15:24:15 -04001017 return rv;
1018 }
1019
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001020 // returns Uint8Array
1021 CanvasKit.SkCanvas.prototype.readPixels = function(x, y, w, h, alphaType,
Nathaniel Nifongb1ebbb12020-05-26 13:10:20 -04001022 colorType, colorSpace, dstRowBytes) {
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001023 // supply defaults (which are compatible with HTMLCanvas's getImageData)
1024 alphaType = alphaType || CanvasKit.AlphaType.Unpremul;
1025 colorType = colorType || CanvasKit.ColorType.RGBA_8888;
Nathaniel Nifongb1ebbb12020-05-26 13:10:20 -04001026 colorSpace = colorSpace || CanvasKit.SkColorSpace.SRGB;
1027 var pixBytes = 4;
1028 if (colorType === CanvasKit.ColorType.RGBA_F16) {
1029 pixBytes = 8;
1030 }
1031 dstRowBytes = dstRowBytes || (pixBytes * w);
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001032
1033 var len = h * dstRowBytes
1034 var pptr = CanvasKit._malloc(len);
1035 var ok = this._readPixels({
1036 'width': w,
1037 'height': h,
Kevin Lubick52b9f372018-12-04 13:57:36 -05001038 'colorType': colorType,
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001039 'alphaType': alphaType,
Nathaniel Nifongb1ebbb12020-05-26 13:10:20 -04001040 'colorSpace': colorSpace,
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001041 }, pptr, dstRowBytes, x, y);
1042 if (!ok) {
1043 CanvasKit._free(pptr);
1044 return null;
1045 }
1046
1047 // The first typed array is just a view into memory. Because we will
1048 // be free-ing that, we call slice to make a persistent copy.
Bryce Thomas1fa54042020-01-14 13:46:30 -08001049 var pixels = new Uint8Array(CanvasKit.HEAPU8.buffer, pptr, len).slice();
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001050 CanvasKit._free(pptr);
1051 return pixels;
1052 }
1053
Kevin Lubickcf118922020-05-28 14:43:38 -04001054 // pixels should be a Uint8Array or a plain JS array.
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001055 CanvasKit.SkCanvas.prototype.writePixels = function(pixels, srcWidth, srcHeight,
Nathaniel Nifongb1ebbb12020-05-26 13:10:20 -04001056 destX, destY, alphaType, colorType, colorSpace) {
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001057 if (pixels.byteLength % (srcWidth * srcHeight)) {
1058 throw 'pixels length must be a multiple of the srcWidth * srcHeight';
1059 }
1060 var bytesPerPixel = pixels.byteLength / (srcWidth * srcHeight);
1061 // supply defaults (which are compatible with HTMLCanvas's putImageData)
1062 alphaType = alphaType || CanvasKit.AlphaType.Unpremul;
1063 colorType = colorType || CanvasKit.ColorType.RGBA_8888;
Nathaniel Nifongb1ebbb12020-05-26 13:10:20 -04001064 colorSpace = colorSpace || CanvasKit.SkColorSpace.SRGB;
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001065 var srcRowBytes = bytesPerPixel * srcWidth;
1066
Kevin Lubick69e46da2020-06-05 07:13:48 -04001067 var pptr = copy1dArray(pixels, "HEAPU8");
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001068 var ok = this._writePixels({
1069 'width': srcWidth,
1070 'height': srcHeight,
1071 'colorType': colorType,
1072 'alphaType': alphaType,
Nathaniel Nifongb1ebbb12020-05-26 13:10:20 -04001073 'colorSpace': colorSpace,
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001074 }, pptr, srcRowBytes, destX, destY);
1075
Kevin Lubickcf118922020-05-28 14:43:38 -04001076 freeArraysThatAreNotMallocedByUsers(pptr, pixels);
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001077 return ok;
Kevin Lubick52b9f372018-12-04 13:57:36 -05001078 }
1079
Nathaniel Nifong1bedbeb2020-05-04 16:46:17 -04001080 CanvasKit.SkColorFilter.MakeBlend = function(color4f, mode) {
Kevin Lubick6aa38692020-06-01 11:25:47 -04001081 var cPtr = copyColorToWasm(color4f);
Nathaniel Nifong1bedbeb2020-05-04 16:46:17 -04001082 var result = CanvasKit.SkColorFilter._MakeBlend(cPtr, mode);
Nathaniel Nifong1bedbeb2020-05-04 16:46:17 -04001083 return result;
1084 }
1085
Kevin Lubickd3729342019-09-12 11:11:25 -04001086 // colorMatrix is an SkColorMatrix (e.g. Float32Array of length 20)
1087 CanvasKit.SkColorFilter.MakeMatrix = function(colorMatrix) {
1088 if (!colorMatrix || colorMatrix.length !== 20) {
Kevin Lubick6bffe392020-04-02 15:24:15 -04001089 throw 'invalid color matrix';
Kevin Lubickd3729342019-09-12 11:11:25 -04001090 }
Kevin Lubick69e46da2020-06-05 07:13:48 -04001091 var fptr = copy1dArray(colorMatrix, "HEAPF32");
Kevin Lubickd3729342019-09-12 11:11:25 -04001092 // We know skia memcopies the floats, so we can free our memory after the call returns.
1093 var m = CanvasKit.SkColorFilter._makeMatrix(fptr);
Kevin Lubickcf118922020-05-28 14:43:38 -04001094 freeArraysThatAreNotMallocedByUsers(fptr, colorMatrix);
Kevin Lubickd3729342019-09-12 11:11:25 -04001095 return m;
1096 }
1097
Kevin Lubick6bffe392020-04-02 15:24:15 -04001098 CanvasKit.SkImageFilter.MakeMatrixTransform = function(matr, filterQuality, input) {
1099 var matrPtr = copy3x3MatrixToWasm(matr);
Kevin Lubick6aa38692020-06-01 11:25:47 -04001100 return CanvasKit.SkImageFilter._MakeMatrixTransform(matrPtr, filterQuality, input);
Kevin Lubick6bffe392020-04-02 15:24:15 -04001101 }
1102
Nathaniel Nifong1bedbeb2020-05-04 16:46:17 -04001103 CanvasKit.SkPaint.prototype.getColor = function() {
Kevin Lubick6aa38692020-06-01 11:25:47 -04001104 this._getColor(_scratchColorPtr);
1105 return copyColorFromWasm(_scratchColorPtr);
Nathaniel Nifong1bedbeb2020-05-04 16:46:17 -04001106 }
1107
Nathaniel Nifongb1ebbb12020-05-26 13:10:20 -04001108 CanvasKit.SkPaint.prototype.setColor = function(color4f, colorSpace) {
1109 colorSpace = colorSpace || null; // null will be replaced with sRGB in the C++ method.
1110 // emscripten wouldn't bind undefined to the sk_sp<SkColorSpace> expected here.
Kevin Lubick6aa38692020-06-01 11:25:47 -04001111 var cPtr = copyColorToWasm(color4f);
Nathaniel Nifongb1ebbb12020-05-26 13:10:20 -04001112 this._setColor(cPtr, colorSpace);
Nathaniel Nifong1bedbeb2020-05-04 16:46:17 -04001113 }
1114
Kevin Lubick93f1a382020-06-02 16:15:23 -04001115 // The color components here are expected to be floating point values (nominally between
1116 // 0.0 and 1.0, but with wider color gamuts, the values could exceed this range). To convert
1117 // between standard 8 bit colors and floats, just divide by 255 before passing them in.
1118 CanvasKit.SkPaint.prototype.setColorComponents = function(r, g, b, a, colorSpace) {
1119 colorSpace = colorSpace || null; // null will be replaced with sRGB in the C++ method.
1120 // emscripten wouldn't bind undefined to the sk_sp<SkColorSpace> expected here.
1121 var cPtr = copyColorComponentsToWasm(r, g, b, a);
1122 this._setColor(cPtr, colorSpace);
1123 }
1124
Kevin Lubickcc13fd32019-04-05 13:00:01 -04001125 CanvasKit.SkSurface.prototype.captureFrameAsSkPicture = function(drawFrame) {
1126 // Set up SkPictureRecorder
1127 var spr = new CanvasKit.SkPictureRecorder();
1128 var canvas = spr.beginRecording(
1129 CanvasKit.LTRBRect(0, 0, this.width(), this.height()));
1130 drawFrame(canvas);
1131 var pic = spr.finishRecordingAsPicture();
1132 spr.delete();
1133 // TODO: do we need to clean up the memory for canvas?
1134 // If we delete it here, saveAsFile doesn't work correctly.
1135 return pic;
1136 }
1137
Kevin Lubick359a7e32019-03-19 09:34:37 -04001138 CanvasKit.SkSurface.prototype.requestAnimationFrame = function(callback, dirtyRect) {
1139 if (!this._cached_canvas) {
1140 this._cached_canvas = this.getCanvas();
1141 }
1142 window.requestAnimationFrame(function() {
Kevin Lubick39026282019-03-28 12:46:40 -04001143 if (this._context !== undefined) {
1144 CanvasKit.setCurrentContext(this._context);
1145 }
Kevin Lubick359a7e32019-03-19 09:34:37 -04001146
1147 callback(this._cached_canvas);
1148
Bryce Thomas2c5b8562020-01-22 13:49:41 -08001149 // We do not dispose() of the SkSurface here, as the client will typically
1150 // call requestAnimationFrame again from within the supplied callback.
1151 // For drawing a single frame, prefer drawOnce().
Bryce Thomas9331ca02020-05-29 16:51:21 -07001152 this.flush(dirtyRect);
Kevin Lubick359a7e32019-03-19 09:34:37 -04001153 }.bind(this));
1154 }
1155
Kevin Lubick52379332020-01-27 10:01:25 -05001156 // drawOnce will dispose of the surface after drawing the frame using the provided
1157 // callback.
Bryce Thomas2c5b8562020-01-22 13:49:41 -08001158 CanvasKit.SkSurface.prototype.drawOnce = function(callback, dirtyRect) {
1159 if (!this._cached_canvas) {
1160 this._cached_canvas = this.getCanvas();
1161 }
1162 window.requestAnimationFrame(function() {
1163 if (this._context !== undefined) {
1164 CanvasKit.setCurrentContext(this._context);
1165 }
1166 callback(this._cached_canvas);
1167
Bryce Thomas9331ca02020-05-29 16:51:21 -07001168 this.flush(dirtyRect);
Bryce Thomas2c5b8562020-01-22 13:49:41 -08001169 this.dispose();
1170 }.bind(this));
1171 }
1172
Nathaniel Nifong23b0ed92020-03-04 15:43:50 -05001173 CanvasKit.SkPathEffect.MakeDash = function(intervals, phase) {
1174 if (!phase) {
1175 phase = 0;
1176 }
1177 if (!intervals.length || intervals.length % 2 === 1) {
1178 throw 'Intervals array must have even length';
1179 }
Kevin Lubick69e46da2020-06-05 07:13:48 -04001180 var ptr = copy1dArray(intervals, "HEAPF32");
Kevin Lubickf279c632020-03-18 09:53:55 -04001181 var dpe = CanvasKit.SkPathEffect._MakeDash(ptr, intervals.length, phase);
Kevin Lubickcf118922020-05-28 14:43:38 -04001182 freeArraysThatAreNotMallocedByUsers(ptr, intervals);
Nathaniel Nifong23b0ed92020-03-04 15:43:50 -05001183 return dpe;
1184 }
1185
Nathaniel Nifongb1ebbb12020-05-26 13:10:20 -04001186 CanvasKit.SkShader.Color = function(color4f, colorSpace) {
1187 colorSpace = colorSpace || null
Kevin Lubick6aa38692020-06-01 11:25:47 -04001188 var cPtr = copyColorToWasm(color4f);
Nathaniel Nifongb1ebbb12020-05-26 13:10:20 -04001189 var result = CanvasKit.SkShader._Color(cPtr, colorSpace);
Nathaniel Nifong1bedbeb2020-05-04 16:46:17 -04001190 return result;
1191 }
1192
Nathaniel Nifongb1ebbb12020-05-26 13:10:20 -04001193 CanvasKit.SkShader.MakeLinearGradient = function(start, end, colors, pos, mode, localMatrix, flags, colorSpace) {
1194 colorSpace = colorSpace || null
Kevin Lubick69e46da2020-06-05 07:13:48 -04001195 var colorPtr = copy2dArray(colors, "HEAPF32");
1196 var posPtr = copy1dArray(pos, "HEAPF32");
Nathaniel Nifong23b0ed92020-03-04 15:43:50 -05001197 flags = flags || 0;
Kevin Lubick6bffe392020-04-02 15:24:15 -04001198 var localMatrixPtr = copy3x3MatrixToWasm(localMatrix);
Nathaniel Nifong23b0ed92020-03-04 15:43:50 -05001199
Kevin Lubick6bffe392020-04-02 15:24:15 -04001200 var lgs = CanvasKit._MakeLinearGradientShader(start, end, colorPtr, posPtr,
Nathaniel Nifongb1ebbb12020-05-26 13:10:20 -04001201 colors.length, mode, flags, localMatrixPtr, colorSpace);
Nathaniel Nifong23b0ed92020-03-04 15:43:50 -05001202
1203 CanvasKit._free(colorPtr);
Kevin Lubickcf118922020-05-28 14:43:38 -04001204 freeArraysThatAreNotMallocedByUsers(posPtr, pos);
Nathaniel Nifong23b0ed92020-03-04 15:43:50 -05001205 return lgs;
1206 }
1207
Nathaniel Nifongb1ebbb12020-05-26 13:10:20 -04001208 CanvasKit.SkShader.MakeRadialGradient = function(center, radius, colors, pos, mode, localMatrix, flags, colorSpace) {
1209 colorSpace = colorSpace || null
Kevin Lubick69e46da2020-06-05 07:13:48 -04001210 var colorPtr = copy2dArray(colors, "HEAPF32");
1211 var posPtr = copy1dArray(pos, "HEAPF32");
Nathaniel Nifong23b0ed92020-03-04 15:43:50 -05001212 flags = flags || 0;
Kevin Lubick6bffe392020-04-02 15:24:15 -04001213 var localMatrixPtr = copy3x3MatrixToWasm(localMatrix);
Nathaniel Nifong23b0ed92020-03-04 15:43:50 -05001214
Kevin Lubick6bffe392020-04-02 15:24:15 -04001215 var rgs = CanvasKit._MakeRadialGradientShader(center, radius, colorPtr, posPtr,
Nathaniel Nifongb1ebbb12020-05-26 13:10:20 -04001216 colors.length, mode, flags, localMatrixPtr, colorSpace);
Nathaniel Nifong23b0ed92020-03-04 15:43:50 -05001217
1218 CanvasKit._free(colorPtr);
Kevin Lubickcf118922020-05-28 14:43:38 -04001219 freeArraysThatAreNotMallocedByUsers(posPtr, pos);
Nathaniel Nifong23b0ed92020-03-04 15:43:50 -05001220 return rgs;
1221 }
1222
Nathaniel Nifongb1ebbb12020-05-26 13:10:20 -04001223 CanvasKit.SkShader.MakeSweepGradient = function(cx, cy, colors, pos, mode, localMatrix, flags, startAngle, endAngle, colorSpace) {
1224 colorSpace = colorSpace || null
Kevin Lubick69e46da2020-06-05 07:13:48 -04001225 var colorPtr = copy2dArray(colors, "HEAPF32");
1226 var posPtr = copy1dArray(pos, "HEAPF32");
Dan Field3d44f732020-03-16 09:17:30 -07001227 flags = flags || 0;
1228 startAngle = startAngle || 0;
1229 endAngle = endAngle || 360;
Kevin Lubick6bffe392020-04-02 15:24:15 -04001230 var localMatrixPtr = copy3x3MatrixToWasm(localMatrix);
Dan Field3d44f732020-03-16 09:17:30 -07001231
1232 var sgs = CanvasKit._MakeSweepGradientShader(cx, cy, colorPtr, posPtr,
Kevin Lubick6bffe392020-04-02 15:24:15 -04001233 colors.length, mode,
1234 startAngle, endAngle, flags,
Nathaniel Nifongb1ebbb12020-05-26 13:10:20 -04001235 localMatrixPtr, colorSpace);
Dan Field3d44f732020-03-16 09:17:30 -07001236
1237 CanvasKit._free(colorPtr);
Kevin Lubickcf118922020-05-28 14:43:38 -04001238 freeArraysThatAreNotMallocedByUsers(posPtr, pos);
Dan Field3d44f732020-03-16 09:17:30 -07001239 return sgs;
1240 }
1241
Nathaniel Nifong23b0ed92020-03-04 15:43:50 -05001242 CanvasKit.SkShader.MakeTwoPointConicalGradient = function(start, startRadius, end, endRadius,
Nathaniel Nifongb1ebbb12020-05-26 13:10:20 -04001243 colors, pos, mode, localMatrix, flags, colorSpace) {
1244 colorSpace = colorSpace || null
Kevin Lubick69e46da2020-06-05 07:13:48 -04001245 var colorPtr = copy2dArray(colors, "HEAPF32");
1246 var posPtr = copy1dArray(pos, "HEAPF32");
Nathaniel Nifong23b0ed92020-03-04 15:43:50 -05001247 flags = flags || 0;
Kevin Lubick6bffe392020-04-02 15:24:15 -04001248 var localMatrixPtr = copy3x3MatrixToWasm(localMatrix);
Nathaniel Nifong23b0ed92020-03-04 15:43:50 -05001249
Kevin Lubick6bffe392020-04-02 15:24:15 -04001250 var rgs = CanvasKit._MakeTwoPointConicalGradientShader(
Nathaniel Nifong23b0ed92020-03-04 15:43:50 -05001251 start, startRadius, end, endRadius,
Nathaniel Nifongb1ebbb12020-05-26 13:10:20 -04001252 colorPtr, posPtr, colors.length, mode, flags, localMatrixPtr, colorSpace);
Nathaniel Nifong23b0ed92020-03-04 15:43:50 -05001253
1254 CanvasKit._free(colorPtr);
Kevin Lubickcf118922020-05-28 14:43:38 -04001255 freeArraysThatAreNotMallocedByUsers(posPtr, pos);
Nathaniel Nifong23b0ed92020-03-04 15:43:50 -05001256 return rgs;
1257 }
1258
1259 // temporary support for deprecated names.
Nathaniel Nifongc8f95e22020-03-09 11:52:51 -04001260 CanvasKit.MakeSkDashPathEffect = CanvasKit.SkPathEffect.MakeDash;
1261 CanvasKit.MakeLinearGradientShader = CanvasKit.SkShader.MakeLinearGradient;
1262 CanvasKit.MakeRadialGradientShader = CanvasKit.SkShader.MakeRadialGradient;
1263 CanvasKit.MakeTwoPointConicalGradientShader = CanvasKit.SkShader.MakeTwoPointConicalGradient;
Nathaniel Nifong23b0ed92020-03-04 15:43:50 -05001264
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001265 // Run through the JS files that are added at compile time.
1266 if (CanvasKit._extraInitializations) {
1267 CanvasKit._extraInitializations.forEach(function(init) {
1268 init();
1269 });
Kevin Lubickeb2f6b02018-11-29 15:07:02 -05001270 }
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001271}; // end CanvasKit.onRuntimeInitialized, that is, anything changing prototypes or dynamic.
Kevin Lubickeb2f6b02018-11-29 15:07:02 -05001272
Nathaniel Nifong1bedbeb2020-05-04 16:46:17 -04001273// Accepts an object holding two canvaskit colors.
1274// {
1275// ambient: {r, g, b, a},
1276// spot: {r, g, b, a},
1277// }
1278// Returns the same format
1279CanvasKit.computeTonalColors = function(tonalColors) {
Kevin Lubick6aa38692020-06-01 11:25:47 -04001280 var cPtrAmbi = copyColorToWasmNoScratch(tonalColors['ambient']);
1281 var cPtrSpot = copyColorToWasmNoScratch(tonalColors['spot']);
Nathaniel Nifong1bedbeb2020-05-04 16:46:17 -04001282 this._computeTonalColors(cPtrAmbi, cPtrSpot);
1283 var result = {
1284 'ambient': copyColorFromWasm(cPtrAmbi),
1285 'spot': copyColorFromWasm(cPtrSpot),
1286 }
Kevin Lubick6aa38692020-06-01 11:25:47 -04001287 freeArraysThatAreNotMallocedByUsers(cPtrAmbi);
1288 freeArraysThatAreNotMallocedByUsers(cPtrSpot);
Nathaniel Nifong1bedbeb2020-05-04 16:46:17 -04001289 return result;
1290}
1291
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001292CanvasKit.LTRBRect = function(l, t, r, b) {
1293 return {
1294 fLeft: l,
1295 fTop: t,
1296 fRight: r,
1297 fBottom: b,
1298 };
Kevin Lubick1a05fce2018-11-20 12:51:16 -05001299}
1300
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001301CanvasKit.XYWHRect = function(x, y, w, h) {
1302 return {
1303 fLeft: x,
1304 fTop: y,
1305 fRight: x+w,
1306 fBottom: y+h,
1307 };
Kevin Lubick1a05fce2018-11-20 12:51:16 -05001308}
1309
Kevin Lubick7d644e12019-09-11 14:22:22 -04001310// RRectXY returns an RRect with the given rect and a radiusX and radiusY for
1311// all 4 corners.
1312CanvasKit.RRectXY = function(rect, rx, ry) {
1313 return {
1314 rect: rect,
1315 rx1: rx,
1316 ry1: ry,
1317 rx2: rx,
1318 ry2: ry,
1319 rx3: rx,
1320 ry3: ry,
1321 rx4: rx,
1322 ry4: ry,
1323 };
1324}
1325
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001326CanvasKit.MakePathFromCmds = function(cmds) {
1327 var ptrLen = loadCmdsTypedArray(cmds);
1328 var path = CanvasKit._MakePathFromCmds(ptrLen[0], ptrLen[1]);
1329 CanvasKit._free(ptrLen[0]);
1330 return path;
1331}
1332
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001333// data is a TypedArray or ArrayBuffer e.g. from fetch().then(resp.arrayBuffer())
Kevin Lubick6b921b72019-09-18 16:18:17 -04001334CanvasKit.MakeAnimatedImageFromEncoded = function(data) {
1335 data = new Uint8Array(data);
1336
1337 var iptr = CanvasKit._malloc(data.byteLength);
1338 CanvasKit.HEAPU8.set(data, iptr);
1339 var img = CanvasKit._decodeAnimatedImage(iptr, data.byteLength);
1340 if (!img) {
1341 SkDebug('Could not decode animated image');
1342 return null;
1343 }
1344 return img;
1345}
1346
1347// data is a TypedArray or ArrayBuffer e.g. from fetch().then(resp.arrayBuffer())
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001348CanvasKit.MakeImageFromEncoded = function(data) {
1349 data = new Uint8Array(data);
1350
1351 var iptr = CanvasKit._malloc(data.byteLength);
1352 CanvasKit.HEAPU8.set(data, iptr);
1353 var img = CanvasKit._decodeImage(iptr, data.byteLength);
1354 if (!img) {
1355 SkDebug('Could not decode image');
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001356 return null;
1357 }
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001358 return img;
1359}
1360
Kevin Lubickeda0b432019-12-02 08:26:48 -05001361// pixels must be a Uint8Array with bytes representing the pixel values
1362// (e.g. each set of 4 bytes could represent RGBA values for a single pixel).
Nathaniel Nifongb1ebbb12020-05-26 13:10:20 -04001363CanvasKit.MakeImage = function(pixels, width, height, alphaType, colorType, colorSpace) {
Kevin Lubickeda0b432019-12-02 08:26:48 -05001364 var bytesPerPixel = pixels.length / (width * height);
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001365 var info = {
1366 'width': width,
1367 'height': height,
1368 'alphaType': alphaType,
1369 'colorType': colorType,
Nathaniel Nifongb1ebbb12020-05-26 13:10:20 -04001370 'colorSpace': colorSpace,
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001371 };
Kevin Lubick69e46da2020-06-05 07:13:48 -04001372 var pptr = copy1dArray(pixels, "HEAPU8");
Kevin Lubickeda0b432019-12-02 08:26:48 -05001373 // No need to _free pptr, Image takes it with SkData::MakeFromMalloc
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001374
Kevin Lubickeda0b432019-12-02 08:26:48 -05001375 return CanvasKit._MakeImage(info, pptr, pixels.length, width * bytesPerPixel);
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001376}
1377
Nathaniel Nifong1bedbeb2020-05-04 16:46:17 -04001378// colors is an array of float color arrays
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001379CanvasKit.MakeSkVertices = function(mode, positions, textureCoordinates, colors,
Mike Reed5caf9352020-03-02 14:57:09 -05001380 indices, isVolatile) {
Kevin Lubickb3574c92019-03-06 08:25:36 -05001381 // Default isVolitile to true if not set
1382 isVolatile = isVolatile === undefined ? true : isVolatile;
Kevin Lubickd6ba7252019-06-03 14:38:05 -04001383 var idxCount = (indices && indices.length) || 0;
1384
1385 var flags = 0;
1386 // These flags are from SkVertices.h and should be kept in sync with those.
1387 if (textureCoordinates && textureCoordinates.length) {
1388 flags |= (1 << 0);
1389 }
1390 if (colors && colors.length) {
1391 flags |= (1 << 1);
1392 }
Kevin Lubickd6ba7252019-06-03 14:38:05 -04001393 if (!isVolatile) {
Mike Reed5caf9352020-03-02 14:57:09 -05001394 flags |= (1 << 2);
Kevin Lubickd6ba7252019-06-03 14:38:05 -04001395 }
1396
1397 var builder = new CanvasKit._SkVerticesBuilder(mode, positions.length, idxCount, flags);
1398
Kevin Lubick69e46da2020-06-05 07:13:48 -04001399 copy2dArray(positions, "HEAPF32", builder.positions());
Kevin Lubickd6ba7252019-06-03 14:38:05 -04001400 if (builder.texCoords()) {
Kevin Lubick69e46da2020-06-05 07:13:48 -04001401 copy2dArray(textureCoordinates, "HEAPF32", builder.texCoords());
Kevin Lubickd6ba7252019-06-03 14:38:05 -04001402 }
1403 if (builder.colors()) {
Nathaniel Nifonge5d32542020-03-26 09:27:48 -04001404 // Convert from canvaskit 4f colors to 32 bit uint colors which builder supports.
Kevin Lubick69e46da2020-06-05 07:13:48 -04001405 copy1dArray(colors.map(toUint32Color), "HEAPU32", builder.colors());
Kevin Lubickd6ba7252019-06-03 14:38:05 -04001406 }
Kevin Lubickd6ba7252019-06-03 14:38:05 -04001407 if (builder.indices()) {
Kevin Lubick69e46da2020-06-05 07:13:48 -04001408 copy1dArray(indices, "HEAPU16", builder.indices());
Kevin Lubickd6ba7252019-06-03 14:38:05 -04001409 }
Kevin Lubickb3574c92019-03-06 08:25:36 -05001410
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001411 var idxCount = (indices && indices.length) || 0;
Kevin Lubickd6ba7252019-06-03 14:38:05 -04001412 // Create the vertices, which owns the memory that the builder had allocated.
1413 return builder.detach();
Kevin Lubicka4f218d2020-01-14 08:39:09 -05001414};