blob: f81cd12d82ab40cde261bec987ad7e7e21b97068 [file] [log] [blame]
ztenghui7b4516e2014-01-07 10:42:55 -08001/*
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>
ztenghuif5ca8b42014-01-27 15:53:28 -080022#include <stdlib.h>
ztenghui7b4516e2014-01-07 10:42:55 -080023#include <utils/Log.h>
24
ztenghui63d41ab2014-02-14 13:13:41 -080025#include "ShadowTessellator.h"
ztenghui7b4516e2014-01-07 10:42:55 -080026#include "SpotShadow.h"
27#include "Vertex.h"
28
29namespace android {
30namespace uirenderer {
31
Chris Craik726118b2014-03-07 18:27:49 -080032static const double EPSILON = 1e-7;
33
ztenghui7b4516e2014-01-07 10:42:55 -080034/**
Chris Craik726118b2014-03-07 18:27:49 -080035 * Calculate the angle between and x and a y coordinate.
36 * The atan2 range from -PI to PI.
ztenghui7b4516e2014-01-07 10:42:55 -080037 */
Chris Craikb79a3e32014-03-11 12:20:17 -070038static float angle(const Vector2& point, const Vector2& center) {
Chris Craik726118b2014-03-07 18:27:49 -080039 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 */
Chris Craikb79a3e32014-03-11 12:20:17 -070054static float rayIntersectPoints(const Vector2& rayOrigin, float dx, float dy,
Chris Craik726118b2014-03-07 18:27:49 -080055 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;
ztenghui99af9422014-03-14 14:35:54 -070065 if (interpVal < 0 || interpVal > 1) {
66 ALOGW("rayIntersectPoints is hitting outside the segment %f", interpVal);
67 }
Chris Craik726118b2014-03-07 18:27:49 -080068#endif
69
70 double distance = (p1.x * (rayOrigin.y - p2.y) + p2.x * (p1.y - rayOrigin.y) +
71 rayOrigin.x * (p2.y - p1.y)) / divisor;
72
73 return distance; // may be negative in error cases
ztenghui7b4516e2014-01-07 10:42:55 -080074}
75
76/**
ztenghui7b4516e2014-01-07 10:42:55 -080077 * Sort points by their X coordinates
78 *
79 * @param points the points as a Vector2 array.
80 * @param pointsLength the number of vertices of the polygon.
81 */
82void SpotShadow::xsort(Vector2* points, int pointsLength) {
83 quicksortX(points, 0, pointsLength - 1);
84}
85
86/**
87 * compute the convex hull of a collection of Points
88 *
89 * @param points the points as a Vector2 array.
90 * @param pointsLength the number of vertices of the polygon.
91 * @param retPoly pre allocated array of floats to put the vertices
92 * @return the number of points in the polygon 0 if no intersection
93 */
94int SpotShadow::hull(Vector2* points, int pointsLength, Vector2* retPoly) {
95 xsort(points, pointsLength);
96 int n = pointsLength;
97 Vector2 lUpper[n];
98 lUpper[0] = points[0];
99 lUpper[1] = points[1];
100
101 int lUpperSize = 2;
102
103 for (int i = 2; i < n; i++) {
104 lUpper[lUpperSize] = points[i];
105 lUpperSize++;
106
ztenghuif5ca8b42014-01-27 15:53:28 -0800107 while (lUpperSize > 2 && !ccw(
108 lUpper[lUpperSize - 3].x, lUpper[lUpperSize - 3].y,
109 lUpper[lUpperSize - 2].x, lUpper[lUpperSize - 2].y,
110 lUpper[lUpperSize - 1].x, lUpper[lUpperSize - 1].y)) {
ztenghui7b4516e2014-01-07 10:42:55 -0800111 // Remove the middle point of the three last
112 lUpper[lUpperSize - 2].x = lUpper[lUpperSize - 1].x;
113 lUpper[lUpperSize - 2].y = lUpper[lUpperSize - 1].y;
114 lUpperSize--;
115 }
116 }
117
118 Vector2 lLower[n];
119 lLower[0] = points[n - 1];
120 lLower[1] = points[n - 2];
121
122 int lLowerSize = 2;
123
124 for (int i = n - 3; i >= 0; i--) {
125 lLower[lLowerSize] = points[i];
126 lLowerSize++;
127
ztenghuif5ca8b42014-01-27 15:53:28 -0800128 while (lLowerSize > 2 && !ccw(
129 lLower[lLowerSize - 3].x, lLower[lLowerSize - 3].y,
130 lLower[lLowerSize - 2].x, lLower[lLowerSize - 2].y,
131 lLower[lLowerSize - 1].x, lLower[lLowerSize - 1].y)) {
ztenghui7b4516e2014-01-07 10:42:55 -0800132 // Remove the middle point of the three last
133 lLower[lLowerSize - 2] = lLower[lLowerSize - 1];
134 lLowerSize--;
135 }
136 }
ztenghui7b4516e2014-01-07 10:42:55 -0800137
Chris Craik726118b2014-03-07 18:27:49 -0800138 // output points in CW ordering
139 const int total = lUpperSize + lLowerSize - 2;
140 int outIndex = total - 1;
ztenghui7b4516e2014-01-07 10:42:55 -0800141 for (int i = 0; i < lUpperSize; i++) {
Chris Craik726118b2014-03-07 18:27:49 -0800142 retPoly[outIndex] = lUpper[i];
143 outIndex--;
ztenghui7b4516e2014-01-07 10:42:55 -0800144 }
145
146 for (int i = 1; i < lLowerSize - 1; i++) {
Chris Craik726118b2014-03-07 18:27:49 -0800147 retPoly[outIndex] = lLower[i];
148 outIndex--;
ztenghui7b4516e2014-01-07 10:42:55 -0800149 }
150 // TODO: Add test harness which verify that all the points are inside the hull.
Chris Craik726118b2014-03-07 18:27:49 -0800151 return total;
ztenghui7b4516e2014-01-07 10:42:55 -0800152}
153
154/**
ztenghuif5ca8b42014-01-27 15:53:28 -0800155 * Test whether the 3 points form a counter clockwise turn.
ztenghui7b4516e2014-01-07 10:42:55 -0800156 *
ztenghui7b4516e2014-01-07 10:42:55 -0800157 * @return true if a right hand turn
158 */
ztenghuif5ca8b42014-01-27 15:53:28 -0800159bool SpotShadow::ccw(double ax, double ay, double bx, double by,
ztenghui7b4516e2014-01-07 10:42:55 -0800160 double cx, double cy) {
161 return (bx - ax) * (cy - ay) - (by - ay) * (cx - ax) > EPSILON;
162}
163
164/**
165 * Calculates the intersection of poly1 with poly2 and put in poly2.
ztenghui50ecf842014-03-11 16:52:30 -0700166 * Note that both poly1 and poly2 must be in CW order already!
ztenghui7b4516e2014-01-07 10:42:55 -0800167 *
168 * @param poly1 The 1st polygon, as a Vector2 array.
169 * @param poly1Length The number of vertices of 1st polygon.
170 * @param poly2 The 2nd and output polygon, as a Vector2 array.
171 * @param poly2Length The number of vertices of 2nd polygon.
172 * @return number of vertices in output polygon as poly2.
173 */
ztenghui50ecf842014-03-11 16:52:30 -0700174int SpotShadow::intersection(const Vector2* poly1, int poly1Length,
ztenghui7b4516e2014-01-07 10:42:55 -0800175 Vector2* poly2, int poly2Length) {
ztenghui50ecf842014-03-11 16:52:30 -0700176#if DEBUG_SHADOW
177 if (!isClockwise(poly1, poly1Length)) {
178 ALOGW("Poly1 is not clockwise! Intersection is wrong!");
179 }
180 if (!isClockwise(poly2, poly2Length)) {
181 ALOGW("Poly2 is not clockwise! Intersection is wrong!");
182 }
183#endif
ztenghui7b4516e2014-01-07 10:42:55 -0800184 Vector2 poly[poly1Length * poly2Length + 2];
185 int count = 0;
186 int pcount = 0;
187
188 // If one vertex from one polygon sits inside another polygon, add it and
189 // count them.
190 for (int i = 0; i < poly1Length; i++) {
191 if (testPointInsidePolygon(poly1[i], poly2, poly2Length)) {
192 poly[count] = poly1[i];
193 count++;
194 pcount++;
195
196 }
197 }
198
199 int insidePoly2 = pcount;
200 for (int i = 0; i < poly2Length; i++) {
201 if (testPointInsidePolygon(poly2[i], poly1, poly1Length)) {
202 poly[count] = poly2[i];
203 count++;
204 }
205 }
206
207 int insidePoly1 = count - insidePoly2;
208 // If all vertices from poly1 are inside poly2, then just return poly1.
209 if (insidePoly2 == poly1Length) {
210 memcpy(poly2, poly1, poly1Length * sizeof(Vector2));
211 return poly1Length;
212 }
213
214 // If all vertices from poly2 are inside poly1, then just return poly2.
215 if (insidePoly1 == poly2Length) {
216 return poly2Length;
217 }
218
219 // Since neither polygon fully contain the other one, we need to add all the
220 // intersection points.
221 Vector2 intersection;
222 for (int i = 0; i < poly2Length; i++) {
223 for (int j = 0; j < poly1Length; j++) {
224 int poly2LineStart = i;
225 int poly2LineEnd = ((i + 1) % poly2Length);
226 int poly1LineStart = j;
227 int poly1LineEnd = ((j + 1) % poly1Length);
228 bool found = lineIntersection(
229 poly2[poly2LineStart].x, poly2[poly2LineStart].y,
230 poly2[poly2LineEnd].x, poly2[poly2LineEnd].y,
231 poly1[poly1LineStart].x, poly1[poly1LineStart].y,
232 poly1[poly1LineEnd].x, poly1[poly1LineEnd].y,
233 intersection);
234 if (found) {
235 poly[count].x = intersection.x;
236 poly[count].y = intersection.y;
237 count++;
238 } else {
239 Vector2 delta = poly2[i] - poly1[j];
ztenghuif5ca8b42014-01-27 15:53:28 -0800240 if (delta.lengthSquared() < EPSILON) {
ztenghui7b4516e2014-01-07 10:42:55 -0800241 poly[count] = poly2[i];
242 count++;
243 }
244 }
245 }
246 }
247
248 if (count == 0) {
249 return 0;
250 }
251
252 // Sort the result polygon around the center.
253 Vector2 center(0.0f, 0.0f);
254 for (int i = 0; i < count; i++) {
255 center += poly[i];
256 }
257 center /= count;
258 sort(poly, count, center);
259
ztenghuif5ca8b42014-01-27 15:53:28 -0800260#if DEBUG_SHADOW
261 // Since poly2 is overwritten as the result, we need to save a copy to do
262 // our verification.
263 Vector2 oldPoly2[poly2Length];
264 int oldPoly2Length = poly2Length;
265 memcpy(oldPoly2, poly2, sizeof(Vector2) * poly2Length);
266#endif
ztenghui7b4516e2014-01-07 10:42:55 -0800267
ztenghuif5ca8b42014-01-27 15:53:28 -0800268 // Filter the result out from poly and put it into poly2.
ztenghui7b4516e2014-01-07 10:42:55 -0800269 poly2[0] = poly[0];
ztenghuif5ca8b42014-01-27 15:53:28 -0800270 int lastOutputIndex = 0;
ztenghui7b4516e2014-01-07 10:42:55 -0800271 for (int i = 1; i < count; i++) {
ztenghuif5ca8b42014-01-27 15:53:28 -0800272 Vector2 delta = poly[i] - poly2[lastOutputIndex];
273 if (delta.lengthSquared() >= EPSILON) {
274 poly2[++lastOutputIndex] = poly[i];
275 } else {
276 // If the vertices are too close, pick the inner one, because the
277 // inner one is more likely to be an intersection point.
278 Vector2 delta1 = poly[i] - center;
279 Vector2 delta2 = poly2[lastOutputIndex] - center;
280 if (delta1.lengthSquared() < delta2.lengthSquared()) {
281 poly2[lastOutputIndex] = poly[i];
282 }
ztenghui7b4516e2014-01-07 10:42:55 -0800283 }
284 }
ztenghuif5ca8b42014-01-27 15:53:28 -0800285 int resultLength = lastOutputIndex + 1;
286
287#if DEBUG_SHADOW
288 testConvex(poly2, resultLength, "intersection");
289 testConvex(poly1, poly1Length, "input poly1");
290 testConvex(oldPoly2, oldPoly2Length, "input poly2");
291
292 testIntersection(poly1, poly1Length, oldPoly2, oldPoly2Length, poly2, resultLength);
293#endif
ztenghui7b4516e2014-01-07 10:42:55 -0800294
295 return resultLength;
296}
297
298/**
299 * Sort points about a center point
300 *
301 * @param poly The in and out polyogon as a Vector2 array.
302 * @param polyLength The number of vertices of the polygon.
303 * @param center the center ctr[0] = x , ctr[1] = y to sort around.
304 */
305void SpotShadow::sort(Vector2* poly, int polyLength, const Vector2& center) {
306 quicksortCirc(poly, 0, polyLength - 1, center);
307}
308
309/**
ztenghui7b4516e2014-01-07 10:42:55 -0800310 * Swap points pointed to by i and j
311 */
312void SpotShadow::swap(Vector2* points, int i, int j) {
313 Vector2 temp = points[i];
314 points[i] = points[j];
315 points[j] = temp;
316}
317
318/**
319 * quick sort implementation about the center.
320 */
321void SpotShadow::quicksortCirc(Vector2* points, int low, int high,
322 const Vector2& center) {
323 int i = low, j = high;
324 int p = low + (high - low) / 2;
325 float pivot = angle(points[p], center);
326 while (i <= j) {
Chris Craik726118b2014-03-07 18:27:49 -0800327 while (angle(points[i], center) > pivot) {
ztenghui7b4516e2014-01-07 10:42:55 -0800328 i++;
329 }
Chris Craik726118b2014-03-07 18:27:49 -0800330 while (angle(points[j], center) < pivot) {
ztenghui7b4516e2014-01-07 10:42:55 -0800331 j--;
332 }
333
334 if (i <= j) {
335 swap(points, i, j);
336 i++;
337 j--;
338 }
339 }
340 if (low < j) quicksortCirc(points, low, j, center);
341 if (i < high) quicksortCirc(points, i, high, center);
342}
343
344/**
345 * Sort points by x axis
346 *
347 * @param points points to sort
348 * @param low start index
349 * @param high end index
350 */
351void SpotShadow::quicksortX(Vector2* points, int low, int high) {
352 int i = low, j = high;
353 int p = low + (high - low) / 2;
354 float pivot = points[p].x;
355 while (i <= j) {
356 while (points[i].x < pivot) {
357 i++;
358 }
359 while (points[j].x > pivot) {
360 j--;
361 }
362
363 if (i <= j) {
364 swap(points, i, j);
365 i++;
366 j--;
367 }
368 }
369 if (low < j) quicksortX(points, low, j);
370 if (i < high) quicksortX(points, i, high);
371}
372
373/**
374 * Test whether a point is inside the polygon.
375 *
376 * @param testPoint the point to test
377 * @param poly the polygon
378 * @return true if the testPoint is inside the poly.
379 */
380bool SpotShadow::testPointInsidePolygon(const Vector2 testPoint,
381 const Vector2* poly, int len) {
382 bool c = false;
383 double testx = testPoint.x;
384 double testy = testPoint.y;
385 for (int i = 0, j = len - 1; i < len; j = i++) {
386 double startX = poly[j].x;
387 double startY = poly[j].y;
388 double endX = poly[i].x;
389 double endY = poly[i].y;
390
391 if (((endY > testy) != (startY > testy)) &&
392 (testx < (startX - endX) * (testy - endY)
393 / (startY - endY) + endX)) {
394 c = !c;
395 }
396 }
397 return c;
398}
399
400/**
401 * Make the polygon turn clockwise.
402 *
403 * @param polygon the polygon as a Vector2 array.
404 * @param len the number of points of the polygon
405 */
406void SpotShadow::makeClockwise(Vector2* polygon, int len) {
407 if (polygon == 0 || len == 0) {
408 return;
409 }
410 if (!isClockwise(polygon, len)) {
411 reverse(polygon, len);
412 }
413}
414
415/**
416 * Test whether the polygon is order in clockwise.
417 *
418 * @param polygon the polygon as a Vector2 array
419 * @param len the number of points of the polygon
420 */
ztenghui50ecf842014-03-11 16:52:30 -0700421bool SpotShadow::isClockwise(const Vector2* polygon, int len) {
ztenghui7b4516e2014-01-07 10:42:55 -0800422 double sum = 0;
423 double p1x = polygon[len - 1].x;
424 double p1y = polygon[len - 1].y;
425 for (int i = 0; i < len; i++) {
426
427 double p2x = polygon[i].x;
428 double p2y = polygon[i].y;
429 sum += p1x * p2y - p2x * p1y;
430 p1x = p2x;
431 p1y = p2y;
432 }
433 return sum < 0;
434}
435
436/**
437 * Reverse the polygon
438 *
439 * @param polygon the polygon as a Vector2 array
440 * @param len the number of points of the polygon
441 */
442void SpotShadow::reverse(Vector2* polygon, int len) {
443 int n = len / 2;
444 for (int i = 0; i < n; i++) {
445 Vector2 tmp = polygon[i];
446 int k = len - 1 - i;
447 polygon[i] = polygon[k];
448 polygon[k] = tmp;
449 }
450}
451
452/**
453 * Intersects two lines in parametric form. This function is called in a tight
454 * loop, and we need double precision to get things right.
455 *
456 * @param x1 the x coordinate point 1 of line 1
457 * @param y1 the y coordinate point 1 of line 1
458 * @param x2 the x coordinate point 2 of line 1
459 * @param y2 the y coordinate point 2 of line 1
460 * @param x3 the x coordinate point 1 of line 2
461 * @param y3 the y coordinate point 1 of line 2
462 * @param x4 the x coordinate point 2 of line 2
463 * @param y4 the y coordinate point 2 of line 2
464 * @param ret the x,y location of the intersection
465 * @return true if it found an intersection
466 */
467inline bool SpotShadow::lineIntersection(double x1, double y1, double x2, double y2,
468 double x3, double y3, double x4, double y4, Vector2& ret) {
469 double d = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4);
470 if (d == 0.0) return false;
471
472 double dx = (x1 * y2 - y1 * x2);
473 double dy = (x3 * y4 - y3 * x4);
474 double x = (dx * (x3 - x4) - (x1 - x2) * dy) / d;
475 double y = (dx * (y3 - y4) - (y1 - y2) * dy) / d;
476
477 // The intersection should be in the middle of the point 1 and point 2,
478 // likewise point 3 and point 4.
479 if (((x - x1) * (x - x2) > EPSILON)
480 || ((x - x3) * (x - x4) > EPSILON)
481 || ((y - y1) * (y - y2) > EPSILON)
482 || ((y - y3) * (y - y4) > EPSILON)) {
483 // Not interesected
484 return false;
485 }
486 ret.x = x;
487 ret.y = y;
488 return true;
489
490}
491
492/**
493 * Compute a horizontal circular polygon about point (x , y , height) of radius
494 * (size)
495 *
496 * @param points number of the points of the output polygon.
497 * @param lightCenter the center of the light.
498 * @param size the light size.
499 * @param ret result polygon.
500 */
501void SpotShadow::computeLightPolygon(int points, const Vector3& lightCenter,
502 float size, Vector3* ret) {
503 // TODO: Caching all the sin / cos values and store them in a look up table.
504 for (int i = 0; i < points; i++) {
505 double angle = 2 * i * M_PI / points;
Chris Craik726118b2014-03-07 18:27:49 -0800506 ret[i].x = cosf(angle) * size + lightCenter.x;
507 ret[i].y = sinf(angle) * size + lightCenter.y;
ztenghui7b4516e2014-01-07 10:42:55 -0800508 ret[i].z = lightCenter.z;
509 }
510}
511
512/**
513* Generate the shadow from a spot light.
514*
515* @param poly x,y,z vertexes of a convex polygon that occludes the light source
516* @param polyLength number of vertexes of the occluding polygon
517* @param lightCenter the center of the light
518* @param lightSize the radius of the light source
519* @param lightVertexCount the vertex counter for the light polygon
ztenghui7b4516e2014-01-07 10:42:55 -0800520* @param shadowTriangleStrip return an (x,y,alpha) triangle strip representing the shadow. Return
521* empty strip if error.
522*
523*/
ztenghui50ecf842014-03-11 16:52:30 -0700524VertexBufferMode SpotShadow::createSpotShadow(bool isCasterOpaque, const Vector3* poly,
525 int polyLength, const Vector3& lightCenter, float lightSize,
526 int lightVertexCount, VertexBuffer& retStrips) {
ztenghui7b4516e2014-01-07 10:42:55 -0800527 Vector3 light[lightVertexCount * 3];
528 computeLightPolygon(lightVertexCount, lightCenter, lightSize, light);
ztenghui50ecf842014-03-11 16:52:30 -0700529 computeSpotShadow(isCasterOpaque, light, lightVertexCount, lightCenter, poly,
530 polyLength, retStrips);
531 return kVertexBufferMode_TwoPolyRingShadow;
ztenghui7b4516e2014-01-07 10:42:55 -0800532}
533
534/**
535 * Generate the shadow spot light of shape lightPoly and a object poly
536 *
537 * @param lightPoly x,y,z vertex of a convex polygon that is the light source
538 * @param lightPolyLength number of vertexes of the light source polygon
539 * @param poly x,y,z vertexes of a convex polygon that occludes the light source
540 * @param polyLength number of vertexes of the occluding polygon
ztenghui7b4516e2014-01-07 10:42:55 -0800541 * @param shadowTriangleStrip return an (x,y,alpha) triangle strip representing the shadow. Return
542 * empty strip if error.
543 */
ztenghui50ecf842014-03-11 16:52:30 -0700544void SpotShadow::computeSpotShadow(bool isCasterOpaque, const Vector3* lightPoly,
545 int lightPolyLength, const Vector3& lightCenter, const Vector3* poly,
546 int polyLength, VertexBuffer& shadowTriangleStrip) {
ztenghui7b4516e2014-01-07 10:42:55 -0800547 // Point clouds for all the shadowed vertices
548 Vector2 shadowRegion[lightPolyLength * polyLength];
549 // Shadow polygon from one point light.
550 Vector2 outline[polyLength];
551 Vector2 umbraMem[polyLength * lightPolyLength];
552 Vector2* umbra = umbraMem;
553
554 int umbraLength = 0;
555
556 // Validate input, receiver is always at z = 0 plane.
557 bool inputPolyPositionValid = true;
558 for (int i = 0; i < polyLength; i++) {
ztenghui7b4516e2014-01-07 10:42:55 -0800559 if (poly[i].z >= lightPoly[0].z) {
560 inputPolyPositionValid = false;
Chris Craikb79a3e32014-03-11 12:20:17 -0700561 ALOGW("polygon above the light");
ztenghui7b4516e2014-01-07 10:42:55 -0800562 break;
563 }
564 }
565
566 // If the caster's position is invalid, don't draw anything.
567 if (!inputPolyPositionValid) {
568 return;
569 }
570
571 // Calculate the umbra polygon based on intersections of all outlines
572 int k = 0;
573 for (int j = 0; j < lightPolyLength; j++) {
574 int m = 0;
575 for (int i = 0; i < polyLength; i++) {
ztenghui50ecf842014-03-11 16:52:30 -0700576 float deltaZ = lightPoly[j].z - poly[i].z;
577 if (deltaZ == 0) {
ztenghui7b4516e2014-01-07 10:42:55 -0800578 return;
579 }
ztenghui50ecf842014-03-11 16:52:30 -0700580 float ratioZ = lightPoly[j].z / deltaZ;
581 float x = lightPoly[j].x - ratioZ * (lightPoly[j].x - poly[i].x);
582 float y = lightPoly[j].y - ratioZ * (lightPoly[j].y - poly[i].y);
ztenghui7b4516e2014-01-07 10:42:55 -0800583
584 Vector2 newPoint = Vector2(x, y);
585 shadowRegion[k] = newPoint;
586 outline[m] = newPoint;
587
588 k++;
589 m++;
590 }
591
592 // For the first light polygon's vertex, use the outline as the umbra.
593 // Later on, use the intersection of the outline and existing umbra.
594 if (umbraLength == 0) {
595 for (int i = 0; i < polyLength; i++) {
596 umbra[i] = outline[i];
597 }
598 umbraLength = polyLength;
599 } else {
600 int col = ((j * 255) / lightPolyLength);
601 umbraLength = intersection(outline, polyLength, umbra, umbraLength);
602 if (umbraLength == 0) {
603 break;
604 }
605 }
606 }
607
608 // Generate the penumbra area using the hull of all shadow regions.
609 int shadowRegionLength = k;
610 Vector2 penumbra[k];
611 int penumbraLength = hull(shadowRegion, shadowRegionLength, penumbra);
612
ztenghui5176c972014-01-31 17:17:55 -0800613 Vector2 fakeUmbra[polyLength];
ztenghui7b4516e2014-01-07 10:42:55 -0800614 if (umbraLength < 3) {
ztenghui5176c972014-01-31 17:17:55 -0800615 // If there is no real umbra, make a fake one.
ztenghui7b4516e2014-01-07 10:42:55 -0800616 for (int i = 0; i < polyLength; i++) {
ztenghui50ecf842014-03-11 16:52:30 -0700617 float deltaZ = lightCenter.z - poly[i].z;
618 if (deltaZ == 0) {
ztenghui7b4516e2014-01-07 10:42:55 -0800619 return;
620 }
ztenghui50ecf842014-03-11 16:52:30 -0700621 float ratioZ = lightCenter.z / deltaZ;
622 float x = lightCenter.x - ratioZ * (lightCenter.x - poly[i].x);
623 float y = lightCenter.y - ratioZ * (lightCenter.y - poly[i].y);
ztenghui7b4516e2014-01-07 10:42:55 -0800624
ztenghui5176c972014-01-31 17:17:55 -0800625 fakeUmbra[i].x = x;
626 fakeUmbra[i].y = y;
ztenghui7b4516e2014-01-07 10:42:55 -0800627 }
628
629 // Shrink the centroid's shadow by 10%.
630 // TODO: Study the magic number of 10%.
ztenghui63d41ab2014-02-14 13:13:41 -0800631 Vector2 shadowCentroid =
632 ShadowTessellator::centroid2d(fakeUmbra, polyLength);
ztenghui7b4516e2014-01-07 10:42:55 -0800633 for (int i = 0; i < polyLength; i++) {
ztenghui5176c972014-01-31 17:17:55 -0800634 fakeUmbra[i] = shadowCentroid * (1.0f - SHADOW_SHRINK_SCALE) +
635 fakeUmbra[i] * SHADOW_SHRINK_SCALE;
ztenghui7b4516e2014-01-07 10:42:55 -0800636 }
637#if DEBUG_SHADOW
638 ALOGD("No real umbra make a fake one, centroid2d = %f , %f",
639 shadowCentroid.x, shadowCentroid.y);
640#endif
641 // Set the fake umbra, whose size is the same as the original polygon.
ztenghui5176c972014-01-31 17:17:55 -0800642 umbra = fakeUmbra;
ztenghui7b4516e2014-01-07 10:42:55 -0800643 umbraLength = polyLength;
644 }
645
ztenghui50ecf842014-03-11 16:52:30 -0700646 generateTriangleStrip(isCasterOpaque, penumbra, penumbraLength, umbra,
647 umbraLength, poly, polyLength, shadowTriangleStrip);
ztenghui7b4516e2014-01-07 10:42:55 -0800648}
649
650/**
Chris Craik726118b2014-03-07 18:27:49 -0800651 * Converts a polygon specified with CW vertices into an array of distance-from-centroid values.
652 *
653 * Returns false in error conditions
654 *
655 * @param poly Array of vertices. Note that these *must* be CW.
656 * @param polyLength The number of vertices in the polygon.
657 * @param polyCentroid The centroid of the polygon, from which rays will be cast
658 * @param rayDist The output array for the calculated distances, must be SHADOW_RAY_COUNT in size
659 */
660bool convertPolyToRayDist(const Vector2* poly, int polyLength, const Vector2& polyCentroid,
661 float* rayDist) {
662 const int rays = SHADOW_RAY_COUNT;
663 const float step = M_PI * 2 / rays;
664
665 const Vector2* lastVertex = &(poly[polyLength - 1]);
666 float startAngle = angle(*lastVertex, polyCentroid);
667
668 // Start with the ray that's closest to and less than startAngle
669 int rayIndex = floor((startAngle - EPSILON) / step);
670 rayIndex = (rayIndex + rays) % rays; // ensure positive
671
672 for (int polyIndex = 0; polyIndex < polyLength; polyIndex++) {
673 /*
674 * For a given pair of vertices on the polygon, poly[i-1] and poly[i], the rays that
675 * intersect these will be those that are between the two angles from the centroid that the
676 * vertices define.
677 *
678 * Because the polygon vertices are stored clockwise, the closest ray with an angle
679 * *smaller* than that defined by angle(poly[i], centroid) will be the first ray that does
680 * not intersect with poly[i-1], poly[i].
681 */
682 float currentAngle = angle(poly[polyIndex], polyCentroid);
683
684 // find first ray that will not intersect the line segment poly[i-1] & poly[i]
685 int firstRayIndexOnNextSegment = floor((currentAngle - EPSILON) / step);
686 firstRayIndexOnNextSegment = (firstRayIndexOnNextSegment + rays) % rays; // ensure positive
687
688 // Iterate through all rays that intersect with poly[i-1], poly[i] line segment.
689 // This may be 0 rays.
690 while (rayIndex != firstRayIndexOnNextSegment) {
691 float distanceToIntersect = rayIntersectPoints(polyCentroid,
692 cos(rayIndex * step),
693 sin(rayIndex * step),
694 *lastVertex, poly[polyIndex]);
ztenghui50ecf842014-03-11 16:52:30 -0700695 if (distanceToIntersect < 0) {
696#if DEBUG_SHADOW
697 ALOGW("ERROR: convertPolyToRayDist failed");
698#endif
699 return false; // error case, abort
700 }
Chris Craik726118b2014-03-07 18:27:49 -0800701
702 rayDist[rayIndex] = distanceToIntersect;
703
704 rayIndex = (rayIndex - 1 + rays) % rays;
705 }
706 lastVertex = &poly[polyIndex];
707 }
708
709 return true;
710}
711
ztenghui50ecf842014-03-11 16:52:30 -0700712int SpotShadow::calculateOccludedUmbra(const Vector2* umbra, int umbraLength,
713 const Vector3* poly, int polyLength, Vector2* occludedUmbra) {
714 // Occluded umbra area is computed as the intersection of the projected 2D
715 // poly and umbra.
716 for (int i = 0; i < polyLength; i++) {
717 occludedUmbra[i].x = poly[i].x;
718 occludedUmbra[i].y = poly[i].y;
719 }
720
721 // Both umbra and incoming polygon are guaranteed to be CW, so we can call
722 // intersection() directly.
723 return intersection(umbra, umbraLength,
724 occludedUmbra, polyLength);
725}
726
727#define OCLLUDED_UMBRA_SHRINK_FACTOR 0.95f
Chris Craik726118b2014-03-07 18:27:49 -0800728/**
ztenghui7b4516e2014-01-07 10:42:55 -0800729 * Generate a triangle strip given two convex polygons
730 *
731 * @param penumbra The outer polygon x,y vertexes
732 * @param penumbraLength The number of vertexes in the outer polygon
733 * @param umbra The inner outer polygon x,y vertexes
734 * @param umbraLength The number of vertexes in the inner polygon
ztenghui7b4516e2014-01-07 10:42:55 -0800735 * @param shadowTriangleStrip return an (x,y,alpha) triangle strip representing the shadow. Return
736 * empty strip if error.
737**/
ztenghui50ecf842014-03-11 16:52:30 -0700738void SpotShadow::generateTriangleStrip(bool isCasterOpaque, const Vector2* penumbra,
739 int penumbraLength, const Vector2* umbra, int umbraLength,
740 const Vector3* poly, int polyLength, VertexBuffer& shadowTriangleStrip) {
ztenghui63d41ab2014-02-14 13:13:41 -0800741 const int rays = SHADOW_RAY_COUNT;
Chris Craik726118b2014-03-07 18:27:49 -0800742 const int size = 2 * rays;
743 const float step = M_PI * 2 / rays;
ztenghui7b4516e2014-01-07 10:42:55 -0800744 // Centroid of the umbra.
ztenghui63d41ab2014-02-14 13:13:41 -0800745 Vector2 centroid = ShadowTessellator::centroid2d(umbra, umbraLength);
ztenghui7b4516e2014-01-07 10:42:55 -0800746#if DEBUG_SHADOW
747 ALOGD("centroid2d = %f , %f", centroid.x, centroid.y);
748#endif
749 // Intersection to the penumbra.
750 float penumbraDistPerRay[rays];
751 // Intersection to the umbra.
752 float umbraDistPerRay[rays];
ztenghui50ecf842014-03-11 16:52:30 -0700753 // Intersection to the occluded umbra area.
754 float occludedUmbraDistPerRay[rays];
ztenghui7b4516e2014-01-07 10:42:55 -0800755
Chris Craik726118b2014-03-07 18:27:49 -0800756 // convert CW polygons to ray distance encoding, aborting on conversion failure
757 if (!convertPolyToRayDist(umbra, umbraLength, centroid, umbraDistPerRay)) return;
758 if (!convertPolyToRayDist(penumbra, penumbraLength, centroid, penumbraDistPerRay)) return;
ztenghui7b4516e2014-01-07 10:42:55 -0800759
ztenghui50ecf842014-03-11 16:52:30 -0700760 bool hasOccludedUmbraArea = false;
761 if (isCasterOpaque) {
762 Vector2 occludedUmbra[polyLength + umbraLength];
763 int occludedUmbraLength = calculateOccludedUmbra(umbra, umbraLength, poly, polyLength,
764 occludedUmbra);
765 // Make sure the centroid is inside the umbra, otherwise, fall back to the
766 // approach as if there is no occluded umbra area.
767 if (testPointInsidePolygon(centroid, occludedUmbra, occludedUmbraLength)) {
768 hasOccludedUmbraArea = true;
769 // Shrink the occluded umbra area to avoid pixel level artifacts.
770 for (int i = 0; i < occludedUmbraLength; i ++) {
771 occludedUmbra[i] = centroid + (occludedUmbra[i] - centroid) *
772 OCLLUDED_UMBRA_SHRINK_FACTOR;
773 }
774 if (!convertPolyToRayDist(occludedUmbra, occludedUmbraLength, centroid,
775 occludedUmbraDistPerRay)) {
776 return;
777 }
778 }
779 }
780
781 AlphaVertex* shadowVertices =
782 shadowTriangleStrip.alloc<AlphaVertex>(SHADOW_VERTEX_COUNT);
ztenghui7b4516e2014-01-07 10:42:55 -0800783
ztenghui63d41ab2014-02-14 13:13:41 -0800784 // Calculate the vertices (x, y, alpha) in the shadow area.
ztenghui50ecf842014-03-11 16:52:30 -0700785 AlphaVertex centroidXYA;
786 AlphaVertex::set(&centroidXYA, centroid.x, centroid.y, 1.0f);
Chris Craik726118b2014-03-07 18:27:49 -0800787 for (int rayIndex = 0; rayIndex < rays; rayIndex++) {
788 float dx = cosf(step * rayIndex);
789 float dy = sinf(step * rayIndex);
790
ztenghui50ecf842014-03-11 16:52:30 -0700791 // penumbra ring
792 float penumbraDistance = penumbraDistPerRay[rayIndex];
Chris Craik726118b2014-03-07 18:27:49 -0800793 AlphaVertex::set(&shadowVertices[rayIndex],
ztenghui50ecf842014-03-11 16:52:30 -0700794 dx * penumbraDistance + centroid.x,
795 dy * penumbraDistance + centroid.y, 0.0f);
Chris Craik726118b2014-03-07 18:27:49 -0800796
ztenghui50ecf842014-03-11 16:52:30 -0700797 // umbra ring
798 float umbraDistance = umbraDistPerRay[rayIndex];
Chris Craik726118b2014-03-07 18:27:49 -0800799 AlphaVertex::set(&shadowVertices[rays + rayIndex],
ztenghui50ecf842014-03-11 16:52:30 -0700800 dx * umbraDistance + centroid.x, dy * umbraDistance + centroid.y, 1.0f);
801
802 // occluded umbra ring
803 if (hasOccludedUmbraArea) {
804 float occludedUmbraDistance = occludedUmbraDistPerRay[rayIndex];
805 AlphaVertex::set(&shadowVertices[2 * rays + rayIndex],
806 dx * occludedUmbraDistance + centroid.x,
807 dy * occludedUmbraDistance + centroid.y, 1.0f);
808 } else {
809 // Put all vertices of the occluded umbra ring at the centroid.
810 shadowVertices[2 * rays + rayIndex] = centroidXYA;
811 }
ztenghui7b4516e2014-01-07 10:42:55 -0800812 }
ztenghui7b4516e2014-01-07 10:42:55 -0800813}
814
815/**
816 * This is only for experimental purpose.
817 * After intersections are calculated, we could smooth the polygon if needed.
818 * So far, we don't think it is more appealing yet.
819 *
820 * @param level The level of smoothness.
821 * @param rays The total number of rays.
822 * @param rayDist (In and Out) The distance for each ray.
823 *
824 */
825void SpotShadow::smoothPolygon(int level, int rays, float* rayDist) {
826 for (int k = 0; k < level; k++) {
827 for (int i = 0; i < rays; i++) {
828 float p1 = rayDist[(rays - 1 + i) % rays];
829 float p2 = rayDist[i];
830 float p3 = rayDist[(i + 1) % rays];
831 rayDist[i] = (p1 + p2 * 2 + p3) / 4;
832 }
833 }
834}
835
ztenghuif5ca8b42014-01-27 15:53:28 -0800836#if DEBUG_SHADOW
837
838#define TEST_POINT_NUMBER 128
839
840/**
841 * Calculate the bounds for generating random test points.
842 */
843void SpotShadow::updateBound(const Vector2 inVector, Vector2& lowerBound,
844 Vector2& upperBound ) {
845 if (inVector.x < lowerBound.x) {
846 lowerBound.x = inVector.x;
847 }
848
849 if (inVector.y < lowerBound.y) {
850 lowerBound.y = inVector.y;
851 }
852
853 if (inVector.x > upperBound.x) {
854 upperBound.x = inVector.x;
855 }
856
857 if (inVector.y > upperBound.y) {
858 upperBound.y = inVector.y;
859 }
860}
861
862/**
863 * For debug purpose, when things go wrong, dump the whole polygon data.
864 */
865static void dumpPolygon(const Vector2* poly, int polyLength, const char* polyName) {
866 for (int i = 0; i < polyLength; i++) {
867 ALOGD("polygon %s i %d x %f y %f", polyName, i, poly[i].x, poly[i].y);
868 }
869}
870
871/**
872 * Test whether the polygon is convex.
873 */
874bool SpotShadow::testConvex(const Vector2* polygon, int polygonLength,
875 const char* name) {
876 bool isConvex = true;
877 for (int i = 0; i < polygonLength; i++) {
878 Vector2 start = polygon[i];
879 Vector2 middle = polygon[(i + 1) % polygonLength];
880 Vector2 end = polygon[(i + 2) % polygonLength];
881
882 double delta = (double(middle.x) - start.x) * (double(end.y) - start.y) -
883 (double(middle.y) - start.y) * (double(end.x) - start.x);
884 bool isCCWOrCoLinear = (delta >= EPSILON);
885
886 if (isCCWOrCoLinear) {
ztenghui50ecf842014-03-11 16:52:30 -0700887 ALOGW("(Error Type 2): polygon (%s) is not a convex b/c start (x %f, y %f),"
ztenghuif5ca8b42014-01-27 15:53:28 -0800888 "middle (x %f, y %f) and end (x %f, y %f) , delta is %f !!!",
889 name, start.x, start.y, middle.x, middle.y, end.x, end.y, delta);
890 isConvex = false;
891 break;
892 }
893 }
894 return isConvex;
895}
896
897/**
898 * Test whether or not the polygon (intersection) is within the 2 input polygons.
899 * Using Marte Carlo method, we generate a random point, and if it is inside the
900 * intersection, then it must be inside both source polygons.
901 */
902void SpotShadow::testIntersection(const Vector2* poly1, int poly1Length,
903 const Vector2* poly2, int poly2Length,
904 const Vector2* intersection, int intersectionLength) {
905 // Find the min and max of x and y.
906 Vector2 lowerBound(FLT_MAX, FLT_MAX);
907 Vector2 upperBound(-FLT_MAX, -FLT_MAX);
908 for (int i = 0; i < poly1Length; i++) {
909 updateBound(poly1[i], lowerBound, upperBound);
910 }
911 for (int i = 0; i < poly2Length; i++) {
912 updateBound(poly2[i], lowerBound, upperBound);
913 }
914
915 bool dumpPoly = false;
916 for (int k = 0; k < TEST_POINT_NUMBER; k++) {
917 // Generate a random point between minX, minY and maxX, maxY.
918 double randomX = rand() / double(RAND_MAX);
919 double randomY = rand() / double(RAND_MAX);
920
921 Vector2 testPoint;
922 testPoint.x = lowerBound.x + randomX * (upperBound.x - lowerBound.x);
923 testPoint.y = lowerBound.y + randomY * (upperBound.y - lowerBound.y);
924
925 // If the random point is in both poly 1 and 2, then it must be intersection.
926 if (testPointInsidePolygon(testPoint, intersection, intersectionLength)) {
927 if (!testPointInsidePolygon(testPoint, poly1, poly1Length)) {
928 dumpPoly = true;
ztenghui50ecf842014-03-11 16:52:30 -0700929 ALOGW("(Error Type 1): one point (%f, %f) in the intersection is"
ztenghuif5ca8b42014-01-27 15:53:28 -0800930 " not in the poly1",
931 testPoint.x, testPoint.y);
932 }
933
934 if (!testPointInsidePolygon(testPoint, poly2, poly2Length)) {
935 dumpPoly = true;
ztenghui50ecf842014-03-11 16:52:30 -0700936 ALOGW("(Error Type 1): one point (%f, %f) in the intersection is"
ztenghuif5ca8b42014-01-27 15:53:28 -0800937 " not in the poly2",
938 testPoint.x, testPoint.y);
939 }
940 }
941 }
942
943 if (dumpPoly) {
944 dumpPolygon(intersection, intersectionLength, "intersection");
945 for (int i = 1; i < intersectionLength; i++) {
946 Vector2 delta = intersection[i] - intersection[i - 1];
947 ALOGD("Intersetion i, %d Vs i-1 is delta %f", i, delta.lengthSquared());
948 }
949
950 dumpPolygon(poly1, poly1Length, "poly 1");
951 dumpPolygon(poly2, poly2Length, "poly 2");
952 }
953}
954#endif
955
ztenghui7b4516e2014-01-07 10:42:55 -0800956}; // namespace uirenderer
957}; // namespace android