1/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17// The highest z value can't be higher than (CASTER_Z_CAP_RATIO * light.z)
18#define CASTER_Z_CAP_RATIO 0.95f
19
20// When there is no umbra, then just fake the umbra using
21// centroid * (1 - FAKE_UMBRA_SIZE_RATIO) + outline * FAKE_UMBRA_SIZE_RATIO
22#define FAKE_UMBRA_SIZE_RATIO 0.05f
23
24// When the polygon is about 90 vertices, the penumbra + umbra can reach 270 rays.
25// That is consider pretty fine tessllated polygon so far.
26// This is just to prevent using too much some memory when edge slicing is not
27// needed any more.
28#define FINE_TESSELLATED_POLYGON_RAY_NUMBER 270
29/**
30 * Extra vertices for the corner for smoother corner.
31 * Only for outer loop.
32 * Note that we use such extra memory to avoid an extra loop.
33 */
34// For half circle, we could add EXTRA_VERTEX_PER_PI vertices.
35// Set to 1 if we don't want to have any.
36#define SPOT_EXTRA_CORNER_VERTEX_PER_PI 18
37
38// For the whole polygon, the sum of all the deltas b/t normals is 2 * M_PI,
39// therefore, the maximum number of extra vertices will be twice bigger.
40#define SPOT_MAX_EXTRA_CORNER_VERTEX_NUMBER  (2 * SPOT_EXTRA_CORNER_VERTEX_PER_PI)
41
42// For each RADIANS_DIVISOR, we would allocate one more vertex b/t the normals.
43#define SPOT_CORNER_RADIANS_DIVISOR (M_PI / SPOT_EXTRA_CORNER_VERTEX_PER_PI)
44
45#define PENUMBRA_ALPHA 0.0f
46#define UMBRA_ALPHA 1.0f
47
48#include "SpotShadow.h"
49
50#include "ShadowTessellator.h"
51#include "Vertex.h"
52#include "VertexBuffer.h"
53#include "utils/MathUtils.h"
54
55#include <algorithm>
56#include <math.h>
57#include <stdlib.h>
58#include <utils/Log.h>
59
60// TODO: After we settle down the new algorithm, we can remove the old one and
61// its utility functions.
62// Right now, we still need to keep it for comparison purpose and future expansion.
63namespace android {
64namespace uirenderer {
65
66static const float EPSILON = 1e-7;
67
68/**
69 * For each polygon's vertex, the light center will project it to the receiver
70 * as one of the outline vertex.
71 * For each outline vertex, we need to store the position and normal.
72 * Normal here is defined against the edge by the current vertex and the next vertex.
73 */
74struct OutlineData {
75    Vector2 position;
76    Vector2 normal;
77    float radius;
78};
79
80/**
81 * For each vertex, we need to keep track of its angle, whether it is penumbra or
82 * umbra, and its corresponding vertex index.
83 */
84struct SpotShadow::VertexAngleData {
85    // The angle to the vertex from the centroid.
86    float mAngle;
87    // True is the vertex comes from penumbra, otherwise it comes from umbra.
88    bool mIsPenumbra;
89    // The index of the vertex described by this data.
90    int mVertexIndex;
91    void set(float angle, bool isPenumbra, int index) {
92        mAngle = angle;
93        mIsPenumbra = isPenumbra;
94        mVertexIndex = index;
95    }
96};
97
98/**
99 * Calculate the angle between and x and a y coordinate.
100 * The atan2 range from -PI to PI.
101 */
102static float angle(const Vector2& point, const Vector2& center) {
103    return atan2(point.y - center.y, point.x - center.x);
104}
105
106/**
107 * Calculate the intersection of a ray with the line segment defined by two points.
108 *
109 * Returns a negative value in error conditions.
110
111 * @param rayOrigin The start of the ray
112 * @param dx The x vector of the ray
113 * @param dy The y vector of the ray
114 * @param p1 The first point defining the line segment
115 * @param p2 The second point defining the line segment
116 * @return The distance along the ray if it intersects with the line segment, negative if otherwise
117 */
118static float rayIntersectPoints(const Vector2& rayOrigin, float dx, float dy,
119        const Vector2& p1, const Vector2& p2) {
120    // The math below is derived from solving this formula, basically the
121    // intersection point should stay on both the ray and the edge of (p1, p2).
122    // solve([p1x+t*(p2x-p1x)=dx*t2+px,p1y+t*(p2y-p1y)=dy*t2+py],[t,t2]);
123
124    float divisor = (dx * (p1.y - p2.y) + dy * p2.x - dy * p1.x);
125    if (divisor == 0) return -1.0f; // error, invalid divisor
126
127#if DEBUG_SHADOW
128    float interpVal = (dx * (p1.y - rayOrigin.y) + dy * rayOrigin.x - dy * p1.x) / divisor;
129    if (interpVal < 0 || interpVal > 1) {
130        ALOGW("rayIntersectPoints is hitting outside the segment %f", interpVal);
131    }
132#endif
133
134    float distance = (p1.x * (rayOrigin.y - p2.y) + p2.x * (p1.y - rayOrigin.y) +
135            rayOrigin.x * (p2.y - p1.y)) / divisor;
136
137    return distance; // may be negative in error cases
138}
139
140/**
141 * Sort points by their X coordinates
142 *
143 * @param points the points as a Vector2 array.
144 * @param pointsLength the number of vertices of the polygon.
145 */
146void SpotShadow::xsort(Vector2* points, int pointsLength) {
147    auto cmp = [](const Vector2& a, const Vector2& b) -> bool {
148        return a.x < b.x;
149    };
150    std::sort(points, points + pointsLength, cmp);
151}
152
153/**
154 * compute the convex hull of a collection of Points
155 *
156 * @param points the points as a Vector2 array.
157 * @param pointsLength the number of vertices of the polygon.
158 * @param retPoly pre allocated array of floats to put the vertices
159 * @return the number of points in the polygon 0 if no intersection
160 */
161int SpotShadow::hull(Vector2* points, int pointsLength, Vector2* retPoly) {
162    xsort(points, pointsLength);
163    int n = pointsLength;
164    Vector2 lUpper[n];
165    lUpper[0] = points[0];
166    lUpper[1] = points[1];
167
168    int lUpperSize = 2;
169
170    for (int i = 2; i < n; i++) {
171        lUpper[lUpperSize] = points[i];
172        lUpperSize++;
173
174        while (lUpperSize > 2 && !ccw(
175                lUpper[lUpperSize - 3].x, lUpper[lUpperSize - 3].y,
176                lUpper[lUpperSize - 2].x, lUpper[lUpperSize - 2].y,
177                lUpper[lUpperSize - 1].x, lUpper[lUpperSize - 1].y)) {
178            // Remove the middle point of the three last
179            lUpper[lUpperSize - 2].x = lUpper[lUpperSize - 1].x;
180            lUpper[lUpperSize - 2].y = lUpper[lUpperSize - 1].y;
181            lUpperSize--;
182        }
183    }
184
185    Vector2 lLower[n];
186    lLower[0] = points[n - 1];
187    lLower[1] = points[n - 2];
188
189    int lLowerSize = 2;
190
191    for (int i = n - 3; i >= 0; i--) {
192        lLower[lLowerSize] = points[i];
193        lLowerSize++;
194
195        while (lLowerSize > 2 && !ccw(
196                lLower[lLowerSize - 3].x, lLower[lLowerSize - 3].y,
197                lLower[lLowerSize - 2].x, lLower[lLowerSize - 2].y,
198                lLower[lLowerSize - 1].x, lLower[lLowerSize - 1].y)) {
199            // Remove the middle point of the three last
200            lLower[lLowerSize - 2] = lLower[lLowerSize - 1];
201            lLowerSize--;
202        }
203    }
204
205    // output points in CW ordering
206    const int total = lUpperSize + lLowerSize - 2;
207    int outIndex = total - 1;
208    for (int i = 0; i < lUpperSize; i++) {
209        retPoly[outIndex] = lUpper[i];
210        outIndex--;
211    }
212
213    for (int i = 1; i < lLowerSize - 1; i++) {
214        retPoly[outIndex] = lLower[i];
215        outIndex--;
216    }
217    // TODO: Add test harness which verify that all the points are inside the hull.
218    return total;
219}
220
221/**
222 * Test whether the 3 points form a counter clockwise turn.
223 *
224 * @return true if a right hand turn
225 */
226bool SpotShadow::ccw(float ax, float ay, float bx, float by,
227        float cx, float cy) {
228    return (bx - ax) * (cy - ay) - (by - ay) * (cx - ax) > EPSILON;
229}
230
231/**
232 * Sort points about a center point
233 *
234 * @param poly The in and out polyogon as a Vector2 array.
235 * @param polyLength The number of vertices of the polygon.
236 * @param center the center ctr[0] = x , ctr[1] = y to sort around.
237 */
238void SpotShadow::sort(Vector2* poly, int polyLength, const Vector2& center) {
239    quicksortCirc(poly, 0, polyLength - 1, center);
240}
241
242/**
243 * Swap points pointed to by i and j
244 */
245void SpotShadow::swap(Vector2* points, int i, int j) {
246    Vector2 temp = points[i];
247    points[i] = points[j];
248    points[j] = temp;
249}
250
251/**
252 * quick sort implementation about the center.
253 */
254void SpotShadow::quicksortCirc(Vector2* points, int low, int high,
255        const Vector2& center) {
256    int i = low, j = high;
257    int p = low + (high - low) / 2;
258    float pivot = angle(points[p], center);
259    while (i <= j) {
260        while (angle(points[i], center) > pivot) {
261            i++;
262        }
263        while (angle(points[j], center) < pivot) {
264            j--;
265        }
266
267        if (i <= j) {
268            swap(points, i, j);
269            i++;
270            j--;
271        }
272    }
273    if (low < j) quicksortCirc(points, low, j, center);
274    if (i < high) quicksortCirc(points, i, high, center);
275}
276
277/**
278 * Test whether a point is inside the polygon.
279 *
280 * @param testPoint the point to test
281 * @param poly the polygon
282 * @return true if the testPoint is inside the poly.
283 */
284bool SpotShadow::testPointInsidePolygon(const Vector2 testPoint,
285        const Vector2* poly, int len) {
286    bool c = false;
287    float testx = testPoint.x;
288    float testy = testPoint.y;
289    for (int i = 0, j = len - 1; i < len; j = i++) {
290        float startX = poly[j].x;
291        float startY = poly[j].y;
292        float endX = poly[i].x;
293        float endY = poly[i].y;
294
295        if (((endY > testy) != (startY > testy))
296            && (testx < (startX - endX) * (testy - endY)
297             / (startY - endY) + endX)) {
298            c = !c;
299        }
300    }
301    return c;
302}
303
304/**
305 * Make the polygon turn clockwise.
306 *
307 * @param polygon the polygon as a Vector2 array.
308 * @param len the number of points of the polygon
309 */
310void SpotShadow::makeClockwise(Vector2* polygon, int len) {
311    if (polygon == nullptr  || len == 0) {
312        return;
313    }
314    if (!ShadowTessellator::isClockwise(polygon, len)) {
315        reverse(polygon, len);
316    }
317}
318
319/**
320 * Reverse the polygon
321 *
322 * @param polygon the polygon as a Vector2 array
323 * @param len the number of points of the polygon
324 */
325void SpotShadow::reverse(Vector2* polygon, int len) {
326    int n = len / 2;
327    for (int i = 0; i < n; i++) {
328        Vector2 tmp = polygon[i];
329        int k = len - 1 - i;
330        polygon[i] = polygon[k];
331        polygon[k] = tmp;
332    }
333}
334
335/**
336 * Compute a horizontal circular polygon about point (x , y , height) of radius
337 * (size)
338 *
339 * @param points number of the points of the output polygon.
340 * @param lightCenter the center of the light.
341 * @param size the light size.
342 * @param ret result polygon.
343 */
344void SpotShadow::computeLightPolygon(int points, const Vector3& lightCenter,
345        float size, Vector3* ret) {
346    // TODO: Caching all the sin / cos values and store them in a look up table.
347    for (int i = 0; i < points; i++) {
348        float angle = 2 * i * M_PI / points;
349        ret[i].x = cosf(angle) * size + lightCenter.x;
350        ret[i].y = sinf(angle) * size + lightCenter.y;
351        ret[i].z = lightCenter.z;
352    }
353}
354
355/**
356 * From light center, project one vertex to the z=0 surface and get the outline.
357 *
358 * @param outline The result which is the outline position.
359 * @param lightCenter The center of light.
360 * @param polyVertex The input polygon's vertex.
361 *
362 * @return float The ratio of (polygon.z / light.z - polygon.z)
363 */
364float SpotShadow::projectCasterToOutline(Vector2& outline,
365        const Vector3& lightCenter, const Vector3& polyVertex) {
366    float lightToPolyZ = lightCenter.z - polyVertex.z;
367    float ratioZ = CASTER_Z_CAP_RATIO;
368    if (lightToPolyZ != 0) {
369        // If any caster's vertex is almost above the light, we just keep it as 95%
370        // of the height of the light.
371        ratioZ = MathUtils::clamp(polyVertex.z / lightToPolyZ, 0.0f, CASTER_Z_CAP_RATIO);
372    }
373
374    outline.x = polyVertex.x - ratioZ * (lightCenter.x - polyVertex.x);
375    outline.y = polyVertex.y - ratioZ * (lightCenter.y - polyVertex.y);
376    return ratioZ;
377}
378
379/**
380 * Generate the shadow spot light of shape lightPoly and a object poly
381 *
382 * @param isCasterOpaque whether the caster is opaque
383 * @param lightCenter the center of the light
384 * @param lightSize the radius of the light
385 * @param poly x,y,z vertexes of a convex polygon that occludes the light source
386 * @param polyLength number of vertexes of the occluding polygon
387 * @param shadowTriangleStrip return an (x,y,alpha) triangle strip representing the shadow. Return
388 *                            empty strip if error.
389 */
390void SpotShadow::createSpotShadow(bool isCasterOpaque, const Vector3& lightCenter,
391        float lightSize, const Vector3* poly, int polyLength, const Vector3& polyCentroid,
392        VertexBuffer& shadowTriangleStrip) {
393    if (CC_UNLIKELY(lightCenter.z <= 0)) {
394        ALOGW("Relative Light Z is not positive. No spot shadow!");
395        return;
396    }
397    if (CC_UNLIKELY(polyLength < 3)) {
398#if DEBUG_SHADOW
399        ALOGW("Invalid polygon length. No spot shadow!");
400#endif
401        return;
402    }
403    OutlineData outlineData[polyLength];
404    Vector2 outlineCentroid;
405    // Calculate the projected outline for each polygon's vertices from the light center.
406    //
407    //                       O     Light
408    //                      /
409    //                    /
410    //                   .     Polygon vertex
411    //                 /
412    //               /
413    //              O     Outline vertices
414    //
415    // Ratio = (Poly - Outline) / (Light - Poly)
416    // Outline.x = Poly.x - Ratio * (Light.x - Poly.x)
417    // Outline's radius / Light's radius = Ratio
418
419    // Compute the last outline vertex to make sure we can get the normal and outline
420    // in one single loop.
421    projectCasterToOutline(outlineData[polyLength - 1].position, lightCenter,
422            poly[polyLength - 1]);
423
424    // Take the outline's polygon, calculate the normal for each outline edge.
425    int currentNormalIndex = polyLength - 1;
426    int nextNormalIndex = 0;
427
428    for (int i = 0; i < polyLength; i++) {
429        float ratioZ = projectCasterToOutline(outlineData[i].position,
430                lightCenter, poly[i]);
431        outlineData[i].radius = ratioZ * lightSize;
432
433        outlineData[currentNormalIndex].normal = ShadowTessellator::calculateNormal(
434                outlineData[currentNormalIndex].position,
435                outlineData[nextNormalIndex].position);
436        currentNormalIndex = (currentNormalIndex + 1) % polyLength;
437        nextNormalIndex++;
438    }
439
440    projectCasterToOutline(outlineCentroid, lightCenter, polyCentroid);
441
442    int penumbraIndex = 0;
443    // Then each polygon's vertex produce at minmal 2 penumbra vertices.
444    // Since the size can be dynamic here, we keep track of the size and update
445    // the real size at the end.
446    int allocatedPenumbraLength = 2 * polyLength + SPOT_MAX_EXTRA_CORNER_VERTEX_NUMBER;
447    Vector2 penumbra[allocatedPenumbraLength];
448    int totalExtraCornerSliceNumber = 0;
449
450    Vector2 umbra[polyLength];
451
452    // When centroid is covered by all circles from outline, then we consider
453    // the umbra is invalid, and we will tune down the shadow strength.
454    bool hasValidUmbra = true;
455    // We need the minimal of RaitoVI to decrease the spot shadow strength accordingly.
456    float minRaitoVI = FLT_MAX;
457
458    for (int i = 0; i < polyLength; i++) {
459        // Generate all the penumbra's vertices only using the (outline vertex + normal * radius)
460        // There is no guarantee that the penumbra is still convex, but for
461        // each outline vertex, it will connect to all its corresponding penumbra vertices as
462        // triangle fans. And for neighber penumbra vertex, it will be a trapezoid.
463        //
464        // Penumbra Vertices marked as Pi
465        // Outline Vertices marked as Vi
466        //                                            (P3)
467        //          (P2)                               |     ' (P4)
468        //   (P1)'   |                                 |   '
469        //         ' |                                 | '
470        // (P0)  ------------------------------------------------(P5)
471        //           | (V0)                            |(V1)
472        //           |                                 |
473        //           |                                 |
474        //           |                                 |
475        //           |                                 |
476        //           |                                 |
477        //           |                                 |
478        //           |                                 |
479        //           |                                 |
480        //       (V3)-----------------------------------(V2)
481        int preNormalIndex = (i + polyLength - 1) % polyLength;
482
483        const Vector2& previousNormal = outlineData[preNormalIndex].normal;
484        const Vector2& currentNormal = outlineData[i].normal;
485
486        // Depending on how roundness we want for each corner, we can subdivide
487        // further here and/or introduce some heuristic to decide how much the
488        // subdivision should be.
489        int currentExtraSliceNumber = ShadowTessellator::getExtraVertexNumber(
490                previousNormal, currentNormal, SPOT_CORNER_RADIANS_DIVISOR);
491
492        int currentCornerSliceNumber = 1 + currentExtraSliceNumber;
493        totalExtraCornerSliceNumber += currentExtraSliceNumber;
494#if DEBUG_SHADOW
495        ALOGD("currentExtraSliceNumber should be %d", currentExtraSliceNumber);
496        ALOGD("currentCornerSliceNumber should be %d", currentCornerSliceNumber);
497        ALOGD("totalCornerSliceNumber is %d", totalExtraCornerSliceNumber);
498#endif
499        if (CC_UNLIKELY(totalExtraCornerSliceNumber > SPOT_MAX_EXTRA_CORNER_VERTEX_NUMBER)) {
500            currentCornerSliceNumber = 1;
501        }
502        for (int k = 0; k <= currentCornerSliceNumber; k++) {
503            Vector2 avgNormal =
504                    (previousNormal * (currentCornerSliceNumber - k) + currentNormal * k) /
505                    currentCornerSliceNumber;
506            avgNormal.normalize();
507            penumbra[penumbraIndex++] = outlineData[i].position +
508                    avgNormal * outlineData[i].radius;
509        }
510
511
512        // Compute the umbra by the intersection from the outline's centroid!
513        //
514        //       (V) ------------------------------------
515        //           |          '                       |
516        //           |         '                        |
517        //           |       ' (I)                      |
518        //           |    '                             |
519        //           | '             (C)                |
520        //           |                                  |
521        //           |                                  |
522        //           |                                  |
523        //           |                                  |
524        //           ------------------------------------
525        //
526        // Connect a line b/t the outline vertex (V) and the centroid (C), it will
527        // intersect with the outline vertex's circle at point (I).
528        // Now, ratioVI = VI / VC, ratioIC = IC / VC
529        // Then the intersetion point can be computed as Ixy = Vxy * ratioIC + Cxy * ratioVI;
530        //
531        // When all of the outline circles cover the the outline centroid, (like I is
532        // on the other side of C), there is no real umbra any more, so we just fake
533        // a small area around the centroid as the umbra, and tune down the spot
534        // shadow's umbra strength to simulate the effect the whole shadow will
535        // become lighter in this case.
536        // The ratio can be simulated by using the inverse of maximum of ratioVI for
537        // all (V).
538        float distOutline = (outlineData[i].position - outlineCentroid).length();
539        if (CC_UNLIKELY(distOutline == 0)) {
540            // If the outline has 0 area, then there is no spot shadow anyway.
541            ALOGW("Outline has 0 area, no spot shadow!");
542            return;
543        }
544
545        float ratioVI = outlineData[i].radius / distOutline;
546        minRaitoVI = std::min(minRaitoVI, ratioVI);
547        if (ratioVI >= (1 - FAKE_UMBRA_SIZE_RATIO)) {
548            ratioVI = (1 - FAKE_UMBRA_SIZE_RATIO);
549        }
550        // When we know we don't have valid umbra, don't bother to compute the
551        // values below. But we can't skip the loop yet since we want to know the
552        // maximum ratio.
553        float ratioIC = 1 - ratioVI;
554        umbra[i] = outlineData[i].position * ratioIC + outlineCentroid * ratioVI;
555    }
556
557    hasValidUmbra = (minRaitoVI <= 1.0);
558    float shadowStrengthScale = 1.0;
559    if (!hasValidUmbra) {
560#if DEBUG_SHADOW
561        ALOGW("The object is too close to the light or too small, no real umbra!");
562#endif
563        for (int i = 0; i < polyLength; i++) {
564            umbra[i] = outlineData[i].position * FAKE_UMBRA_SIZE_RATIO +
565                    outlineCentroid * (1 - FAKE_UMBRA_SIZE_RATIO);
566        }
567        shadowStrengthScale = 1.0 / minRaitoVI;
568    }
569
570    int penumbraLength = penumbraIndex;
571    int umbraLength = polyLength;
572
573#if DEBUG_SHADOW
574    ALOGD("penumbraLength is %d , allocatedPenumbraLength %d", penumbraLength, allocatedPenumbraLength);
575    dumpPolygon(poly, polyLength, "input poly");
576    dumpPolygon(penumbra, penumbraLength, "penumbra");
577    dumpPolygon(umbra, umbraLength, "umbra");
578    ALOGD("hasValidUmbra is %d and shadowStrengthScale is %f", hasValidUmbra, shadowStrengthScale);
579#endif
580
581    // The penumbra and umbra needs to be in convex shape to keep consistency
582    // and quality.
583    // Since we are still shooting rays to penumbra, it needs to be convex.
584    // Umbra can be represented as a fan from the centroid, but visually umbra
585    // looks nicer when it is convex.
586    Vector2 finalUmbra[umbraLength];
587    Vector2 finalPenumbra[penumbraLength];
588    int finalUmbraLength = hull(umbra, umbraLength, finalUmbra);
589    int finalPenumbraLength = hull(penumbra, penumbraLength, finalPenumbra);
590
591    generateTriangleStrip(isCasterOpaque, shadowStrengthScale, finalPenumbra,
592            finalPenumbraLength, finalUmbra, finalUmbraLength, poly, polyLength,
593            shadowTriangleStrip, outlineCentroid);
594
595}
596
597/**
598 * This is only for experimental purpose.
599 * After intersections are calculated, we could smooth the polygon if needed.
600 * So far, we don't think it is more appealing yet.
601 *
602 * @param level The level of smoothness.
603 * @param rays The total number of rays.
604 * @param rayDist (In and Out) The distance for each ray.
605 *
606 */
607void SpotShadow::smoothPolygon(int level, int rays, float* rayDist) {
608    for (int k = 0; k < level; k++) {
609        for (int i = 0; i < rays; i++) {
610            float p1 = rayDist[(rays - 1 + i) % rays];
611            float p2 = rayDist[i];
612            float p3 = rayDist[(i + 1) % rays];
613            rayDist[i] = (p1 + p2 * 2 + p3) / 4;
614        }
615    }
616}
617
618// Index pair is meant for storing the tessellation information for the penumbra
619// area. One index must come from exterior tangent of the circles, the other one
620// must come from the interior tangent of the circles.
621struct IndexPair {
622    int outerIndex;
623    int innerIndex;
624};
625
626// For one penumbra vertex, find the cloest umbra vertex and return its index.
627inline int getClosestUmbraIndex(const Vector2& pivot, const Vector2* polygon, int polygonLength) {
628    float minLengthSquared = FLT_MAX;
629    int resultIndex = -1;
630    bool hasDecreased = false;
631    // Starting with some negative offset, assuming both umbra and penumbra are starting
632    // at the same angle, this can help to find the result faster.
633    // Normally, loop 3 times, we can find the closest point.
634    int offset = polygonLength - 2;
635    for (int i = 0; i < polygonLength; i++) {
636        int currentIndex = (i + offset) % polygonLength;
637        float currentLengthSquared = (pivot - polygon[currentIndex]).lengthSquared();
638        if (currentLengthSquared < minLengthSquared) {
639            if (minLengthSquared != FLT_MAX) {
640                hasDecreased = true;
641            }
642            minLengthSquared = currentLengthSquared;
643            resultIndex = currentIndex;
644        } else if (currentLengthSquared > minLengthSquared && hasDecreased) {
645            // Early break b/c we have found the closet one and now the length
646            // is increasing again.
647            break;
648        }
649    }
650    if(resultIndex == -1) {
651        ALOGE("resultIndex is -1, the polygon must be invalid!");
652        resultIndex = 0;
653    }
654    return resultIndex;
655}
656
657// Allow some epsilon here since the later ray intersection did allow for some small
658// floating point error, when the intersection point is slightly outside the segment.
659inline bool sameDirections(bool isPositiveCross, float a, float b) {
660    if (isPositiveCross) {
661        return a >= -EPSILON && b >= -EPSILON;
662    } else {
663        return a <= EPSILON && b <= EPSILON;
664    }
665}
666
667// Find the right polygon edge to shoot the ray at.
668inline int findPolyIndex(bool isPositiveCross, int startPolyIndex, const Vector2& umbraDir,
669        const Vector2* polyToCentroid, int polyLength) {
670    // Make sure we loop with a bound.
671    for (int i = 0; i < polyLength; i++) {
672        int currentIndex = (i + startPolyIndex) % polyLength;
673        const Vector2& currentToCentroid = polyToCentroid[currentIndex];
674        const Vector2& nextToCentroid = polyToCentroid[(currentIndex + 1) % polyLength];
675
676        float currentCrossUmbra = currentToCentroid.cross(umbraDir);
677        float umbraCrossNext = umbraDir.cross(nextToCentroid);
678        if (sameDirections(isPositiveCross, currentCrossUmbra, umbraCrossNext)) {
679#if DEBUG_SHADOW
680            ALOGD("findPolyIndex loop %d times , index %d", i, currentIndex );
681#endif
682            return currentIndex;
683        }
684    }
685    LOG_ALWAYS_FATAL("Can't find the right polygon's edge from startPolyIndex %d", startPolyIndex);
686    return -1;
687}
688
689// Generate the index pair for penumbra / umbra vertices, and more penumbra vertices
690// if needed.
691inline void genNewPenumbraAndPairWithUmbra(const Vector2* penumbra, int penumbraLength,
692        const Vector2* umbra, int umbraLength, Vector2* newPenumbra, int& newPenumbraIndex,
693        IndexPair* verticesPair, int& verticesPairIndex) {
694    // In order to keep everything in just one loop, we need to pre-compute the
695    // closest umbra vertex for the last penumbra vertex.
696    int previousClosestUmbraIndex = getClosestUmbraIndex(penumbra[penumbraLength - 1],
697            umbra, umbraLength);
698    for (int i = 0; i < penumbraLength; i++) {
699        const Vector2& currentPenumbraVertex = penumbra[i];
700        // For current penumbra vertex, starting from previousClosestUmbraIndex,
701        // then check the next one until the distance increase.
702        // The last one before the increase is the umbra vertex we need to pair with.
703        float currentLengthSquared =
704                (currentPenumbraVertex - umbra[previousClosestUmbraIndex]).lengthSquared();
705        int currentClosestUmbraIndex = previousClosestUmbraIndex;
706        int indexDelta = 0;
707        for (int j = 1; j < umbraLength; j++) {
708            int newUmbraIndex = (previousClosestUmbraIndex + j) % umbraLength;
709            float newLengthSquared = (currentPenumbraVertex - umbra[newUmbraIndex]).lengthSquared();
710            if (newLengthSquared > currentLengthSquared) {
711                // currentClosestUmbraIndex is the umbra vertex's index which has
712                // currently found smallest distance, so we can simply break here.
713                break;
714            } else {
715                currentLengthSquared = newLengthSquared;
716                indexDelta++;
717                currentClosestUmbraIndex = newUmbraIndex;
718            }
719        }
720
721        if (indexDelta > 1) {
722            // For those umbra don't have  penumbra, generate new penumbra vertices by interpolation.
723            //
724            // Assuming Pi for penumbra vertices, and Ui for umbra vertices.
725            // In the case like below P1 paired with U1 and P2 paired with  U5.
726            // U2 to U4 are unpaired umbra vertices.
727            //
728            // P1                                        P2
729            // |                                          |
730            // U1     U2                   U3     U4     U5
731            //
732            // We will need to generate 3 more penumbra vertices P1.1, P1.2, P1.3
733            // to pair with U2 to U4.
734            //
735            // P1     P1.1                P1.2   P1.3    P2
736            // |       |                   |      |      |
737            // U1     U2                   U3     U4     U5
738            //
739            // That distance ratio b/t Ui to U1 and Ui to U5 decides its paired penumbra
740            // vertex's location.
741            int newPenumbraNumber = indexDelta - 1;
742
743            float accumulatedDeltaLength[indexDelta];
744            float totalDeltaLength = 0;
745
746            // To save time, cache the previous umbra vertex info outside the loop
747            // and update each loop.
748            Vector2 previousClosestUmbra = umbra[previousClosestUmbraIndex];
749            Vector2 skippedUmbra;
750            // Use umbra data to precompute the length b/t unpaired umbra vertices,
751            // and its ratio against the total length.
752            for (int k = 0; k < indexDelta; k++) {
753                int skippedUmbraIndex = (previousClosestUmbraIndex + k + 1) % umbraLength;
754                skippedUmbra = umbra[skippedUmbraIndex];
755                float currentDeltaLength = (skippedUmbra - previousClosestUmbra).length();
756
757                totalDeltaLength += currentDeltaLength;
758                accumulatedDeltaLength[k] = totalDeltaLength;
759
760                previousClosestUmbra = skippedUmbra;
761            }
762
763            const Vector2& previousPenumbra = penumbra[(i + penumbraLength - 1) % penumbraLength];
764            // Then for each unpaired umbra vertex, create a new penumbra by the ratio,
765            // and pair them togehter.
766            for (int k = 0; k < newPenumbraNumber; k++) {
767                float weightForCurrentPenumbra = 1.0f;
768                if (totalDeltaLength != 0.0f) {
769                    weightForCurrentPenumbra = accumulatedDeltaLength[k] / totalDeltaLength;
770                }
771                float weightForPreviousPenumbra = 1.0f - weightForCurrentPenumbra;
772
773                Vector2 interpolatedPenumbra = currentPenumbraVertex * weightForCurrentPenumbra +
774                    previousPenumbra * weightForPreviousPenumbra;
775
776                int skippedUmbraIndex = (previousClosestUmbraIndex + k + 1) % umbraLength;
777                verticesPair[verticesPairIndex].outerIndex = newPenumbraIndex;
778                verticesPair[verticesPairIndex].innerIndex = skippedUmbraIndex;
779                verticesPairIndex++;
780                newPenumbra[newPenumbraIndex++] = interpolatedPenumbra;
781            }
782        }
783        verticesPair[verticesPairIndex].outerIndex = newPenumbraIndex;
784        verticesPair[verticesPairIndex].innerIndex = currentClosestUmbraIndex;
785        verticesPairIndex++;
786        newPenumbra[newPenumbraIndex++] = currentPenumbraVertex;
787
788        previousClosestUmbraIndex = currentClosestUmbraIndex;
789    }
790}
791
792// Precompute all the polygon's vector, return true if the reference cross product is positive.
793inline bool genPolyToCentroid(const Vector2* poly2d, int polyLength,
794        const Vector2& centroid, Vector2* polyToCentroid) {
795    for (int j = 0; j < polyLength; j++) {
796        polyToCentroid[j] = poly2d[j] - centroid;
797        // Normalize these vectors such that we can use epsilon comparison after
798        // computing their cross products with another normalized vector.
799        polyToCentroid[j].normalize();
800    }
801    float refCrossProduct = 0;
802    for (int j = 0; j < polyLength; j++) {
803        refCrossProduct = polyToCentroid[j].cross(polyToCentroid[(j + 1) % polyLength]);
804        if (refCrossProduct != 0) {
805            break;
806        }
807    }
808
809    return refCrossProduct > 0;
810}
811
812// For one umbra vertex, shoot an ray from centroid to it.
813// If the ray hit the polygon first, then return the intersection point as the
814// closer vertex.
815inline Vector2 getCloserVertex(const Vector2& umbraVertex, const Vector2& centroid,
816        const Vector2* poly2d, int polyLength, const Vector2* polyToCentroid,
817        bool isPositiveCross, int& previousPolyIndex) {
818    Vector2 umbraToCentroid = umbraVertex - centroid;
819    float distanceToUmbra = umbraToCentroid.length();
820    umbraToCentroid = umbraToCentroid / distanceToUmbra;
821
822    // previousPolyIndex is updated for each item such that we can minimize the
823    // looping inside findPolyIndex();
824    previousPolyIndex = findPolyIndex(isPositiveCross, previousPolyIndex,
825            umbraToCentroid, polyToCentroid, polyLength);
826
827    float dx = umbraToCentroid.x;
828    float dy = umbraToCentroid.y;
829    float distanceToIntersectPoly = rayIntersectPoints(centroid, dx, dy,
830            poly2d[previousPolyIndex], poly2d[(previousPolyIndex + 1) % polyLength]);
831    if (distanceToIntersectPoly < 0) {
832        distanceToIntersectPoly = 0;
833    }
834
835    // Pick the closer one as the occluded area vertex.
836    Vector2 closerVertex;
837    if (distanceToIntersectPoly < distanceToUmbra) {
838        closerVertex.x = centroid.x + dx * distanceToIntersectPoly;
839        closerVertex.y = centroid.y + dy * distanceToIntersectPoly;
840    } else {
841        closerVertex = umbraVertex;
842    }
843
844    return closerVertex;
845}
846
847/**
848 * Generate a triangle strip given two convex polygon
849**/
850void SpotShadow::generateTriangleStrip(bool isCasterOpaque, float shadowStrengthScale,
851        Vector2* penumbra, int penumbraLength, Vector2* umbra, int umbraLength,
852        const Vector3* poly, int polyLength, VertexBuffer& shadowTriangleStrip,
853        const Vector2& centroid) {
854    bool hasOccludedUmbraArea = false;
855    Vector2 poly2d[polyLength];
856
857    if (isCasterOpaque) {
858        for (int i = 0; i < polyLength; i++) {
859            poly2d[i].x = poly[i].x;
860            poly2d[i].y = poly[i].y;
861        }
862        // Make sure the centroid is inside the umbra, otherwise, fall back to the
863        // approach as if there is no occluded umbra area.
864        if (testPointInsidePolygon(centroid, poly2d, polyLength)) {
865            hasOccludedUmbraArea = true;
866        }
867    }
868
869    // For each penumbra vertex, find its corresponding closest umbra vertex index.
870    //
871    // Penumbra Vertices marked as Pi
872    // Umbra Vertices marked as Ui
873    //                                            (P3)
874    //          (P2)                               |     ' (P4)
875    //   (P1)'   |                                 |   '
876    //         ' |                                 | '
877    // (P0)  ------------------------------------------------(P5)
878    //           | (U0)                            |(U1)
879    //           |                                 |
880    //           |                                 |(U2)     (P5.1)
881    //           |                                 |
882    //           |                                 |
883    //           |                                 |
884    //           |                                 |
885    //           |                                 |
886    //           |                                 |
887    //       (U4)-----------------------------------(U3)      (P6)
888    //
889    // At least, like P0, P1, P2, they will find the matching umbra as U0.
890    // If we jump over some umbra vertex without matching penumbra vertex, then
891    // we will generate some new penumbra vertex by interpolation. Like P6 is
892    // matching U3, but U2 is not matched with any penumbra vertex.
893    // So interpolate P5.1 out and match U2.
894    // In this way, every umbra vertex will have a matching penumbra vertex.
895    //
896    // The total pair number can be as high as umbraLength + penumbraLength.
897    const int maxNewPenumbraLength = umbraLength + penumbraLength;
898    IndexPair verticesPair[maxNewPenumbraLength];
899    int verticesPairIndex = 0;
900
901    // Cache all the existing penumbra vertices and newly interpolated vertices into a
902    // a new array.
903    Vector2 newPenumbra[maxNewPenumbraLength];
904    int newPenumbraIndex = 0;
905
906    // For each penumbra vertex, find its closet umbra vertex by comparing the
907    // neighbor umbra vertices.
908    genNewPenumbraAndPairWithUmbra(penumbra, penumbraLength, umbra, umbraLength, newPenumbra,
909            newPenumbraIndex, verticesPair, verticesPairIndex);
910    ShadowTessellator::checkOverflow(verticesPairIndex, maxNewPenumbraLength, "Spot pair");
911    ShadowTessellator::checkOverflow(newPenumbraIndex, maxNewPenumbraLength, "Spot new penumbra");
912#if DEBUG_SHADOW
913    for (int i = 0; i < umbraLength; i++) {
914        ALOGD("umbra i %d,  [%f, %f]", i, umbra[i].x, umbra[i].y);
915    }
916    for (int i = 0; i < newPenumbraIndex; i++) {
917        ALOGD("new penumbra i %d,  [%f, %f]", i, newPenumbra[i].x, newPenumbra[i].y);
918    }
919    for (int i = 0; i < verticesPairIndex; i++) {
920        ALOGD("index i %d,  [%d, %d]", i, verticesPair[i].outerIndex, verticesPair[i].innerIndex);
921    }
922#endif
923
924    // For the size of vertex buffer, we need 3 rings, one has newPenumbraSize,
925    // one has umbraLength, the last one has at most umbraLength.
926    //
927    // For the size of index buffer, the umbra area needs (2 * umbraLength + 2).
928    // The penumbra one can vary a bit, but it is bounded by (2 * verticesPairIndex + 2).
929    // And 2 more for jumping between penumbra to umbra.
930    const int newPenumbraLength = newPenumbraIndex;
931    const int totalVertexCount = newPenumbraLength + umbraLength * 2;
932    const int totalIndexCount = 2 * umbraLength + 2 * verticesPairIndex + 6;
933    AlphaVertex* shadowVertices =
934            shadowTriangleStrip.alloc<AlphaVertex>(totalVertexCount);
935    uint16_t* indexBuffer =
936            shadowTriangleStrip.allocIndices<uint16_t>(totalIndexCount);
937    int vertexBufferIndex = 0;
938    int indexBufferIndex = 0;
939
940    // Fill the IB and VB for the penumbra area.
941    for (int i = 0; i < newPenumbraLength; i++) {
942        AlphaVertex::set(&shadowVertices[vertexBufferIndex++], newPenumbra[i].x,
943                newPenumbra[i].y, PENUMBRA_ALPHA);
944    }
945    for (int i = 0; i < umbraLength; i++) {
946        AlphaVertex::set(&shadowVertices[vertexBufferIndex++], umbra[i].x, umbra[i].y,
947                UMBRA_ALPHA);
948    }
949
950    for (int i = 0; i < verticesPairIndex; i++) {
951        indexBuffer[indexBufferIndex++] = verticesPair[i].outerIndex;
952        // All umbra index need to be offseted by newPenumbraSize.
953        indexBuffer[indexBufferIndex++] = verticesPair[i].innerIndex + newPenumbraLength;
954    }
955    indexBuffer[indexBufferIndex++] = verticesPair[0].outerIndex;
956    indexBuffer[indexBufferIndex++] = verticesPair[0].innerIndex + newPenumbraLength;
957
958    // Now fill the IB and VB for the umbra area.
959    // First duplicated the index from previous strip and the first one for the
960    // degenerated triangles.
961    indexBuffer[indexBufferIndex] = indexBuffer[indexBufferIndex - 1];
962    indexBufferIndex++;
963    indexBuffer[indexBufferIndex++] = newPenumbraLength + 0;
964    // Save the first VB index for umbra area in order to close the loop.
965    int savedStartIndex = vertexBufferIndex;
966
967    if (hasOccludedUmbraArea) {
968        // Precompute all the polygon's vector, and the reference cross product,
969        // in order to find the right polygon edge for the ray to intersect.
970        Vector2 polyToCentroid[polyLength];
971        bool isPositiveCross = genPolyToCentroid(poly2d, polyLength, centroid, polyToCentroid);
972
973        // Because both the umbra and polygon are going in the same direction,
974        // we can save the previous polygon index to make sure we have less polygon
975        // vertex to compute for each ray.
976        int previousPolyIndex = 0;
977        for (int i = 0; i < umbraLength; i++) {
978            // Shoot a ray from centroid to each umbra vertices and pick the one with
979            // shorter distance to the centroid, b/t the umbra vertex or the intersection point.
980            Vector2 closerVertex = getCloserVertex(umbra[i], centroid, poly2d, polyLength,
981                    polyToCentroid, isPositiveCross, previousPolyIndex);
982
983            // We already stored the umbra vertices, just need to add the occlued umbra's ones.
984            indexBuffer[indexBufferIndex++] = newPenumbraLength + i;
985            indexBuffer[indexBufferIndex++] = vertexBufferIndex;
986            AlphaVertex::set(&shadowVertices[vertexBufferIndex++],
987                    closerVertex.x, closerVertex.y, UMBRA_ALPHA);
988        }
989    } else {
990        // If there is no occluded umbra at all, then draw the triangle fan
991        // starting from the centroid to all umbra vertices.
992        int lastCentroidIndex = vertexBufferIndex;
993        AlphaVertex::set(&shadowVertices[vertexBufferIndex++], centroid.x,
994                centroid.y, UMBRA_ALPHA);
995        for (int i = 0; i < umbraLength; i++) {
996            indexBuffer[indexBufferIndex++] = newPenumbraLength + i;
997            indexBuffer[indexBufferIndex++] = lastCentroidIndex;
998        }
999    }
1000    // Closing the umbra area triangle's loop here.
1001    indexBuffer[indexBufferIndex++] = newPenumbraLength;
1002    indexBuffer[indexBufferIndex++] = savedStartIndex;
1003
1004    // At the end, update the real index and vertex buffer size.
1005    shadowTriangleStrip.updateVertexCount(vertexBufferIndex);
1006    shadowTriangleStrip.updateIndexCount(indexBufferIndex);
1007    ShadowTessellator::checkOverflow(vertexBufferIndex, totalVertexCount, "Spot Vertex Buffer");
1008    ShadowTessellator::checkOverflow(indexBufferIndex, totalIndexCount, "Spot Index Buffer");
1009
1010    shadowTriangleStrip.setMeshFeatureFlags(VertexBuffer::kAlpha | VertexBuffer::kIndices);
1011    shadowTriangleStrip.computeBounds<AlphaVertex>();
1012}
1013
1014#if DEBUG_SHADOW
1015
1016#define TEST_POINT_NUMBER 128
1017/**
1018 * Calculate the bounds for generating random test points.
1019 */
1020void SpotShadow::updateBound(const Vector2 inVector, Vector2& lowerBound,
1021        Vector2& upperBound) {
1022    if (inVector.x < lowerBound.x) {
1023        lowerBound.x = inVector.x;
1024    }
1025
1026    if (inVector.y < lowerBound.y) {
1027        lowerBound.y = inVector.y;
1028    }
1029
1030    if (inVector.x > upperBound.x) {
1031        upperBound.x = inVector.x;
1032    }
1033
1034    if (inVector.y > upperBound.y) {
1035        upperBound.y = inVector.y;
1036    }
1037}
1038
1039/**
1040 * For debug purpose, when things go wrong, dump the whole polygon data.
1041 */
1042void SpotShadow::dumpPolygon(const Vector2* poly, int polyLength, const char* polyName) {
1043    for (int i = 0; i < polyLength; i++) {
1044        ALOGD("polygon %s i %d x %f y %f", polyName, i, poly[i].x, poly[i].y);
1045    }
1046}
1047
1048/**
1049 * For debug purpose, when things go wrong, dump the whole polygon data.
1050 */
1051void SpotShadow::dumpPolygon(const Vector3* poly, int polyLength, const char* polyName) {
1052    for (int i = 0; i < polyLength; i++) {
1053        ALOGD("polygon %s i %d x %f y %f z %f", polyName, i, poly[i].x, poly[i].y, poly[i].z);
1054    }
1055}
1056
1057/**
1058 * Test whether the polygon is convex.
1059 */
1060bool SpotShadow::testConvex(const Vector2* polygon, int polygonLength,
1061        const char* name) {
1062    bool isConvex = true;
1063    for (int i = 0; i < polygonLength; i++) {
1064        Vector2 start = polygon[i];
1065        Vector2 middle = polygon[(i + 1) % polygonLength];
1066        Vector2 end = polygon[(i + 2) % polygonLength];
1067
1068        float delta = (float(middle.x) - start.x) * (float(end.y) - start.y) -
1069                (float(middle.y) - start.y) * (float(end.x) - start.x);
1070        bool isCCWOrCoLinear = (delta >= EPSILON);
1071
1072        if (isCCWOrCoLinear) {
1073            ALOGW("(Error Type 2): polygon (%s) is not a convex b/c start (x %f, y %f),"
1074                    "middle (x %f, y %f) and end (x %f, y %f) , delta is %f !!!",
1075                    name, start.x, start.y, middle.x, middle.y, end.x, end.y, delta);
1076            isConvex = false;
1077            break;
1078        }
1079    }
1080    return isConvex;
1081}
1082
1083/**
1084 * Test whether or not the polygon (intersection) is within the 2 input polygons.
1085 * Using Marte Carlo method, we generate a random point, and if it is inside the
1086 * intersection, then it must be inside both source polygons.
1087 */
1088void SpotShadow::testIntersection(const Vector2* poly1, int poly1Length,
1089        const Vector2* poly2, int poly2Length,
1090        const Vector2* intersection, int intersectionLength) {
1091    // Find the min and max of x and y.
1092    Vector2 lowerBound = {FLT_MAX, FLT_MAX};
1093    Vector2 upperBound = {-FLT_MAX, -FLT_MAX};
1094    for (int i = 0; i < poly1Length; i++) {
1095        updateBound(poly1[i], lowerBound, upperBound);
1096    }
1097    for (int i = 0; i < poly2Length; i++) {
1098        updateBound(poly2[i], lowerBound, upperBound);
1099    }
1100
1101    bool dumpPoly = false;
1102    for (int k = 0; k < TEST_POINT_NUMBER; k++) {
1103        // Generate a random point between minX, minY and maxX, maxY.
1104        float randomX = rand() / float(RAND_MAX);
1105        float randomY = rand() / float(RAND_MAX);
1106
1107        Vector2 testPoint;
1108        testPoint.x = lowerBound.x + randomX * (upperBound.x - lowerBound.x);
1109        testPoint.y = lowerBound.y + randomY * (upperBound.y - lowerBound.y);
1110
1111        // If the random point is in both poly 1 and 2, then it must be intersection.
1112        if (testPointInsidePolygon(testPoint, intersection, intersectionLength)) {
1113            if (!testPointInsidePolygon(testPoint, poly1, poly1Length)) {
1114                dumpPoly = true;
1115                ALOGW("(Error Type 1): one point (%f, %f) in the intersection is"
1116                        " not in the poly1",
1117                        testPoint.x, testPoint.y);
1118            }
1119
1120            if (!testPointInsidePolygon(testPoint, poly2, poly2Length)) {
1121                dumpPoly = true;
1122                ALOGW("(Error Type 1): one point (%f, %f) in the intersection is"
1123                        " not in the poly2",
1124                        testPoint.x, testPoint.y);
1125            }
1126        }
1127    }
1128
1129    if (dumpPoly) {
1130        dumpPolygon(intersection, intersectionLength, "intersection");
1131        for (int i = 1; i < intersectionLength; i++) {
1132            Vector2 delta = intersection[i] - intersection[i - 1];
1133            ALOGD("Intersetion i, %d Vs i-1 is delta %f", i, delta.lengthSquared());
1134        }
1135
1136        dumpPolygon(poly1, poly1Length, "poly 1");
1137        dumpPolygon(poly2, poly2Length, "poly 2");
1138    }
1139}
1140#endif
1141
1142}; // namespace uirenderer
1143}; // namespace android
1144