1
2 /*
3 * Copyright 2011 Google Inc.
4 *
5 * Use of this source code is governed by a BSD-style license that can be
6 * found in the LICENSE file.
7 */
8 #include "SkMatrix.h"
9 #include "SkMalloc.h"
10
11 // FIXME: needs to be in a header
12 bool SkSetPoly3To3_D(SkMatrix* matrix, const SkPoint src[3], const SkPoint dst[3]);
13
14 typedef int64_t SkDScalar;
15
SkDScalar_toScalar(SkDScalar value)16 static SkScalar SkDScalar_toScalar(SkDScalar value) {
17 SkDScalar result = (value + (1 << 15)) >> 16;
18 SkDEBUGCODE(int top = static_cast<int>(result >> 31);)
19 SkASSERT(top == 0 || top == -1);
20 return (SkScalar)result;
21 }
22
SkDScalar_setMul(SkScalar a,SkScalar b)23 static SkDScalar SkDScalar_setMul(SkScalar a, SkScalar b) {
24 return (SkDScalar) ((SkDScalar) a * (SkDScalar) b);
25 }
26
computeOuterProduct(SkMatrix * matrix,const SkPoint pts0[3],const SkPoint & ave0,const SkPoint pts1[3],const SkPoint & ave1)27 static void computeOuterProduct(SkMatrix* matrix,
28 const SkPoint pts0[3], const SkPoint& ave0,
29 const SkPoint pts1[3], const SkPoint& ave1) {
30 SkDScalar tmp[4];
31 sk_bzero(tmp, sizeof(tmp));
32
33 for (int i = 0; i < 3; i++) {
34 SkScalar x0 = pts0[i].fX - ave0.fX;
35 SkScalar y0 = pts0[i].fY - ave0.fY;
36 SkScalar x1 = pts1[i].fX - ave1.fX;
37 SkScalar y1 = pts1[i].fY - ave1.fY;
38 tmp[0] += SkDScalar_setMul(x0, x1);
39 tmp[1] += SkDScalar_setMul(x0, y1);
40 tmp[2] += SkDScalar_setMul(y0, x1);
41 tmp[3] += SkDScalar_setMul(y0, y1);
42 }
43 matrix->reset();
44 matrix->setScaleX(SkDScalar_toScalar(tmp[0]));
45 matrix->setSkewY( SkDScalar_toScalar(tmp[1]));
46 matrix->setSkewX( SkDScalar_toScalar(tmp[2]));
47 matrix->setScaleY(SkDScalar_toScalar(tmp[3]));
48 }
49
dot(SkScalar ax,SkScalar ay,SkScalar bx,SkScalar by)50 static SkScalar dot(SkScalar ax, SkScalar ay, SkScalar bx, SkScalar by) {
51 return SkDScalar_toScalar(SkDScalar_setMul(ax, bx) +
52 SkDScalar_setMul(ay, by));
53 }
54
SkSetPoly3To3_D(SkMatrix * matrix,const SkPoint src[3],const SkPoint dst[3])55 bool SkSetPoly3To3_D(SkMatrix* matrix, const SkPoint src[3], const SkPoint dst[3]) {
56 const SkPoint& srcAve = src[0];
57 const SkPoint& dstAve = dst[0];
58
59 SkMatrix srcOP, dstOP;
60
61 computeOuterProduct(&srcOP, src, srcAve, src, srcAve);
62
63 if (!srcOP.invert(&srcOP)) {
64 return false;
65 }
66
67 computeOuterProduct(&dstOP, src, srcAve, dst, dstAve);
68
69 matrix->setConcat(dstOP, srcOP);
70 matrix->setTranslateX(dstAve.fX - dot(srcAve.fX, srcAve.fY,
71 matrix->getScaleX(), matrix->getSkewX()));
72 matrix->setTranslateY(dstAve.fY - dot(srcAve.fX, srcAve.fY,
73 matrix->getSkewY(), matrix->getScaleY()));
74 return true;
75 }
76