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