SpotShadow.cpp revision 3bd3fa1f1d437e22aee35381a559dcee15a437dd
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#define CASTER_Z_CAP_RATIO 0.95f 21#define FAKE_UMBRA_SIZE_RATIO 0.01f 22#define OCLLUDED_UMBRA_SHRINK_FACTOR 0.95f 23 24#include <math.h> 25#include <stdlib.h> 26#include <utils/Log.h> 27 28#include "ShadowTessellator.h" 29#include "SpotShadow.h" 30#include "Vertex.h" 31#include "utils/MathUtils.h" 32 33// TODO: After we settle down the new algorithm, we can remove the old one and 34// its utility functions. 35// Right now, we still need to keep it for comparison purpose and future expansion. 36namespace android { 37namespace uirenderer { 38 39static const double EPSILON = 1e-7; 40 41/** 42 * For each polygon's vertex, the light center will project it to the receiver 43 * as one of the outline vertex. 44 * For each outline vertex, we need to store the position and normal. 45 * Normal here is defined against the edge by the current vertex and the next vertex. 46 */ 47struct OutlineData { 48 Vector2 position; 49 Vector2 normal; 50 float radius; 51}; 52 53/** 54 * Calculate the angle between and x and a y coordinate. 55 * The atan2 range from -PI to PI. 56 */ 57static float angle(const Vector2& point, const Vector2& center) { 58 return atan2(point.y - center.y, point.x - center.x); 59} 60 61/** 62 * Calculate the intersection of a ray with the line segment defined by two points. 63 * 64 * Returns a negative value in error conditions. 65 66 * @param rayOrigin The start of the ray 67 * @param dx The x vector of the ray 68 * @param dy The y vector of the ray 69 * @param p1 The first point defining the line segment 70 * @param p2 The second point defining the line segment 71 * @return The distance along the ray if it intersects with the line segment, negative if otherwise 72 */ 73static float rayIntersectPoints(const Vector2& rayOrigin, float dx, float dy, 74 const Vector2& p1, const Vector2& p2) { 75 // The math below is derived from solving this formula, basically the 76 // intersection point should stay on both the ray and the edge of (p1, p2). 77 // solve([p1x+t*(p2x-p1x)=dx*t2+px,p1y+t*(p2y-p1y)=dy*t2+py],[t,t2]); 78 79 double divisor = (dx * (p1.y - p2.y) + dy * p2.x - dy * p1.x); 80 if (divisor == 0) return -1.0f; // error, invalid divisor 81 82#if DEBUG_SHADOW 83 double interpVal = (dx * (p1.y - rayOrigin.y) + dy * rayOrigin.x - dy * p1.x) / divisor; 84 if (interpVal < 0 || interpVal > 1) { 85 ALOGW("rayIntersectPoints is hitting outside the segment %f", interpVal); 86 } 87#endif 88 89 double distance = (p1.x * (rayOrigin.y - p2.y) + p2.x * (p1.y - rayOrigin.y) + 90 rayOrigin.x * (p2.y - p1.y)) / divisor; 91 92 return distance; // may be negative in error cases 93} 94 95/** 96 * Sort points by their X coordinates 97 * 98 * @param points the points as a Vector2 array. 99 * @param pointsLength the number of vertices of the polygon. 100 */ 101void SpotShadow::xsort(Vector2* points, int pointsLength) { 102 quicksortX(points, 0, pointsLength - 1); 103} 104 105/** 106 * compute the convex hull of a collection of Points 107 * 108 * @param points the points as a Vector2 array. 109 * @param pointsLength the number of vertices of the polygon. 110 * @param retPoly pre allocated array of floats to put the vertices 111 * @return the number of points in the polygon 0 if no intersection 112 */ 113int SpotShadow::hull(Vector2* points, int pointsLength, Vector2* retPoly) { 114 xsort(points, pointsLength); 115 int n = pointsLength; 116 Vector2 lUpper[n]; 117 lUpper[0] = points[0]; 118 lUpper[1] = points[1]; 119 120 int lUpperSize = 2; 121 122 for (int i = 2; i < n; i++) { 123 lUpper[lUpperSize] = points[i]; 124 lUpperSize++; 125 126 while (lUpperSize > 2 && !ccw( 127 lUpper[lUpperSize - 3].x, lUpper[lUpperSize - 3].y, 128 lUpper[lUpperSize - 2].x, lUpper[lUpperSize - 2].y, 129 lUpper[lUpperSize - 1].x, lUpper[lUpperSize - 1].y)) { 130 // Remove the middle point of the three last 131 lUpper[lUpperSize - 2].x = lUpper[lUpperSize - 1].x; 132 lUpper[lUpperSize - 2].y = lUpper[lUpperSize - 1].y; 133 lUpperSize--; 134 } 135 } 136 137 Vector2 lLower[n]; 138 lLower[0] = points[n - 1]; 139 lLower[1] = points[n - 2]; 140 141 int lLowerSize = 2; 142 143 for (int i = n - 3; i >= 0; i--) { 144 lLower[lLowerSize] = points[i]; 145 lLowerSize++; 146 147 while (lLowerSize > 2 && !ccw( 148 lLower[lLowerSize - 3].x, lLower[lLowerSize - 3].y, 149 lLower[lLowerSize - 2].x, lLower[lLowerSize - 2].y, 150 lLower[lLowerSize - 1].x, lLower[lLowerSize - 1].y)) { 151 // Remove the middle point of the three last 152 lLower[lLowerSize - 2] = lLower[lLowerSize - 1]; 153 lLowerSize--; 154 } 155 } 156 157 // output points in CW ordering 158 const int total = lUpperSize + lLowerSize - 2; 159 int outIndex = total - 1; 160 for (int i = 0; i < lUpperSize; i++) { 161 retPoly[outIndex] = lUpper[i]; 162 outIndex--; 163 } 164 165 for (int i = 1; i < lLowerSize - 1; i++) { 166 retPoly[outIndex] = lLower[i]; 167 outIndex--; 168 } 169 // TODO: Add test harness which verify that all the points are inside the hull. 170 return total; 171} 172 173/** 174 * Test whether the 3 points form a counter clockwise turn. 175 * 176 * @return true if a right hand turn 177 */ 178bool SpotShadow::ccw(double ax, double ay, double bx, double by, 179 double cx, double cy) { 180 return (bx - ax) * (cy - ay) - (by - ay) * (cx - ax) > EPSILON; 181} 182 183/** 184 * Calculates the intersection of poly1 with poly2 and put in poly2. 185 * Note that both poly1 and poly2 must be in CW order already! 186 * 187 * @param poly1 The 1st polygon, as a Vector2 array. 188 * @param poly1Length The number of vertices of 1st polygon. 189 * @param poly2 The 2nd and output polygon, as a Vector2 array. 190 * @param poly2Length The number of vertices of 2nd polygon. 191 * @return number of vertices in output polygon as poly2. 192 */ 193int SpotShadow::intersection(const Vector2* poly1, int poly1Length, 194 Vector2* poly2, int poly2Length) { 195#if DEBUG_SHADOW 196 if (!ShadowTessellator::isClockwise(poly1, poly1Length)) { 197 ALOGW("Poly1 is not clockwise! Intersection is wrong!"); 198 } 199 if (!ShadowTessellator::isClockwise(poly2, poly2Length)) { 200 ALOGW("Poly2 is not clockwise! Intersection is wrong!"); 201 } 202#endif 203 Vector2 poly[poly1Length * poly2Length + 2]; 204 int count = 0; 205 int pcount = 0; 206 207 // If one vertex from one polygon sits inside another polygon, add it and 208 // count them. 209 for (int i = 0; i < poly1Length; i++) { 210 if (testPointInsidePolygon(poly1[i], poly2, poly2Length)) { 211 poly[count] = poly1[i]; 212 count++; 213 pcount++; 214 215 } 216 } 217 218 int insidePoly2 = pcount; 219 for (int i = 0; i < poly2Length; i++) { 220 if (testPointInsidePolygon(poly2[i], poly1, poly1Length)) { 221 poly[count] = poly2[i]; 222 count++; 223 } 224 } 225 226 int insidePoly1 = count - insidePoly2; 227 // If all vertices from poly1 are inside poly2, then just return poly1. 228 if (insidePoly2 == poly1Length) { 229 memcpy(poly2, poly1, poly1Length * sizeof(Vector2)); 230 return poly1Length; 231 } 232 233 // If all vertices from poly2 are inside poly1, then just return poly2. 234 if (insidePoly1 == poly2Length) { 235 return poly2Length; 236 } 237 238 // Since neither polygon fully contain the other one, we need to add all the 239 // intersection points. 240 Vector2 intersection = {0, 0}; 241 for (int i = 0; i < poly2Length; i++) { 242 for (int j = 0; j < poly1Length; j++) { 243 int poly2LineStart = i; 244 int poly2LineEnd = ((i + 1) % poly2Length); 245 int poly1LineStart = j; 246 int poly1LineEnd = ((j + 1) % poly1Length); 247 bool found = lineIntersection( 248 poly2[poly2LineStart].x, poly2[poly2LineStart].y, 249 poly2[poly2LineEnd].x, poly2[poly2LineEnd].y, 250 poly1[poly1LineStart].x, poly1[poly1LineStart].y, 251 poly1[poly1LineEnd].x, poly1[poly1LineEnd].y, 252 intersection); 253 if (found) { 254 poly[count].x = intersection.x; 255 poly[count].y = intersection.y; 256 count++; 257 } else { 258 Vector2 delta = poly2[i] - poly1[j]; 259 if (delta.lengthSquared() < EPSILON) { 260 poly[count] = poly2[i]; 261 count++; 262 } 263 } 264 } 265 } 266 267 if (count == 0) { 268 return 0; 269 } 270 271 // Sort the result polygon around the center. 272 Vector2 center = {0.0f, 0.0f}; 273 for (int i = 0; i < count; i++) { 274 center += poly[i]; 275 } 276 center /= count; 277 sort(poly, count, center); 278 279#if DEBUG_SHADOW 280 // Since poly2 is overwritten as the result, we need to save a copy to do 281 // our verification. 282 Vector2 oldPoly2[poly2Length]; 283 int oldPoly2Length = poly2Length; 284 memcpy(oldPoly2, poly2, sizeof(Vector2) * poly2Length); 285#endif 286 287 // Filter the result out from poly and put it into poly2. 288 poly2[0] = poly[0]; 289 int lastOutputIndex = 0; 290 for (int i = 1; i < count; i++) { 291 Vector2 delta = poly[i] - poly2[lastOutputIndex]; 292 if (delta.lengthSquared() >= EPSILON) { 293 poly2[++lastOutputIndex] = poly[i]; 294 } else { 295 // If the vertices are too close, pick the inner one, because the 296 // inner one is more likely to be an intersection point. 297 Vector2 delta1 = poly[i] - center; 298 Vector2 delta2 = poly2[lastOutputIndex] - center; 299 if (delta1.lengthSquared() < delta2.lengthSquared()) { 300 poly2[lastOutputIndex] = poly[i]; 301 } 302 } 303 } 304 int resultLength = lastOutputIndex + 1; 305 306#if DEBUG_SHADOW 307 testConvex(poly2, resultLength, "intersection"); 308 testConvex(poly1, poly1Length, "input poly1"); 309 testConvex(oldPoly2, oldPoly2Length, "input poly2"); 310 311 testIntersection(poly1, poly1Length, oldPoly2, oldPoly2Length, poly2, resultLength); 312#endif 313 314 return resultLength; 315} 316 317/** 318 * Sort points about a center point 319 * 320 * @param poly The in and out polyogon as a Vector2 array. 321 * @param polyLength The number of vertices of the polygon. 322 * @param center the center ctr[0] = x , ctr[1] = y to sort around. 323 */ 324void SpotShadow::sort(Vector2* poly, int polyLength, const Vector2& center) { 325 quicksortCirc(poly, 0, polyLength - 1, center); 326} 327 328/** 329 * Swap points pointed to by i and j 330 */ 331void SpotShadow::swap(Vector2* points, int i, int j) { 332 Vector2 temp = points[i]; 333 points[i] = points[j]; 334 points[j] = temp; 335} 336 337/** 338 * quick sort implementation about the center. 339 */ 340void SpotShadow::quicksortCirc(Vector2* points, int low, int high, 341 const Vector2& center) { 342 int i = low, j = high; 343 int p = low + (high - low) / 2; 344 float pivot = angle(points[p], center); 345 while (i <= j) { 346 while (angle(points[i], center) > pivot) { 347 i++; 348 } 349 while (angle(points[j], center) < pivot) { 350 j--; 351 } 352 353 if (i <= j) { 354 swap(points, i, j); 355 i++; 356 j--; 357 } 358 } 359 if (low < j) quicksortCirc(points, low, j, center); 360 if (i < high) quicksortCirc(points, i, high, center); 361} 362 363/** 364 * Sort points by x axis 365 * 366 * @param points points to sort 367 * @param low start index 368 * @param high end index 369 */ 370void SpotShadow::quicksortX(Vector2* points, int low, int high) { 371 int i = low, j = high; 372 int p = low + (high - low) / 2; 373 float pivot = points[p].x; 374 while (i <= j) { 375 while (points[i].x < pivot) { 376 i++; 377 } 378 while (points[j].x > pivot) { 379 j--; 380 } 381 382 if (i <= j) { 383 swap(points, i, j); 384 i++; 385 j--; 386 } 387 } 388 if (low < j) quicksortX(points, low, j); 389 if (i < high) quicksortX(points, i, high); 390} 391 392/** 393 * Test whether a point is inside the polygon. 394 * 395 * @param testPoint the point to test 396 * @param poly the polygon 397 * @return true if the testPoint is inside the poly. 398 */ 399bool SpotShadow::testPointInsidePolygon(const Vector2 testPoint, 400 const Vector2* poly, int len) { 401 bool c = false; 402 double testx = testPoint.x; 403 double testy = testPoint.y; 404 for (int i = 0, j = len - 1; i < len; j = i++) { 405 double startX = poly[j].x; 406 double startY = poly[j].y; 407 double endX = poly[i].x; 408 double endY = poly[i].y; 409 410 if (((endY > testy) != (startY > testy)) && 411 (testx < (startX - endX) * (testy - endY) 412 / (startY - endY) + endX)) { 413 c = !c; 414 } 415 } 416 return c; 417} 418 419/** 420 * Make the polygon turn clockwise. 421 * 422 * @param polygon the polygon as a Vector2 array. 423 * @param len the number of points of the polygon 424 */ 425void SpotShadow::makeClockwise(Vector2* polygon, int len) { 426 if (polygon == 0 || len == 0) { 427 return; 428 } 429 if (!ShadowTessellator::isClockwise(polygon, len)) { 430 reverse(polygon, len); 431 } 432} 433 434/** 435 * Reverse the polygon 436 * 437 * @param polygon the polygon as a Vector2 array 438 * @param len the number of points of the polygon 439 */ 440void SpotShadow::reverse(Vector2* polygon, int len) { 441 int n = len / 2; 442 for (int i = 0; i < n; i++) { 443 Vector2 tmp = polygon[i]; 444 int k = len - 1 - i; 445 polygon[i] = polygon[k]; 446 polygon[k] = tmp; 447 } 448} 449 450/** 451 * Intersects two lines in parametric form. This function is called in a tight 452 * loop, and we need double precision to get things right. 453 * 454 * @param x1 the x coordinate point 1 of line 1 455 * @param y1 the y coordinate point 1 of line 1 456 * @param x2 the x coordinate point 2 of line 1 457 * @param y2 the y coordinate point 2 of line 1 458 * @param x3 the x coordinate point 1 of line 2 459 * @param y3 the y coordinate point 1 of line 2 460 * @param x4 the x coordinate point 2 of line 2 461 * @param y4 the y coordinate point 2 of line 2 462 * @param ret the x,y location of the intersection 463 * @return true if it found an intersection 464 */ 465inline bool SpotShadow::lineIntersection(double x1, double y1, double x2, double y2, 466 double x3, double y3, double x4, double y4, Vector2& ret) { 467 double d = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4); 468 if (d == 0.0) return false; 469 470 double dx = (x1 * y2 - y1 * x2); 471 double dy = (x3 * y4 - y3 * x4); 472 double x = (dx * (x3 - x4) - (x1 - x2) * dy) / d; 473 double y = (dx * (y3 - y4) - (y1 - y2) * dy) / d; 474 475 // The intersection should be in the middle of the point 1 and point 2, 476 // likewise point 3 and point 4. 477 if (((x - x1) * (x - x2) > EPSILON) 478 || ((x - x3) * (x - x4) > EPSILON) 479 || ((y - y1) * (y - y2) > EPSILON) 480 || ((y - y3) * (y - y4) > EPSILON)) { 481 // Not interesected 482 return false; 483 } 484 ret.x = x; 485 ret.y = y; 486 return true; 487 488} 489 490/** 491 * Compute a horizontal circular polygon about point (x , y , height) of radius 492 * (size) 493 * 494 * @param points number of the points of the output polygon. 495 * @param lightCenter the center of the light. 496 * @param size the light size. 497 * @param ret result polygon. 498 */ 499void SpotShadow::computeLightPolygon(int points, const Vector3& lightCenter, 500 float size, Vector3* ret) { 501 // TODO: Caching all the sin / cos values and store them in a look up table. 502 for (int i = 0; i < points; i++) { 503 double angle = 2 * i * M_PI / points; 504 ret[i].x = cosf(angle) * size + lightCenter.x; 505 ret[i].y = sinf(angle) * size + lightCenter.y; 506 ret[i].z = lightCenter.z; 507 } 508} 509 510/** 511* Generate the shadow from a spot light. 512* 513* @param poly x,y,z vertexes of a convex polygon that occludes the light source 514* @param polyLength number of vertexes of the occluding polygon 515* @param lightCenter the center of the light 516* @param lightSize the radius of the light source 517* @param lightVertexCount the vertex counter for the light polygon 518* @param shadowTriangleStrip return an (x,y,alpha) triangle strip representing the shadow. Return 519* empty strip if error. 520* 521*/ 522 523void SpotShadow::createSpotShadow_old(bool isCasterOpaque, const Vector3* poly, 524 int polyLength, const Vector3& lightCenter, float lightSize, 525 int lightVertexCount, VertexBuffer& retStrips) { 526 Vector3 light[lightVertexCount * 3]; 527 computeLightPolygon(lightVertexCount, lightCenter, lightSize, light); 528 computeSpotShadow_old(isCasterOpaque, light, lightVertexCount, lightCenter, poly, 529 polyLength, retStrips); 530} 531 532/** 533 * Generate the shadow spot light of shape lightPoly and a object poly 534 * 535 * @param lightPoly x,y,z vertex of a convex polygon that is the light source 536 * @param lightPolyLength number of vertexes of the light source polygon 537 * @param poly x,y,z vertexes of a convex polygon that occludes the light source 538 * @param polyLength number of vertexes of the occluding polygon 539 * @param shadowTriangleStrip return an (x,y,alpha) triangle strip representing the shadow. Return 540 * empty strip if error. 541 */ 542void SpotShadow::computeSpotShadow_old(bool isCasterOpaque, const Vector3* lightPoly, 543 int lightPolyLength, const Vector3& lightCenter, const Vector3* poly, int polyLength, 544 VertexBuffer& shadowTriangleStrip) { 545 // Point clouds for all the shadowed vertices 546 Vector2 shadowRegion[lightPolyLength * polyLength]; 547 // Shadow polygon from one point light. 548 Vector2 outline[polyLength]; 549 Vector2 umbraMem[polyLength * lightPolyLength]; 550 Vector2* umbra = umbraMem; 551 552 int umbraLength = 0; 553 554 // Validate input, receiver is always at z = 0 plane. 555 bool inputPolyPositionValid = true; 556 for (int i = 0; i < polyLength; i++) { 557 if (poly[i].z >= lightPoly[0].z) { 558 inputPolyPositionValid = false; 559 ALOGW("polygon above the light"); 560 break; 561 } 562 } 563 564 // If the caster's position is invalid, don't draw anything. 565 if (!inputPolyPositionValid) { 566 return; 567 } 568 569 // Calculate the umbra polygon based on intersections of all outlines 570 int k = 0; 571 for (int j = 0; j < lightPolyLength; j++) { 572 int m = 0; 573 for (int i = 0; i < polyLength; i++) { 574 // After validating the input, deltaZ is guaranteed to be positive. 575 float deltaZ = lightPoly[j].z - poly[i].z; 576 float ratioZ = lightPoly[j].z / deltaZ; 577 float x = lightPoly[j].x - ratioZ * (lightPoly[j].x - poly[i].x); 578 float y = lightPoly[j].y - ratioZ * (lightPoly[j].y - poly[i].y); 579 580 Vector2 newPoint = {x, y}; 581 shadowRegion[k] = newPoint; 582 outline[m] = newPoint; 583 584 k++; 585 m++; 586 } 587 588 // For the first light polygon's vertex, use the outline as the umbra. 589 // Later on, use the intersection of the outline and existing umbra. 590 if (umbraLength == 0) { 591 for (int i = 0; i < polyLength; i++) { 592 umbra[i] = outline[i]; 593 } 594 umbraLength = polyLength; 595 } else { 596 int col = ((j * 255) / lightPolyLength); 597 umbraLength = intersection(outline, polyLength, umbra, umbraLength); 598 if (umbraLength == 0) { 599 break; 600 } 601 } 602 } 603 604 // Generate the penumbra area using the hull of all shadow regions. 605 int shadowRegionLength = k; 606 Vector2 penumbra[k]; 607 int penumbraLength = hull(shadowRegion, shadowRegionLength, penumbra); 608 609 Vector2 fakeUmbra[polyLength]; 610 if (umbraLength < 3) { 611 // If there is no real umbra, make a fake one. 612 for (int i = 0; i < polyLength; i++) { 613 float deltaZ = lightCenter.z - poly[i].z; 614 float ratioZ = lightCenter.z / deltaZ; 615 float x = lightCenter.x - ratioZ * (lightCenter.x - poly[i].x); 616 float y = lightCenter.y - ratioZ * (lightCenter.y - poly[i].y); 617 618 fakeUmbra[i].x = x; 619 fakeUmbra[i].y = y; 620 } 621 622 // Shrink the centroid's shadow by 10%. 623 // TODO: Study the magic number of 10%. 624 Vector2 shadowCentroid = 625 ShadowTessellator::centroid2d(fakeUmbra, polyLength); 626 for (int i = 0; i < polyLength; i++) { 627 fakeUmbra[i] = shadowCentroid * (1.0f - SHADOW_SHRINK_SCALE) + 628 fakeUmbra[i] * SHADOW_SHRINK_SCALE; 629 } 630#if DEBUG_SHADOW 631 ALOGD("No real umbra make a fake one, centroid2d = %f , %f", 632 shadowCentroid.x, shadowCentroid.y); 633#endif 634 // Set the fake umbra, whose size is the same as the original polygon. 635 umbra = fakeUmbra; 636 umbraLength = polyLength; 637 } 638 639 generateTriangleStrip(isCasterOpaque, 1.0, penumbra, penumbraLength, umbra, 640 umbraLength, poly, polyLength, shadowTriangleStrip); 641} 642 643float SpotShadow::projectCasterToOutline(Vector2& outline, 644 const Vector3& lightCenter, const Vector3& polyVertex) { 645 float lightToPolyZ = lightCenter.z - polyVertex.z; 646 float ratioZ = CASTER_Z_CAP_RATIO; 647 if (lightToPolyZ != 0) { 648 // If any caster's vertex is almost above the light, we just keep it as 95% 649 // of the height of the light. 650 ratioZ = MathUtils::clamp(polyVertex.z / lightToPolyZ, 0.0f, CASTER_Z_CAP_RATIO); 651 } 652 653 outline.x = polyVertex.x - ratioZ * (lightCenter.x - polyVertex.x); 654 outline.y = polyVertex.y - ratioZ * (lightCenter.y - polyVertex.y); 655 return ratioZ; 656} 657 658/** 659 * Generate the shadow spot light of shape lightPoly and a object poly 660 * 661 * @param isCasterOpaque whether the caster is opaque 662 * @param lightCenter the center of the light 663 * @param lightSize the radius of the light 664 * @param poly x,y,z vertexes of a convex polygon that occludes the light source 665 * @param polyLength number of vertexes of the occluding polygon 666 * @param shadowTriangleStrip return an (x,y,alpha) triangle strip representing the shadow. Return 667 * empty strip if error. 668 */ 669void SpotShadow::createSpotShadow(bool isCasterOpaque, const Vector3& lightCenter, 670 float lightSize, const Vector3* poly, int polyLength, const Vector3& polyCentroid, 671 VertexBuffer& shadowTriangleStrip) { 672 if (CC_UNLIKELY(lightCenter.z <= 0)) { 673 ALOGW("Relative Light Z is not positive. No spot shadow!"); 674 return; 675 } 676 OutlineData outlineData[polyLength]; 677 Vector2 outlineCentroid; 678 // Calculate the projected outline for each polygon's vertices from the light center. 679 // 680 // O Light 681 // / 682 // / 683 // . Polygon vertex 684 // / 685 // / 686 // O Outline vertices 687 // 688 // Ratio = (Poly - Outline) / (Light - Poly) 689 // Outline.x = Poly.x - Ratio * (Light.x - Poly.x) 690 // Outline's radius / Light's radius = Ratio 691 692 // Compute the last outline vertex to make sure we can get the normal and outline 693 // in one single loop. 694 projectCasterToOutline(outlineData[polyLength - 1].position, lightCenter, 695 poly[polyLength - 1]); 696 697 // Take the outline's polygon, calculate the normal for each outline edge. 698 int currentNormalIndex = polyLength - 1; 699 int nextNormalIndex = 0; 700 701 for (int i = 0; i < polyLength; i++) { 702 float ratioZ = projectCasterToOutline(outlineData[i].position, 703 lightCenter, poly[i]); 704 outlineData[i].radius = ratioZ * lightSize; 705 706 outlineData[currentNormalIndex].normal = ShadowTessellator::calculateNormal( 707 outlineData[currentNormalIndex].position, 708 outlineData[nextNormalIndex].position); 709 currentNormalIndex = (currentNormalIndex + 1) % polyLength; 710 nextNormalIndex++; 711 } 712 713 projectCasterToOutline(outlineCentroid, lightCenter, polyCentroid); 714 715 int penumbraIndex = 0; 716 int penumbraLength = polyLength * 3; 717 Vector2 penumbra[penumbraLength]; 718 719 Vector2 umbra[polyLength]; 720 float distOutline = 0; 721 float ratioVI = 0; 722 723 bool hasValidUmbra = true; 724 // We need the maxRatioVI to decrease the spot shadow strength accordingly. 725 float maxRaitoVI = 1.0; 726 727 for (int i = 0; i < polyLength; i++) { 728 // Generate all the penumbra's vertices only using the (outline vertex + normal * radius) 729 // There is no guarantee that the penumbra is still convex, but for 730 // each outline vertex, it will connect to all its corresponding penumbra vertices as 731 // triangle fans. And for neighber penumbra vertex, it will be a trapezoid. 732 // 733 // Penumbra Vertices marked as Pi 734 // Outline Vertices marked as Vi 735 // (P3) 736 // (P2) | ' (P4) 737 // (P1)' | | ' 738 // ' | | ' 739 // (P0) ------------------------------------------------(P5) 740 // | (V0) |(V1) 741 // | | 742 // | | 743 // | | 744 // | | 745 // | | 746 // | | 747 // | | 748 // | | 749 // (V3)-----------------------------------(V2) 750 int preNormalIndex = (i + polyLength - 1) % polyLength; 751 penumbra[penumbraIndex++] = outlineData[i].position + 752 outlineData[preNormalIndex].normal * outlineData[i].radius; 753 754 int currentNormalIndex = i; 755 // (TODO) Depending on how roundness we want for each corner, we can subdivide 756 // further here and/or introduce some heuristic to decide how much the 757 // subdivision should be. 758 Vector2 avgNormal = 759 (outlineData[preNormalIndex].normal + outlineData[currentNormalIndex].normal) / 2; 760 761 penumbra[penumbraIndex++] = outlineData[i].position + 762 avgNormal * outlineData[i].radius; 763 764 penumbra[penumbraIndex++] = outlineData[i].position + 765 outlineData[currentNormalIndex].normal * outlineData[i].radius; 766 767 // Compute the umbra by the intersection from the outline's centroid! 768 // 769 // (V) ------------------------------------ 770 // | ' | 771 // | ' | 772 // | ' (I) | 773 // | ' | 774 // | ' (C) | 775 // | | 776 // | | 777 // | | 778 // | | 779 // ------------------------------------ 780 // 781 // Connect a line b/t the outline vertex (V) and the centroid (C), it will 782 // intersect with the outline vertex's circle at point (I). 783 // Now, ratioVI = VI / VC, ratioIC = IC / VC 784 // Then the intersetion point can be computed as Ixy = Vxy * ratioIC + Cxy * ratioVI; 785 // 786 // When one of the outline circle cover the the outline centroid, (like I is 787 // on the other side of C), there is no real umbra any more, so we just fake 788 // a small area around the centroid as the umbra, and tune down the spot 789 // shadow's umbra strength to simulate the effect the whole shadow will 790 // become lighter in this case. 791 // The ratio can be simulated by using the inverse of maximum of ratioVI for 792 // all (V). 793 distOutline = (outlineData[i].position - outlineCentroid).length(); 794 if (CC_UNLIKELY(distOutline == 0)) { 795 // If the outline has 0 area, then there is no spot shadow anyway. 796 ALOGW("Outline has 0 area, no spot shadow!"); 797 return; 798 } 799 ratioVI = outlineData[i].radius / distOutline; 800 if (ratioVI >= 1.0) { 801 maxRaitoVI = ratioVI; 802 hasValidUmbra = false; 803 } 804 // When we know we don't have valid umbra, don't bother to compute the 805 // values below. But we can't skip the loop yet since we want to know the 806 // maximum ratio. 807 if (hasValidUmbra) { 808 float ratioIC = (distOutline - outlineData[i].radius) / distOutline; 809 umbra[i] = outlineData[i].position * ratioIC + outlineCentroid * ratioVI; 810 } 811 } 812 813 float shadowStrengthScale = 1.0; 814 if (!hasValidUmbra) { 815 ALOGW("The object is too close to the light or too small, no real umbra!"); 816 for (int i = 0; i < polyLength; i++) { 817 umbra[i] = outlineData[i].position * FAKE_UMBRA_SIZE_RATIO + 818 outlineCentroid * (1 - FAKE_UMBRA_SIZE_RATIO); 819 } 820 shadowStrengthScale = 1.0 / maxRaitoVI; 821 } 822 823#if DEBUG_SHADOW 824 dumpPolygon(poly, polyLength, "input poly"); 825 dumpPolygon(outline, polyLength, "outline"); 826 dumpPolygon(penumbra, penumbraLength, "penumbra"); 827 dumpPolygon(umbra, polyLength, "umbra"); 828 ALOGD("hasValidUmbra is %d and shadowStrengthScale is %f", hasValidUmbra, shadowStrengthScale); 829#endif 830 831 generateTriangleStrip(isCasterOpaque, shadowStrengthScale, penumbra, 832 penumbraLength, umbra, polyLength, poly, polyLength, shadowTriangleStrip); 833} 834 835/** 836 * Converts a polygon specified with CW vertices into an array of distance-from-centroid values. 837 * 838 * Returns false in error conditions 839 * 840 * @param poly Array of vertices. Note that these *must* be CW. 841 * @param polyLength The number of vertices in the polygon. 842 * @param polyCentroid The centroid of the polygon, from which rays will be cast 843 * @param rayDist The output array for the calculated distances, must be SHADOW_RAY_COUNT in size 844 */ 845bool convertPolyToRayDist(const Vector2* poly, int polyLength, const Vector2& polyCentroid, 846 float* rayDist) { 847 const int rays = SHADOW_RAY_COUNT; 848 const float step = M_PI * 2 / rays; 849 850 const Vector2* lastVertex = &(poly[polyLength - 1]); 851 float startAngle = angle(*lastVertex, polyCentroid); 852 853 // Start with the ray that's closest to and less than startAngle 854 int rayIndex = floor((startAngle - EPSILON) / step); 855 rayIndex = (rayIndex + rays) % rays; // ensure positive 856 857 for (int polyIndex = 0; polyIndex < polyLength; polyIndex++) { 858 /* 859 * For a given pair of vertices on the polygon, poly[i-1] and poly[i], the rays that 860 * intersect these will be those that are between the two angles from the centroid that the 861 * vertices define. 862 * 863 * Because the polygon vertices are stored clockwise, the closest ray with an angle 864 * *smaller* than that defined by angle(poly[i], centroid) will be the first ray that does 865 * not intersect with poly[i-1], poly[i]. 866 */ 867 float currentAngle = angle(poly[polyIndex], polyCentroid); 868 869 // find first ray that will not intersect the line segment poly[i-1] & poly[i] 870 int firstRayIndexOnNextSegment = floor((currentAngle - EPSILON) / step); 871 firstRayIndexOnNextSegment = (firstRayIndexOnNextSegment + rays) % rays; // ensure positive 872 873 // Iterate through all rays that intersect with poly[i-1], poly[i] line segment. 874 // This may be 0 rays. 875 while (rayIndex != firstRayIndexOnNextSegment) { 876 float distanceToIntersect = rayIntersectPoints(polyCentroid, 877 cos(rayIndex * step), 878 sin(rayIndex * step), 879 *lastVertex, poly[polyIndex]); 880 if (distanceToIntersect < 0) { 881#if DEBUG_SHADOW 882 ALOGW("ERROR: convertPolyToRayDist failed"); 883#endif 884 return false; // error case, abort 885 } 886 887 rayDist[rayIndex] = distanceToIntersect; 888 889 rayIndex = (rayIndex - 1 + rays) % rays; 890 } 891 lastVertex = &poly[polyIndex]; 892 } 893 894 return true; 895} 896 897int SpotShadow::calculateOccludedUmbra(const Vector2* umbra, int umbraLength, 898 const Vector3* poly, int polyLength, Vector2* occludedUmbra) { 899 // Occluded umbra area is computed as the intersection of the projected 2D 900 // poly and umbra. 901 for (int i = 0; i < polyLength; i++) { 902 occludedUmbra[i].x = poly[i].x; 903 occludedUmbra[i].y = poly[i].y; 904 } 905 906 // Both umbra and incoming polygon are guaranteed to be CW, so we can call 907 // intersection() directly. 908 return intersection(umbra, umbraLength, 909 occludedUmbra, polyLength); 910} 911 912/** 913 * Generate a triangle strip given two convex polygons 914 * 915 * @param penumbra The outer polygon x,y vertexes 916 * @param penumbraLength The number of vertexes in the outer polygon 917 * @param umbra The inner outer polygon x,y vertexes 918 * @param umbraLength The number of vertexes in the inner polygon 919 * @param shadowTriangleStrip return an (x,y,alpha) triangle strip representing the shadow. Return 920 * empty strip if error. 921**/ 922void SpotShadow::generateTriangleStrip(bool isCasterOpaque, float shadowStrengthScale, 923 const Vector2* penumbra, int penumbraLength, const Vector2* umbra, int umbraLength, 924 const Vector3* poly, int polyLength, VertexBuffer& shadowTriangleStrip) { 925 const int rays = SHADOW_RAY_COUNT; 926 const int size = 2 * rays; 927 const float step = M_PI * 2 / rays; 928 // Centroid of the umbra. 929 Vector2 centroid = ShadowTessellator::centroid2d(umbra, umbraLength); 930#if DEBUG_SHADOW 931 ALOGD("centroid2d = %f , %f", centroid.x, centroid.y); 932#endif 933 // Intersection to the penumbra. 934 float penumbraDistPerRay[rays]; 935 // Intersection to the umbra. 936 float umbraDistPerRay[rays]; 937 // Intersection to the occluded umbra area. 938 float occludedUmbraDistPerRay[rays]; 939 940 // convert CW polygons to ray distance encoding, aborting on conversion failure 941 if (!convertPolyToRayDist(umbra, umbraLength, centroid, umbraDistPerRay)) return; 942 if (!convertPolyToRayDist(penumbra, penumbraLength, centroid, penumbraDistPerRay)) return; 943 944 bool hasOccludedUmbraArea = false; 945 if (isCasterOpaque) { 946 Vector2 occludedUmbra[polyLength + umbraLength]; 947 int occludedUmbraLength = calculateOccludedUmbra(umbra, umbraLength, poly, polyLength, 948 occludedUmbra); 949 // Make sure the centroid is inside the umbra, otherwise, fall back to the 950 // approach as if there is no occluded umbra area. 951 if (testPointInsidePolygon(centroid, occludedUmbra, occludedUmbraLength)) { 952 hasOccludedUmbraArea = true; 953 // Shrink the occluded umbra area to avoid pixel level artifacts. 954 for (int i = 0; i < occludedUmbraLength; i ++) { 955 occludedUmbra[i] = centroid + (occludedUmbra[i] - centroid) * 956 OCLLUDED_UMBRA_SHRINK_FACTOR; 957 } 958 if (!convertPolyToRayDist(occludedUmbra, occludedUmbraLength, centroid, 959 occludedUmbraDistPerRay)) { 960 return; 961 } 962 } 963 } 964 AlphaVertex* shadowVertices = 965 shadowTriangleStrip.alloc<AlphaVertex>(SHADOW_VERTEX_COUNT); 966 967 // NOTE: Shadow alpha values are transformed when stored in alphavertices, 968 // so that they can be consumed directly by gFS_Main_ApplyVertexAlphaShadowInterp 969 float transformedMaxAlpha = M_PI * shadowStrengthScale; 970 971 // Calculate the vertices (x, y, alpha) in the shadow area. 972 AlphaVertex centroidXYA; 973 AlphaVertex::set(¢roidXYA, centroid.x, centroid.y, transformedMaxAlpha); 974 for (int rayIndex = 0; rayIndex < rays; rayIndex++) { 975 float dx = cosf(step * rayIndex); 976 float dy = sinf(step * rayIndex); 977 978 // penumbra ring 979 float penumbraDistance = penumbraDistPerRay[rayIndex]; 980 AlphaVertex::set(&shadowVertices[rayIndex], 981 dx * penumbraDistance + centroid.x, 982 dy * penumbraDistance + centroid.y, 0.0f); 983 984 // umbra ring 985 float umbraDistance = umbraDistPerRay[rayIndex]; 986 AlphaVertex::set(&shadowVertices[rays + rayIndex], 987 dx * umbraDistance + centroid.x, 988 dy * umbraDistance + centroid.y, 989 transformedMaxAlpha); 990 991 // occluded umbra ring 992 if (hasOccludedUmbraArea) { 993 float occludedUmbraDistance = occludedUmbraDistPerRay[rayIndex]; 994 AlphaVertex::set(&shadowVertices[2 * rays + rayIndex], 995 dx * occludedUmbraDistance + centroid.x, 996 dy * occludedUmbraDistance + centroid.y, transformedMaxAlpha); 997 } else { 998 // Put all vertices of the occluded umbra ring at the centroid. 999 shadowVertices[2 * rays + rayIndex] = centroidXYA; 1000 } 1001 } 1002 shadowTriangleStrip.setMode(VertexBuffer::kTwoPolyRingShadow); 1003 shadowTriangleStrip.computeBounds<AlphaVertex>(); 1004} 1005 1006/** 1007 * This is only for experimental purpose. 1008 * After intersections are calculated, we could smooth the polygon if needed. 1009 * So far, we don't think it is more appealing yet. 1010 * 1011 * @param level The level of smoothness. 1012 * @param rays The total number of rays. 1013 * @param rayDist (In and Out) The distance for each ray. 1014 * 1015 */ 1016void SpotShadow::smoothPolygon(int level, int rays, float* rayDist) { 1017 for (int k = 0; k < level; k++) { 1018 for (int i = 0; i < rays; i++) { 1019 float p1 = rayDist[(rays - 1 + i) % rays]; 1020 float p2 = rayDist[i]; 1021 float p3 = rayDist[(i + 1) % rays]; 1022 rayDist[i] = (p1 + p2 * 2 + p3) / 4; 1023 } 1024 } 1025} 1026 1027#if DEBUG_SHADOW 1028 1029#define TEST_POINT_NUMBER 128 1030 1031/** 1032 * Calculate the bounds for generating random test points. 1033 */ 1034void SpotShadow::updateBound(const Vector2 inVector, Vector2& lowerBound, 1035 Vector2& upperBound ) { 1036 if (inVector.x < lowerBound.x) { 1037 lowerBound.x = inVector.x; 1038 } 1039 1040 if (inVector.y < lowerBound.y) { 1041 lowerBound.y = inVector.y; 1042 } 1043 1044 if (inVector.x > upperBound.x) { 1045 upperBound.x = inVector.x; 1046 } 1047 1048 if (inVector.y > upperBound.y) { 1049 upperBound.y = inVector.y; 1050 } 1051} 1052 1053/** 1054 * For debug purpose, when things go wrong, dump the whole polygon data. 1055 */ 1056void SpotShadow::dumpPolygon(const Vector2* poly, int polyLength, const char* polyName) { 1057 for (int i = 0; i < polyLength; i++) { 1058 ALOGD("polygon %s i %d x %f y %f", polyName, i, poly[i].x, poly[i].y); 1059 } 1060} 1061 1062/** 1063 * For debug purpose, when things go wrong, dump the whole polygon data. 1064 */ 1065void SpotShadow::dumpPolygon(const Vector3* poly, int polyLength, const char* polyName) { 1066 for (int i = 0; i < polyLength; i++) { 1067 ALOGD("polygon %s i %d x %f y %f", polyName, i, poly[i].x, poly[i].y); 1068 } 1069} 1070 1071/** 1072 * Test whether the polygon is convex. 1073 */ 1074bool SpotShadow::testConvex(const Vector2* polygon, int polygonLength, 1075 const char* name) { 1076 bool isConvex = true; 1077 for (int i = 0; i < polygonLength; i++) { 1078 Vector2 start = polygon[i]; 1079 Vector2 middle = polygon[(i + 1) % polygonLength]; 1080 Vector2 end = polygon[(i + 2) % polygonLength]; 1081 1082 double delta = (double(middle.x) - start.x) * (double(end.y) - start.y) - 1083 (double(middle.y) - start.y) * (double(end.x) - start.x); 1084 bool isCCWOrCoLinear = (delta >= EPSILON); 1085 1086 if (isCCWOrCoLinear) { 1087 ALOGW("(Error Type 2): polygon (%s) is not a convex b/c start (x %f, y %f)," 1088 "middle (x %f, y %f) and end (x %f, y %f) , delta is %f !!!", 1089 name, start.x, start.y, middle.x, middle.y, end.x, end.y, delta); 1090 isConvex = false; 1091 break; 1092 } 1093 } 1094 return isConvex; 1095} 1096 1097/** 1098 * Test whether or not the polygon (intersection) is within the 2 input polygons. 1099 * Using Marte Carlo method, we generate a random point, and if it is inside the 1100 * intersection, then it must be inside both source polygons. 1101 */ 1102void SpotShadow::testIntersection(const Vector2* poly1, int poly1Length, 1103 const Vector2* poly2, int poly2Length, 1104 const Vector2* intersection, int intersectionLength) { 1105 // Find the min and max of x and y. 1106 Vector2 lowerBound = {FLT_MAX, FLT_MAX}; 1107 Vector2 upperBound = {-FLT_MAX, -FLT_MAX}; 1108 for (int i = 0; i < poly1Length; i++) { 1109 updateBound(poly1[i], lowerBound, upperBound); 1110 } 1111 for (int i = 0; i < poly2Length; i++) { 1112 updateBound(poly2[i], lowerBound, upperBound); 1113 } 1114 1115 bool dumpPoly = false; 1116 for (int k = 0; k < TEST_POINT_NUMBER; k++) { 1117 // Generate a random point between minX, minY and maxX, maxY. 1118 double randomX = rand() / double(RAND_MAX); 1119 double randomY = rand() / double(RAND_MAX); 1120 1121 Vector2 testPoint; 1122 testPoint.x = lowerBound.x + randomX * (upperBound.x - lowerBound.x); 1123 testPoint.y = lowerBound.y + randomY * (upperBound.y - lowerBound.y); 1124 1125 // If the random point is in both poly 1 and 2, then it must be intersection. 1126 if (testPointInsidePolygon(testPoint, intersection, intersectionLength)) { 1127 if (!testPointInsidePolygon(testPoint, poly1, poly1Length)) { 1128 dumpPoly = true; 1129 ALOGW("(Error Type 1): one point (%f, %f) in the intersection is" 1130 " not in the poly1", 1131 testPoint.x, testPoint.y); 1132 } 1133 1134 if (!testPointInsidePolygon(testPoint, poly2, poly2Length)) { 1135 dumpPoly = true; 1136 ALOGW("(Error Type 1): one point (%f, %f) in the intersection is" 1137 " not in the poly2", 1138 testPoint.x, testPoint.y); 1139 } 1140 } 1141 } 1142 1143 if (dumpPoly) { 1144 dumpPolygon(intersection, intersectionLength, "intersection"); 1145 for (int i = 1; i < intersectionLength; i++) { 1146 Vector2 delta = intersection[i] - intersection[i - 1]; 1147 ALOGD("Intersetion i, %d Vs i-1 is delta %f", i, delta.lengthSquared()); 1148 } 1149 1150 dumpPolygon(poly1, poly1Length, "poly 1"); 1151 dumpPolygon(poly2, poly2Length, "poly 2"); 1152 } 1153} 1154#endif 1155 1156}; // namespace uirenderer 1157}; // namespace android 1158