SpotShadow.cpp revision 726118b35240957710d4d85fb5747e2ba8b934f7
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#define LOG_TAG "OpenGLRenderer"
18
19#define SHADOW_SHRINK_SCALE 0.1f
20
21#include <math.h>
22#include <stdlib.h>
23#include <utils/Log.h>
24
25#include "ShadowTessellator.h"
26#include "SpotShadow.h"
27#include "Vertex.h"
28
29namespace android {
30namespace uirenderer {
31
32static const double EPSILON = 1e-7;
33
34/**
35 * Calculate the angle between and x and a y coordinate.
36 * The atan2 range from -PI to PI.
37 */
38float angle(const Vector2& point, const Vector2& center) {
39    return atan2(point.y - center.y, point.x - center.x);
40}
41
42/**
43 * Calculate the intersection of a ray with the line segment defined by two points.
44 *
45 * Returns a negative value in error conditions.
46
47 * @param rayOrigin The start of the ray
48 * @param dx The x vector of the ray
49 * @param dy The y vector of the ray
50 * @param p1 The first point defining the line segment
51 * @param p2 The second point defining the line segment
52 * @return The distance along the ray if it intersects with the line segment, negative if otherwise
53 */
54float rayIntersectPoints(const Vector2& rayOrigin, float dx, float dy,
55        const Vector2& p1, const Vector2& p2) {
56    // The math below is derived from solving this formula, basically the
57    // intersection point should stay on both the ray and the edge of (p1, p2).
58    // solve([p1x+t*(p2x-p1x)=dx*t2+px,p1y+t*(p2y-p1y)=dy*t2+py],[t,t2]);
59
60    double divisor = (dx * (p1.y - p2.y) + dy * p2.x - dy * p1.x);
61    if (divisor == 0) return -1.0f; // error, invalid divisor
62
63#if DEBUG_SHADOW
64    double interpVal = (dx * (p1.y - rayOrigin.y) + dy * rayOrigin.x - dy * p1.x) / divisor;
65    if (interpVal < 0 || interpVal > 1) return -1.0f; // error, doesn't intersect between points
66#endif
67
68    double distance = (p1.x * (rayOrigin.y - p2.y) + p2.x * (p1.y - rayOrigin.y) +
69            rayOrigin.x * (p2.y - p1.y)) / divisor;
70
71    return distance; // may be negative in error cases
72}
73
74/**
75 * Sort points by their X coordinates
76 *
77 * @param points the points as a Vector2 array.
78 * @param pointsLength the number of vertices of the polygon.
79 */
80void SpotShadow::xsort(Vector2* points, int pointsLength) {
81    quicksortX(points, 0, pointsLength - 1);
82}
83
84/**
85 * compute the convex hull of a collection of Points
86 *
87 * @param points the points as a Vector2 array.
88 * @param pointsLength the number of vertices of the polygon.
89 * @param retPoly pre allocated array of floats to put the vertices
90 * @return the number of points in the polygon 0 if no intersection
91 */
92int SpotShadow::hull(Vector2* points, int pointsLength, Vector2* retPoly) {
93    xsort(points, pointsLength);
94    int n = pointsLength;
95    Vector2 lUpper[n];
96    lUpper[0] = points[0];
97    lUpper[1] = points[1];
98
99    int lUpperSize = 2;
100
101    for (int i = 2; i < n; i++) {
102        lUpper[lUpperSize] = points[i];
103        lUpperSize++;
104
105        while (lUpperSize > 2 && !ccw(
106                lUpper[lUpperSize - 3].x, lUpper[lUpperSize - 3].y,
107                lUpper[lUpperSize - 2].x, lUpper[lUpperSize - 2].y,
108                lUpper[lUpperSize - 1].x, lUpper[lUpperSize - 1].y)) {
109            // Remove the middle point of the three last
110            lUpper[lUpperSize - 2].x = lUpper[lUpperSize - 1].x;
111            lUpper[lUpperSize - 2].y = lUpper[lUpperSize - 1].y;
112            lUpperSize--;
113        }
114    }
115
116    Vector2 lLower[n];
117    lLower[0] = points[n - 1];
118    lLower[1] = points[n - 2];
119
120    int lLowerSize = 2;
121
122    for (int i = n - 3; i >= 0; i--) {
123        lLower[lLowerSize] = points[i];
124        lLowerSize++;
125
126        while (lLowerSize > 2 && !ccw(
127                lLower[lLowerSize - 3].x, lLower[lLowerSize - 3].y,
128                lLower[lLowerSize - 2].x, lLower[lLowerSize - 2].y,
129                lLower[lLowerSize - 1].x, lLower[lLowerSize - 1].y)) {
130            // Remove the middle point of the three last
131            lLower[lLowerSize - 2] = lLower[lLowerSize - 1];
132            lLowerSize--;
133        }
134    }
135
136    // output points in CW ordering
137    const int total = lUpperSize + lLowerSize - 2;
138    int outIndex = total - 1;
139    for (int i = 0; i < lUpperSize; i++) {
140        retPoly[outIndex] = lUpper[i];
141        outIndex--;
142    }
143
144    for (int i = 1; i < lLowerSize - 1; i++) {
145        retPoly[outIndex] = lLower[i];
146        outIndex--;
147    }
148    // TODO: Add test harness which verify that all the points are inside the hull.
149    return total;
150}
151
152/**
153 * Test whether the 3 points form a counter clockwise turn.
154 *
155 * @return true if a right hand turn
156 */
157bool SpotShadow::ccw(double ax, double ay, double bx, double by,
158        double cx, double cy) {
159    return (bx - ax) * (cy - ay) - (by - ay) * (cx - ax) > EPSILON;
160}
161
162/**
163 * Calculates the intersection of poly1 with poly2 and put in poly2.
164 *
165 *
166 * @param poly1 The 1st polygon, as a Vector2 array.
167 * @param poly1Length The number of vertices of 1st polygon.
168 * @param poly2 The 2nd and output polygon, as a Vector2 array.
169 * @param poly2Length The number of vertices of 2nd polygon.
170 * @return number of vertices in output polygon as poly2.
171 */
172int SpotShadow::intersection(Vector2* poly1, int poly1Length,
173        Vector2* poly2, int poly2Length) {
174    makeClockwise(poly1, poly1Length);
175    makeClockwise(poly2, poly2Length);
176
177    Vector2 poly[poly1Length * poly2Length + 2];
178    int count = 0;
179    int pcount = 0;
180
181    // If one vertex from one polygon sits inside another polygon, add it and
182    // count them.
183    for (int i = 0; i < poly1Length; i++) {
184        if (testPointInsidePolygon(poly1[i], poly2, poly2Length)) {
185            poly[count] = poly1[i];
186            count++;
187            pcount++;
188
189        }
190    }
191
192    int insidePoly2 = pcount;
193    for (int i = 0; i < poly2Length; i++) {
194        if (testPointInsidePolygon(poly2[i], poly1, poly1Length)) {
195            poly[count] = poly2[i];
196            count++;
197        }
198    }
199
200    int insidePoly1 = count - insidePoly2;
201    // If all vertices from poly1 are inside poly2, then just return poly1.
202    if (insidePoly2 == poly1Length) {
203        memcpy(poly2, poly1, poly1Length * sizeof(Vector2));
204        return poly1Length;
205    }
206
207    // If all vertices from poly2 are inside poly1, then just return poly2.
208    if (insidePoly1 == poly2Length) {
209        return poly2Length;
210    }
211
212    // Since neither polygon fully contain the other one, we need to add all the
213    // intersection points.
214    Vector2 intersection;
215    for (int i = 0; i < poly2Length; i++) {
216        for (int j = 0; j < poly1Length; j++) {
217            int poly2LineStart = i;
218            int poly2LineEnd = ((i + 1) % poly2Length);
219            int poly1LineStart = j;
220            int poly1LineEnd = ((j + 1) % poly1Length);
221            bool found = lineIntersection(
222                    poly2[poly2LineStart].x, poly2[poly2LineStart].y,
223                    poly2[poly2LineEnd].x, poly2[poly2LineEnd].y,
224                    poly1[poly1LineStart].x, poly1[poly1LineStart].y,
225                    poly1[poly1LineEnd].x, poly1[poly1LineEnd].y,
226                    intersection);
227            if (found) {
228                poly[count].x = intersection.x;
229                poly[count].y = intersection.y;
230                count++;
231            } else {
232                Vector2 delta = poly2[i] - poly1[j];
233                if (delta.lengthSquared() < EPSILON) {
234                    poly[count] = poly2[i];
235                    count++;
236                }
237            }
238        }
239    }
240
241    if (count == 0) {
242        return 0;
243    }
244
245    // Sort the result polygon around the center.
246    Vector2 center(0.0f, 0.0f);
247    for (int i = 0; i < count; i++) {
248        center += poly[i];
249    }
250    center /= count;
251    sort(poly, count, center);
252
253#if DEBUG_SHADOW
254    // Since poly2 is overwritten as the result, we need to save a copy to do
255    // our verification.
256    Vector2 oldPoly2[poly2Length];
257    int oldPoly2Length = poly2Length;
258    memcpy(oldPoly2, poly2, sizeof(Vector2) * poly2Length);
259#endif
260
261    // Filter the result out from poly and put it into poly2.
262    poly2[0] = poly[0];
263    int lastOutputIndex = 0;
264    for (int i = 1; i < count; i++) {
265        Vector2 delta = poly[i] - poly2[lastOutputIndex];
266        if (delta.lengthSquared() >= EPSILON) {
267            poly2[++lastOutputIndex] = poly[i];
268        } else {
269            // If the vertices are too close, pick the inner one, because the
270            // inner one is more likely to be an intersection point.
271            Vector2 delta1 = poly[i] - center;
272            Vector2 delta2 = poly2[lastOutputIndex] - center;
273            if (delta1.lengthSquared() < delta2.lengthSquared()) {
274                poly2[lastOutputIndex] = poly[i];
275            }
276        }
277    }
278    int resultLength = lastOutputIndex + 1;
279
280#if DEBUG_SHADOW
281    testConvex(poly2, resultLength, "intersection");
282    testConvex(poly1, poly1Length, "input poly1");
283    testConvex(oldPoly2, oldPoly2Length, "input poly2");
284
285    testIntersection(poly1, poly1Length, oldPoly2, oldPoly2Length, poly2, resultLength);
286#endif
287
288    return resultLength;
289}
290
291/**
292 * Sort points about a center point
293 *
294 * @param poly The in and out polyogon as a Vector2 array.
295 * @param polyLength The number of vertices of the polygon.
296 * @param center the center ctr[0] = x , ctr[1] = y to sort around.
297 */
298void SpotShadow::sort(Vector2* poly, int polyLength, const Vector2& center) {
299    quicksortCirc(poly, 0, polyLength - 1, center);
300}
301
302/**
303 * Swap points pointed to by i and j
304 */
305void SpotShadow::swap(Vector2* points, int i, int j) {
306    Vector2 temp = points[i];
307    points[i] = points[j];
308    points[j] = temp;
309}
310
311/**
312 * quick sort implementation about the center.
313 */
314void SpotShadow::quicksortCirc(Vector2* points, int low, int high,
315        const Vector2& center) {
316    int i = low, j = high;
317    int p = low + (high - low) / 2;
318    float pivot = angle(points[p], center);
319    while (i <= j) {
320        while (angle(points[i], center) > pivot) {
321            i++;
322        }
323        while (angle(points[j], center) < pivot) {
324            j--;
325        }
326
327        if (i <= j) {
328            swap(points, i, j);
329            i++;
330            j--;
331        }
332    }
333    if (low < j) quicksortCirc(points, low, j, center);
334    if (i < high) quicksortCirc(points, i, high, center);
335}
336
337/**
338 * Sort points by x axis
339 *
340 * @param points points to sort
341 * @param low start index
342 * @param high end index
343 */
344void SpotShadow::quicksortX(Vector2* points, int low, int high) {
345    int i = low, j = high;
346    int p = low + (high - low) / 2;
347    float pivot = points[p].x;
348    while (i <= j) {
349        while (points[i].x < pivot) {
350            i++;
351        }
352        while (points[j].x > pivot) {
353            j--;
354        }
355
356        if (i <= j) {
357            swap(points, i, j);
358            i++;
359            j--;
360        }
361    }
362    if (low < j) quicksortX(points, low, j);
363    if (i < high) quicksortX(points, i, high);
364}
365
366/**
367 * Test whether a point is inside the polygon.
368 *
369 * @param testPoint the point to test
370 * @param poly the polygon
371 * @return true if the testPoint is inside the poly.
372 */
373bool SpotShadow::testPointInsidePolygon(const Vector2 testPoint,
374        const Vector2* poly, int len) {
375    bool c = false;
376    double testx = testPoint.x;
377    double testy = testPoint.y;
378    for (int i = 0, j = len - 1; i < len; j = i++) {
379        double startX = poly[j].x;
380        double startY = poly[j].y;
381        double endX = poly[i].x;
382        double endY = poly[i].y;
383
384        if (((endY > testy) != (startY > testy)) &&
385            (testx < (startX - endX) * (testy - endY)
386             / (startY - endY) + endX)) {
387            c = !c;
388        }
389    }
390    return c;
391}
392
393/**
394 * Make the polygon turn clockwise.
395 *
396 * @param polygon the polygon as a Vector2 array.
397 * @param len the number of points of the polygon
398 */
399void SpotShadow::makeClockwise(Vector2* polygon, int len) {
400    if (polygon == 0  || len == 0) {
401        return;
402    }
403    if (!isClockwise(polygon, len)) {
404        reverse(polygon, len);
405    }
406}
407
408/**
409 * Test whether the polygon is order in clockwise.
410 *
411 * @param polygon the polygon as a Vector2 array
412 * @param len the number of points of the polygon
413 */
414bool SpotShadow::isClockwise(Vector2* polygon, int len) {
415    double sum = 0;
416    double p1x = polygon[len - 1].x;
417    double p1y = polygon[len - 1].y;
418    for (int i = 0; i < len; i++) {
419
420        double p2x = polygon[i].x;
421        double p2y = polygon[i].y;
422        sum += p1x * p2y - p2x * p1y;
423        p1x = p2x;
424        p1y = p2y;
425    }
426    return sum < 0;
427}
428
429/**
430 * Reverse the polygon
431 *
432 * @param polygon the polygon as a Vector2 array
433 * @param len the number of points of the polygon
434 */
435void SpotShadow::reverse(Vector2* polygon, int len) {
436    int n = len / 2;
437    for (int i = 0; i < n; i++) {
438        Vector2 tmp = polygon[i];
439        int k = len - 1 - i;
440        polygon[i] = polygon[k];
441        polygon[k] = tmp;
442    }
443}
444
445/**
446 * Intersects two lines in parametric form. This function is called in a tight
447 * loop, and we need double precision to get things right.
448 *
449 * @param x1 the x coordinate point 1 of line 1
450 * @param y1 the y coordinate point 1 of line 1
451 * @param x2 the x coordinate point 2 of line 1
452 * @param y2 the y coordinate point 2 of line 1
453 * @param x3 the x coordinate point 1 of line 2
454 * @param y3 the y coordinate point 1 of line 2
455 * @param x4 the x coordinate point 2 of line 2
456 * @param y4 the y coordinate point 2 of line 2
457 * @param ret the x,y location of the intersection
458 * @return true if it found an intersection
459 */
460inline bool SpotShadow::lineIntersection(double x1, double y1, double x2, double y2,
461        double x3, double y3, double x4, double y4, Vector2& ret) {
462    double d = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4);
463    if (d == 0.0) return false;
464
465    double dx = (x1 * y2 - y1 * x2);
466    double dy = (x3 * y4 - y3 * x4);
467    double x = (dx * (x3 - x4) - (x1 - x2) * dy) / d;
468    double y = (dx * (y3 - y4) - (y1 - y2) * dy) / d;
469
470    // The intersection should be in the middle of the point 1 and point 2,
471    // likewise point 3 and point 4.
472    if (((x - x1) * (x - x2) > EPSILON)
473        || ((x - x3) * (x - x4) > EPSILON)
474        || ((y - y1) * (y - y2) > EPSILON)
475        || ((y - y3) * (y - y4) > EPSILON)) {
476        // Not interesected
477        return false;
478    }
479    ret.x = x;
480    ret.y = y;
481    return true;
482
483}
484
485/**
486 * Compute a horizontal circular polygon about point (x , y , height) of radius
487 * (size)
488 *
489 * @param points number of the points of the output polygon.
490 * @param lightCenter the center of the light.
491 * @param size the light size.
492 * @param ret result polygon.
493 */
494void SpotShadow::computeLightPolygon(int points, const Vector3& lightCenter,
495        float size, Vector3* ret) {
496    // TODO: Caching all the sin / cos values and store them in a look up table.
497    for (int i = 0; i < points; i++) {
498        double angle = 2 * i * M_PI / points;
499        ret[i].x = cosf(angle) * size + lightCenter.x;
500        ret[i].y = sinf(angle) * size + lightCenter.y;
501        ret[i].z = lightCenter.z;
502    }
503}
504
505/**
506* Generate the shadow from a spot light.
507*
508* @param poly x,y,z vertexes of a convex polygon that occludes the light source
509* @param polyLength number of vertexes of the occluding polygon
510* @param lightCenter the center of the light
511* @param lightSize the radius of the light source
512* @param lightVertexCount the vertex counter for the light polygon
513* @param shadowTriangleStrip return an (x,y,alpha) triangle strip representing the shadow. Return
514*                            empty strip if error.
515*
516*/
517void SpotShadow::createSpotShadow(const Vector3* poly, int polyLength,
518        const Vector3& lightCenter, float lightSize, int lightVertexCount,
519        VertexBuffer& retStrips) {
520    Vector3 light[lightVertexCount * 3];
521    computeLightPolygon(lightVertexCount, lightCenter, lightSize, light);
522    computeSpotShadow(light, lightVertexCount, lightCenter, poly, polyLength,
523            retStrips);
524}
525
526/**
527 * Generate the shadow spot light of shape lightPoly and a object poly
528 *
529 * @param lightPoly x,y,z vertex of a convex polygon that is the light source
530 * @param lightPolyLength number of vertexes of the light source polygon
531 * @param poly x,y,z vertexes of a convex polygon that occludes the light source
532 * @param polyLength number of vertexes of the occluding polygon
533 * @param shadowTriangleStrip return an (x,y,alpha) triangle strip representing the shadow. Return
534 *                            empty strip if error.
535 */
536void SpotShadow::computeSpotShadow(const Vector3* lightPoly, int lightPolyLength,
537        const Vector3& lightCenter, const Vector3* poly, int polyLength,
538        VertexBuffer& shadowTriangleStrip) {
539    // Point clouds for all the shadowed vertices
540    Vector2 shadowRegion[lightPolyLength * polyLength];
541    // Shadow polygon from one point light.
542    Vector2 outline[polyLength];
543    Vector2 umbraMem[polyLength * lightPolyLength];
544    Vector2* umbra = umbraMem;
545
546    int umbraLength = 0;
547
548    // Validate input, receiver is always at z = 0 plane.
549    bool inputPolyPositionValid = true;
550    for (int i = 0; i < polyLength; i++) {
551        if (poly[i].z <= 0.00001) {
552            inputPolyPositionValid = false;
553            ALOGE("polygon below the surface");
554            break;
555        }
556        if (poly[i].z >= lightPoly[0].z) {
557            inputPolyPositionValid = false;
558            ALOGE("polygon above the light");
559            break;
560        }
561    }
562
563    // If the caster's position is invalid, don't draw anything.
564    if (!inputPolyPositionValid) {
565        return;
566    }
567
568    // Calculate the umbra polygon based on intersections of all outlines
569    int k = 0;
570    for (int j = 0; j < lightPolyLength; j++) {
571        int m = 0;
572        for (int i = 0; i < polyLength; i++) {
573            float t = lightPoly[j].z - poly[i].z;
574            if (t == 0) {
575                return;
576            }
577            t = lightPoly[j].z / t;
578            float x = lightPoly[j].x - t * (lightPoly[j].x - poly[i].x);
579            float y = lightPoly[j].y - t * (lightPoly[j].y - poly[i].y);
580
581            Vector2 newPoint = Vector2(x, y);
582            shadowRegion[k] = newPoint;
583            outline[m] = newPoint;
584
585            k++;
586            m++;
587        }
588
589        // For the first light polygon's vertex, use the outline as the umbra.
590        // Later on, use the intersection of the outline and existing umbra.
591        if (umbraLength == 0) {
592            for (int i = 0; i < polyLength; i++) {
593                umbra[i] = outline[i];
594            }
595            umbraLength = polyLength;
596        } else {
597            int col = ((j * 255) / lightPolyLength);
598            umbraLength = intersection(outline, polyLength, umbra, umbraLength);
599            if (umbraLength == 0) {
600                break;
601            }
602        }
603    }
604
605    // Generate the penumbra area using the hull of all shadow regions.
606    int shadowRegionLength = k;
607    Vector2 penumbra[k];
608    int penumbraLength = hull(shadowRegion, shadowRegionLength, penumbra);
609
610    Vector2 fakeUmbra[polyLength];
611    if (umbraLength < 3) {
612        // If there is no real umbra, make a fake one.
613        for (int i = 0; i < polyLength; i++) {
614            float t = lightCenter.z - poly[i].z;
615            if (t == 0) {
616                return;
617            }
618            t = lightCenter.z / t;
619            float x = lightCenter.x - t * (lightCenter.x - poly[i].x);
620            float y = lightCenter.y - t * (lightCenter.y - poly[i].y);
621
622            fakeUmbra[i].x = x;
623            fakeUmbra[i].y = y;
624        }
625
626        // Shrink the centroid's shadow by 10%.
627        // TODO: Study the magic number of 10%.
628        Vector2 shadowCentroid =
629                ShadowTessellator::centroid2d(fakeUmbra, polyLength);
630        for (int i = 0; i < polyLength; i++) {
631            fakeUmbra[i] = shadowCentroid * (1.0f - SHADOW_SHRINK_SCALE) +
632                    fakeUmbra[i] * SHADOW_SHRINK_SCALE;
633        }
634#if DEBUG_SHADOW
635        ALOGD("No real umbra make a fake one, centroid2d =  %f , %f",
636                shadowCentroid.x, shadowCentroid.y);
637#endif
638        // Set the fake umbra, whose size is the same as the original polygon.
639        umbra = fakeUmbra;
640        umbraLength = polyLength;
641    }
642
643    generateTriangleStrip(penumbra, penumbraLength, umbra, umbraLength,
644            shadowTriangleStrip);
645}
646
647/**
648 * Converts a polygon specified with CW vertices into an array of distance-from-centroid values.
649 *
650 * Returns false in error conditions
651 *
652 * @param poly Array of vertices. Note that these *must* be CW.
653 * @param polyLength The number of vertices in the polygon.
654 * @param polyCentroid The centroid of the polygon, from which rays will be cast
655 * @param rayDist The output array for the calculated distances, must be SHADOW_RAY_COUNT in size
656 */
657bool convertPolyToRayDist(const Vector2* poly, int polyLength, const Vector2& polyCentroid,
658        float* rayDist) {
659    const int rays = SHADOW_RAY_COUNT;
660    const float step = M_PI * 2 / rays;
661
662    const Vector2* lastVertex = &(poly[polyLength - 1]);
663    float startAngle = angle(*lastVertex, polyCentroid);
664
665    // Start with the ray that's closest to and less than startAngle
666    int rayIndex = floor((startAngle - EPSILON) / step);
667    rayIndex = (rayIndex + rays) % rays; // ensure positive
668
669    for (int polyIndex = 0; polyIndex < polyLength; polyIndex++) {
670        /*
671         * For a given pair of vertices on the polygon, poly[i-1] and poly[i], the rays that
672         * intersect these will be those that are between the two angles from the centroid that the
673         * vertices define.
674         *
675         * Because the polygon vertices are stored clockwise, the closest ray with an angle
676         * *smaller* than that defined by angle(poly[i], centroid) will be the first ray that does
677         * not intersect with poly[i-1], poly[i].
678         */
679        float currentAngle = angle(poly[polyIndex], polyCentroid);
680
681        // find first ray that will not intersect the line segment poly[i-1] & poly[i]
682        int firstRayIndexOnNextSegment = floor((currentAngle - EPSILON) / step);
683        firstRayIndexOnNextSegment = (firstRayIndexOnNextSegment + rays) % rays; // ensure positive
684
685        // Iterate through all rays that intersect with poly[i-1], poly[i] line segment.
686        // This may be 0 rays.
687        while (rayIndex != firstRayIndexOnNextSegment) {
688            float distanceToIntersect = rayIntersectPoints(polyCentroid,
689                    cos(rayIndex * step),
690                    sin(rayIndex * step),
691                    *lastVertex, poly[polyIndex]);
692            if (distanceToIntersect < 0) return false; // error case, abort
693
694            rayDist[rayIndex] = distanceToIntersect;
695
696            rayIndex = (rayIndex - 1 + rays) % rays;
697        }
698        lastVertex = &poly[polyIndex];
699    }
700
701   return true;
702}
703
704/**
705 * Generate a triangle strip given two convex polygons
706 *
707 * @param penumbra The outer polygon x,y vertexes
708 * @param penumbraLength The number of vertexes in the outer polygon
709 * @param umbra The inner outer polygon x,y vertexes
710 * @param umbraLength The number of vertexes in the inner polygon
711 * @param shadowTriangleStrip return an (x,y,alpha) triangle strip representing the shadow. Return
712 *                            empty strip if error.
713**/
714void SpotShadow::generateTriangleStrip(const Vector2* penumbra, int penumbraLength,
715        const Vector2* umbra, int umbraLength, VertexBuffer& shadowTriangleStrip) {
716    const int rays = SHADOW_RAY_COUNT;
717
718    const int size = 2 * rays;
719    const float step = M_PI * 2 / rays;
720    // Centroid of the umbra.
721    Vector2 centroid = ShadowTessellator::centroid2d(umbra, umbraLength);
722#if DEBUG_SHADOW
723    ALOGD("centroid2d =  %f , %f", centroid.x, centroid.y);
724#endif
725    // Intersection to the penumbra.
726    float penumbraDistPerRay[rays];
727    // Intersection to the umbra.
728    float umbraDistPerRay[rays];
729
730    // convert CW polygons to ray distance encoding, aborting on conversion failure
731    if (!convertPolyToRayDist(umbra, umbraLength, centroid, umbraDistPerRay)) return;
732    if (!convertPolyToRayDist(penumbra, penumbraLength, centroid, penumbraDistPerRay)) return;
733
734    AlphaVertex* shadowVertices = shadowTriangleStrip.alloc<AlphaVertex>(getStripSize(rays));
735
736    // Calculate the vertices (x, y, alpha) in the shadow area.
737    for (int rayIndex = 0; rayIndex < rays; rayIndex++) {
738        float dx = cosf(step * rayIndex);
739        float dy = sinf(step * rayIndex);
740
741        // outer ring
742        float currentDist = penumbraDistPerRay[rayIndex];
743        AlphaVertex::set(&shadowVertices[rayIndex],
744                dx * currentDist + centroid.x, dy * currentDist + centroid.y, 0.0f);
745
746        // inner ring
747        float deltaDist = umbraDistPerRay[rayIndex] - penumbraDistPerRay[rayIndex];
748        currentDist += deltaDist;
749        AlphaVertex::set(&shadowVertices[rays + rayIndex],
750                dx * currentDist + centroid.x, dy * currentDist + centroid.y, 1.0f);
751    }
752    // The centroid is in the umbra area, so the opacity is considered as 1.0.
753    AlphaVertex::set(&shadowVertices[SHADOW_VERTEX_COUNT - 1], centroid.x, centroid.y, 1.0f);
754#if DEBUG_SHADOW
755    for (int i = 0; i < currentIndex; i++) {
756        ALOGD("spot shadow value: i %d, (x:%f, y:%f, a:%f)", i, shadowVertices[i].x,
757                shadowVertices[i].y, shadowVertices[i].alpha);
758    }
759#endif
760}
761
762/**
763 * This is only for experimental purpose.
764 * After intersections are calculated, we could smooth the polygon if needed.
765 * So far, we don't think it is more appealing yet.
766 *
767 * @param level The level of smoothness.
768 * @param rays The total number of rays.
769 * @param rayDist (In and Out) The distance for each ray.
770 *
771 */
772void SpotShadow::smoothPolygon(int level, int rays, float* rayDist) {
773    for (int k = 0; k < level; k++) {
774        for (int i = 0; i < rays; i++) {
775            float p1 = rayDist[(rays - 1 + i) % rays];
776            float p2 = rayDist[i];
777            float p3 = rayDist[(i + 1) % rays];
778            rayDist[i] = (p1 + p2 * 2 + p3) / 4;
779        }
780    }
781}
782
783/**
784 * Calculate the number of vertex we will create given a number of rays and layers
785 *
786 * @param rays number of points around the polygons you want
787 * @param layers number of layers of triangle strips you need
788 * @return number of vertex (multiply by 3 for number of floats)
789 */
790int SpotShadow::getStripSize(int rays) {
791    return  (2 + rays + (2 * (rays + 1)));
792}
793
794#if DEBUG_SHADOW
795
796#define TEST_POINT_NUMBER 128
797
798/**
799 * Calculate the bounds for generating random test points.
800 */
801void SpotShadow::updateBound(const Vector2 inVector, Vector2& lowerBound,
802        Vector2& upperBound ) {
803    if (inVector.x < lowerBound.x) {
804        lowerBound.x = inVector.x;
805    }
806
807    if (inVector.y < lowerBound.y) {
808        lowerBound.y = inVector.y;
809    }
810
811    if (inVector.x > upperBound.x) {
812        upperBound.x = inVector.x;
813    }
814
815    if (inVector.y > upperBound.y) {
816        upperBound.y = inVector.y;
817    }
818}
819
820/**
821 * For debug purpose, when things go wrong, dump the whole polygon data.
822 */
823static void dumpPolygon(const Vector2* poly, int polyLength, const char* polyName) {
824    for (int i = 0; i < polyLength; i++) {
825        ALOGD("polygon %s i %d x %f y %f", polyName, i, poly[i].x, poly[i].y);
826    }
827}
828
829/**
830 * Test whether the polygon is convex.
831 */
832bool SpotShadow::testConvex(const Vector2* polygon, int polygonLength,
833        const char* name) {
834    bool isConvex = true;
835    for (int i = 0; i < polygonLength; i++) {
836        Vector2 start = polygon[i];
837        Vector2 middle = polygon[(i + 1) % polygonLength];
838        Vector2 end = polygon[(i + 2) % polygonLength];
839
840        double delta = (double(middle.x) - start.x) * (double(end.y) - start.y) -
841                (double(middle.y) - start.y) * (double(end.x) - start.x);
842        bool isCCWOrCoLinear = (delta >= EPSILON);
843
844        if (isCCWOrCoLinear) {
845            ALOGE("(Error Type 2): polygon (%s) is not a convex b/c start (x %f, y %f),"
846                    "middle (x %f, y %f) and end (x %f, y %f) , delta is %f !!!",
847                    name, start.x, start.y, middle.x, middle.y, end.x, end.y, delta);
848            isConvex = false;
849            break;
850        }
851    }
852    return isConvex;
853}
854
855/**
856 * Test whether or not the polygon (intersection) is within the 2 input polygons.
857 * Using Marte Carlo method, we generate a random point, and if it is inside the
858 * intersection, then it must be inside both source polygons.
859 */
860void SpotShadow::testIntersection(const Vector2* poly1, int poly1Length,
861        const Vector2* poly2, int poly2Length,
862        const Vector2* intersection, int intersectionLength) {
863    // Find the min and max of x and y.
864    Vector2 lowerBound(FLT_MAX, FLT_MAX);
865    Vector2 upperBound(-FLT_MAX, -FLT_MAX);
866    for (int i = 0; i < poly1Length; i++) {
867        updateBound(poly1[i], lowerBound, upperBound);
868    }
869    for (int i = 0; i < poly2Length; i++) {
870        updateBound(poly2[i], lowerBound, upperBound);
871    }
872
873    bool dumpPoly = false;
874    for (int k = 0; k < TEST_POINT_NUMBER; k++) {
875        // Generate a random point between minX, minY and maxX, maxY.
876        double randomX = rand() / double(RAND_MAX);
877        double randomY = rand() / double(RAND_MAX);
878
879        Vector2 testPoint;
880        testPoint.x = lowerBound.x + randomX * (upperBound.x - lowerBound.x);
881        testPoint.y = lowerBound.y + randomY * (upperBound.y - lowerBound.y);
882
883        // If the random point is in both poly 1 and 2, then it must be intersection.
884        if (testPointInsidePolygon(testPoint, intersection, intersectionLength)) {
885            if (!testPointInsidePolygon(testPoint, poly1, poly1Length)) {
886                dumpPoly = true;
887                ALOGE("(Error Type 1): one point (%f, %f) in the intersection is"
888                      " not in the poly1",
889                        testPoint.x, testPoint.y);
890            }
891
892            if (!testPointInsidePolygon(testPoint, poly2, poly2Length)) {
893                dumpPoly = true;
894                ALOGE("(Error Type 1): one point (%f, %f) in the intersection is"
895                      " not in the poly2",
896                        testPoint.x, testPoint.y);
897            }
898        }
899    }
900
901    if (dumpPoly) {
902        dumpPolygon(intersection, intersectionLength, "intersection");
903        for (int i = 1; i < intersectionLength; i++) {
904            Vector2 delta = intersection[i] - intersection[i - 1];
905            ALOGD("Intersetion i, %d Vs i-1 is delta %f", i, delta.lengthSquared());
906        }
907
908        dumpPolygon(poly1, poly1Length, "poly 1");
909        dumpPolygon(poly2, poly2Length, "poly 2");
910    }
911}
912#endif
913
914}; // namespace uirenderer
915}; // namespace android
916