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