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