2 * Copyright (C) 2014 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 // The highest z value can't be higher than (CASTER_Z_CAP_RATIO * light.z)
18 #define CASTER_Z_CAP_RATIO 0.95f
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
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
28 #define FINE_TESSELLATED_POLYGON_RAY_NUMBER 270
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.
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
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)
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)
45 #define PENUMBRA_ALPHA 0.0f
46 #define UMBRA_ALPHA 1.0f
48 #include "SpotShadow.h"
50 #include "ShadowTessellator.h"
52 #include "VertexBuffer.h"
53 #include "utils/MathUtils.h"
58 #include <utils/Log.h>
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.
64 namespace uirenderer {
66 static const float EPSILON = 1e-7;
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.
81 * For each vertex, we need to keep track of its angle, whether it is penumbra or
82 * umbra, and its corresponding vertex index.
84 struct SpotShadow::VertexAngleData {
85 // The angle to the vertex from the centroid.
87 // True is the vertex comes from penumbra, otherwise it comes from umbra.
89 // The index of the vertex described by this data.
91 void set(float angle, bool isPenumbra, int index) {
93 mIsPenumbra = isPenumbra;
99 * Calculate the angle between and x and a y coordinate.
100 * The atan2 range from -PI to PI.
102 static float angle(const Vector2& point, const Vector2& center) {
103 return atan2(point.y - center.y, point.x - center.x);
107 * Calculate the intersection of a ray with the line segment defined by two points.
109 * Returns a negative value in error conditions.
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
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]);
124 float divisor = (dx * (p1.y - p2.y) + dy * p2.x - dy * p1.x);
125 if (divisor == 0) return -1.0f; // error, invalid divisor
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);
134 float distance = (p1.x * (rayOrigin.y - p2.y) + p2.x * (p1.y - rayOrigin.y) +
135 rayOrigin.x * (p2.y - p1.y)) / divisor;
137 return distance; // may be negative in error cases
141 * Sort points by their X coordinates
143 * @param points the points as a Vector2 array.
144 * @param pointsLength the number of vertices of the polygon.
146 void SpotShadow::xsort(Vector2* points, int pointsLength) {
147 auto cmp = [](const Vector2& a, const Vector2& b) -> bool {
150 std::sort(points, points + pointsLength, cmp);
154 * compute the convex hull of a collection of Points
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
161 int SpotShadow::hull(Vector2* points, int pointsLength, Vector2* retPoly) {
162 xsort(points, pointsLength);
163 int n = pointsLength;
165 lUpper[0] = points[0];
166 lUpper[1] = points[1];
170 for (int i = 2; i < n; i++) {
171 lUpper[lUpperSize] = points[i];
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;
186 lLower[0] = points[n - 1];
187 lLower[1] = points[n - 2];
191 for (int i = n - 3; i >= 0; i--) {
192 lLower[lLowerSize] = points[i];
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];
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];
213 for (int i = 1; i < lLowerSize - 1; i++) {
214 retPoly[outIndex] = lLower[i];
217 // TODO: Add test harness which verify that all the points are inside the hull.
222 * Test whether the 3 points form a counter clockwise turn.
224 * @return true if a right hand turn
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;
232 * Sort points about a center point
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.
238 void SpotShadow::sort(Vector2* poly, int polyLength, const Vector2& center) {
239 quicksortCirc(poly, 0, polyLength - 1, center);
243 * Swap points pointed to by i and j
245 void SpotShadow::swap(Vector2* points, int i, int j) {
246 Vector2 temp = points[i];
247 points[i] = points[j];
252 * quick sort implementation about the center.
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);
260 while (angle(points[i], center) > pivot) {
263 while (angle(points[j], center) < pivot) {
273 if (low < j) quicksortCirc(points, low, j, center);
274 if (i < high) quicksortCirc(points, i, high, center);
278 * Test whether a point is inside the polygon.
280 * @param testPoint the point to test
281 * @param poly the polygon
282 * @return true if the testPoint is inside the poly.
284 bool SpotShadow::testPointInsidePolygon(const Vector2 testPoint,
285 const Vector2* poly, int len) {
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;
295 if (((endY > testy) != (startY > testy))
296 && (testx < (startX - endX) * (testy - endY)
297 / (startY - endY) + endX)) {
305 * Make the polygon turn clockwise.
307 * @param polygon the polygon as a Vector2 array.
308 * @param len the number of points of the polygon
310 void SpotShadow::makeClockwise(Vector2* polygon, int len) {
311 if (polygon == nullptr || len == 0) {
314 if (!ShadowTessellator::isClockwise(polygon, len)) {
315 reverse(polygon, len);
320 * Reverse the polygon
322 * @param polygon the polygon as a Vector2 array
323 * @param len the number of points of the polygon
325 void SpotShadow::reverse(Vector2* polygon, int len) {
327 for (int i = 0; i < n; i++) {
328 Vector2 tmp = polygon[i];
330 polygon[i] = polygon[k];
336 * Compute a horizontal circular polygon about point (x , y , height) of radius
339 * @param points number of the points of the output polygon.
340 * @param lightCenter the center of the light.
341 * @param size the light size.
342 * @param ret result polygon.
344 void SpotShadow::computeLightPolygon(int points, const Vector3& lightCenter,
345 float size, Vector3* ret) {
346 // TODO: Caching all the sin / cos values and store them in a look up table.
347 for (int i = 0; i < points; i++) {
348 float angle = 2 * i * M_PI / points;
349 ret[i].x = cosf(angle) * size + lightCenter.x;
350 ret[i].y = sinf(angle) * size + lightCenter.y;
351 ret[i].z = lightCenter.z;
356 * From light center, project one vertex to the z=0 surface and get the outline.
358 * @param outline The result which is the outline position.
359 * @param lightCenter The center of light.
360 * @param polyVertex The input polygon's vertex.
362 * @return float The ratio of (polygon.z / light.z - polygon.z)
364 float SpotShadow::projectCasterToOutline(Vector2& outline,
365 const Vector3& lightCenter, const Vector3& polyVertex) {
366 float lightToPolyZ = lightCenter.z - polyVertex.z;
367 float ratioZ = CASTER_Z_CAP_RATIO;
368 if (lightToPolyZ != 0) {
369 // If any caster's vertex is almost above the light, we just keep it as 95%
370 // of the height of the light.
371 ratioZ = MathUtils::clamp(polyVertex.z / lightToPolyZ, 0.0f, CASTER_Z_CAP_RATIO);
374 outline.x = polyVertex.x - ratioZ * (lightCenter.x - polyVertex.x);
375 outline.y = polyVertex.y - ratioZ * (lightCenter.y - polyVertex.y);
380 * Generate the shadow spot light of shape lightPoly and a object poly
382 * @param isCasterOpaque whether the caster is opaque
383 * @param lightCenter the center of the light
384 * @param lightSize the radius of the light
385 * @param poly x,y,z vertexes of a convex polygon that occludes the light source
386 * @param polyLength number of vertexes of the occluding polygon
387 * @param shadowTriangleStrip return an (x,y,alpha) triangle strip representing the shadow. Return
388 * empty strip if error.
390 void SpotShadow::createSpotShadow(bool isCasterOpaque, const Vector3& lightCenter,
391 float lightSize, const Vector3* poly, int polyLength, const Vector3& polyCentroid,
392 VertexBuffer& shadowTriangleStrip) {
393 if (CC_UNLIKELY(lightCenter.z <= 0)) {
394 ALOGW("Relative Light Z is not positive. No spot shadow!");
397 if (CC_UNLIKELY(polyLength < 3)) {
399 ALOGW("Invalid polygon length. No spot shadow!");
403 OutlineData outlineData[polyLength];
404 Vector2 outlineCentroid;
405 // Calculate the projected outline for each polygon's vertices from the light center.
413 // O Outline vertices
415 // Ratio = (Poly - Outline) / (Light - Poly)
416 // Outline.x = Poly.x - Ratio * (Light.x - Poly.x)
417 // Outline's radius / Light's radius = Ratio
419 // Compute the last outline vertex to make sure we can get the normal and outline
420 // in one single loop.
421 projectCasterToOutline(outlineData[polyLength - 1].position, lightCenter,
422 poly[polyLength - 1]);
424 // Take the outline's polygon, calculate the normal for each outline edge.
425 int currentNormalIndex = polyLength - 1;
426 int nextNormalIndex = 0;
428 for (int i = 0; i < polyLength; i++) {
429 float ratioZ = projectCasterToOutline(outlineData[i].position,
430 lightCenter, poly[i]);
431 outlineData[i].radius = ratioZ * lightSize;
433 outlineData[currentNormalIndex].normal = ShadowTessellator::calculateNormal(
434 outlineData[currentNormalIndex].position,
435 outlineData[nextNormalIndex].position);
436 currentNormalIndex = (currentNormalIndex + 1) % polyLength;
440 projectCasterToOutline(outlineCentroid, lightCenter, polyCentroid);
442 int penumbraIndex = 0;
443 // Then each polygon's vertex produce at minmal 2 penumbra vertices.
444 // Since the size can be dynamic here, we keep track of the size and update
445 // the real size at the end.
446 int allocatedPenumbraLength = 2 * polyLength + SPOT_MAX_EXTRA_CORNER_VERTEX_NUMBER;
447 Vector2 penumbra[allocatedPenumbraLength];
448 int totalExtraCornerSliceNumber = 0;
450 Vector2 umbra[polyLength];
452 // When centroid is covered by all circles from outline, then we consider
453 // the umbra is invalid, and we will tune down the shadow strength.
454 bool hasValidUmbra = true;
455 // We need the minimal of RaitoVI to decrease the spot shadow strength accordingly.
456 float minRaitoVI = FLT_MAX;
458 for (int i = 0; i < polyLength; i++) {
459 // Generate all the penumbra's vertices only using the (outline vertex + normal * radius)
460 // There is no guarantee that the penumbra is still convex, but for
461 // each outline vertex, it will connect to all its corresponding penumbra vertices as
462 // triangle fans. And for neighber penumbra vertex, it will be a trapezoid.
464 // Penumbra Vertices marked as Pi
465 // Outline Vertices marked as Vi
470 // (P0) ------------------------------------------------(P5)
480 // (V3)-----------------------------------(V2)
481 int preNormalIndex = (i + polyLength - 1) % polyLength;
483 const Vector2& previousNormal = outlineData[preNormalIndex].normal;
484 const Vector2& currentNormal = outlineData[i].normal;
486 // Depending on how roundness we want for each corner, we can subdivide
487 // further here and/or introduce some heuristic to decide how much the
488 // subdivision should be.
489 int currentExtraSliceNumber = ShadowTessellator::getExtraVertexNumber(
490 previousNormal, currentNormal, SPOT_CORNER_RADIANS_DIVISOR);
492 int currentCornerSliceNumber = 1 + currentExtraSliceNumber;
493 totalExtraCornerSliceNumber += currentExtraSliceNumber;
495 ALOGD("currentExtraSliceNumber should be %d", currentExtraSliceNumber);
496 ALOGD("currentCornerSliceNumber should be %d", currentCornerSliceNumber);
497 ALOGD("totalCornerSliceNumber is %d", totalExtraCornerSliceNumber);
499 if (CC_UNLIKELY(totalExtraCornerSliceNumber > SPOT_MAX_EXTRA_CORNER_VERTEX_NUMBER)) {
500 currentCornerSliceNumber = 1;
502 for (int k = 0; k <= currentCornerSliceNumber; k++) {
504 (previousNormal * (currentCornerSliceNumber - k) + currentNormal * k) /
505 currentCornerSliceNumber;
506 avgNormal.normalize();
507 penumbra[penumbraIndex++] = outlineData[i].position +
508 avgNormal * outlineData[i].radius;
512 // Compute the umbra by the intersection from the outline's centroid!
514 // (V) ------------------------------------
524 // ------------------------------------
526 // Connect a line b/t the outline vertex (V) and the centroid (C), it will
527 // intersect with the outline vertex's circle at point (I).
528 // Now, ratioVI = VI / VC, ratioIC = IC / VC
529 // Then the intersetion point can be computed as Ixy = Vxy * ratioIC + Cxy * ratioVI;
531 // When all of the outline circles cover the the outline centroid, (like I is
532 // on the other side of C), there is no real umbra any more, so we just fake
533 // a small area around the centroid as the umbra, and tune down the spot
534 // shadow's umbra strength to simulate the effect the whole shadow will
535 // become lighter in this case.
536 // The ratio can be simulated by using the inverse of maximum of ratioVI for
538 float distOutline = (outlineData[i].position - outlineCentroid).length();
539 if (CC_UNLIKELY(distOutline == 0)) {
540 // If the outline has 0 area, then there is no spot shadow anyway.
541 ALOGW("Outline has 0 area, no spot shadow!");
545 float ratioVI = outlineData[i].radius / distOutline;
546 minRaitoVI = std::min(minRaitoVI, ratioVI);
547 if (ratioVI >= (1 - FAKE_UMBRA_SIZE_RATIO)) {
548 ratioVI = (1 - FAKE_UMBRA_SIZE_RATIO);
550 // When we know we don't have valid umbra, don't bother to compute the
551 // values below. But we can't skip the loop yet since we want to know the
553 float ratioIC = 1 - ratioVI;
554 umbra[i] = outlineData[i].position * ratioIC + outlineCentroid * ratioVI;
557 hasValidUmbra = (minRaitoVI <= 1.0);
558 float shadowStrengthScale = 1.0;
559 if (!hasValidUmbra) {
561 ALOGW("The object is too close to the light or too small, no real umbra!");
563 for (int i = 0; i < polyLength; i++) {
564 umbra[i] = outlineData[i].position * FAKE_UMBRA_SIZE_RATIO +
565 outlineCentroid * (1 - FAKE_UMBRA_SIZE_RATIO);
567 shadowStrengthScale = 1.0 / minRaitoVI;
570 int penumbraLength = penumbraIndex;
571 int umbraLength = polyLength;
574 ALOGD("penumbraLength is %d , allocatedPenumbraLength %d", penumbraLength, allocatedPenumbraLength);
575 dumpPolygon(poly, polyLength, "input poly");
576 dumpPolygon(penumbra, penumbraLength, "penumbra");
577 dumpPolygon(umbra, umbraLength, "umbra");
578 ALOGD("hasValidUmbra is %d and shadowStrengthScale is %f", hasValidUmbra, shadowStrengthScale);
581 // The penumbra and umbra needs to be in convex shape to keep consistency
583 // Since we are still shooting rays to penumbra, it needs to be convex.
584 // Umbra can be represented as a fan from the centroid, but visually umbra
585 // looks nicer when it is convex.
586 Vector2 finalUmbra[umbraLength];
587 Vector2 finalPenumbra[penumbraLength];
588 int finalUmbraLength = hull(umbra, umbraLength, finalUmbra);
589 int finalPenumbraLength = hull(penumbra, penumbraLength, finalPenumbra);
591 generateTriangleStrip(isCasterOpaque, shadowStrengthScale, finalPenumbra,
592 finalPenumbraLength, finalUmbra, finalUmbraLength, poly, polyLength,
593 shadowTriangleStrip, outlineCentroid);
598 * This is only for experimental purpose.
599 * After intersections are calculated, we could smooth the polygon if needed.
600 * So far, we don't think it is more appealing yet.
602 * @param level The level of smoothness.
603 * @param rays The total number of rays.
604 * @param rayDist (In and Out) The distance for each ray.
607 void SpotShadow::smoothPolygon(int level, int rays, float* rayDist) {
608 for (int k = 0; k < level; k++) {
609 for (int i = 0; i < rays; i++) {
610 float p1 = rayDist[(rays - 1 + i) % rays];
611 float p2 = rayDist[i];
612 float p3 = rayDist[(i + 1) % rays];
613 rayDist[i] = (p1 + p2 * 2 + p3) / 4;
618 // Index pair is meant for storing the tessellation information for the penumbra
619 // area. One index must come from exterior tangent of the circles, the other one
620 // must come from the interior tangent of the circles.
626 // For one penumbra vertex, find the cloest umbra vertex and return its index.
627 inline int getClosestUmbraIndex(const Vector2& pivot, const Vector2* polygon, int polygonLength) {
628 float minLengthSquared = FLT_MAX;
629 int resultIndex = -1;
630 bool hasDecreased = false;
631 // Starting with some negative offset, assuming both umbra and penumbra are starting
632 // at the same angle, this can help to find the result faster.
633 // Normally, loop 3 times, we can find the closest point.
634 int offset = polygonLength - 2;
635 for (int i = 0; i < polygonLength; i++) {
636 int currentIndex = (i + offset) % polygonLength;
637 float currentLengthSquared = (pivot - polygon[currentIndex]).lengthSquared();
638 if (currentLengthSquared < minLengthSquared) {
639 if (minLengthSquared != FLT_MAX) {
642 minLengthSquared = currentLengthSquared;
643 resultIndex = currentIndex;
644 } else if (currentLengthSquared > minLengthSquared && hasDecreased) {
645 // Early break b/c we have found the closet one and now the length
646 // is increasing again.
650 if(resultIndex == -1) {
651 ALOGE("resultIndex is -1, the polygon must be invalid!");
657 // Allow some epsilon here since the later ray intersection did allow for some small
658 // floating point error, when the intersection point is slightly outside the segment.
659 inline bool sameDirections(bool isPositiveCross, float a, float b) {
660 if (isPositiveCross) {
661 return a >= -EPSILON && b >= -EPSILON;
663 return a <= EPSILON && b <= EPSILON;
667 // Find the right polygon edge to shoot the ray at.
668 inline int findPolyIndex(bool isPositiveCross, int startPolyIndex, const Vector2& umbraDir,
669 const Vector2* polyToCentroid, int polyLength) {
670 // Make sure we loop with a bound.
671 for (int i = 0; i < polyLength; i++) {
672 int currentIndex = (i + startPolyIndex) % polyLength;
673 const Vector2& currentToCentroid = polyToCentroid[currentIndex];
674 const Vector2& nextToCentroid = polyToCentroid[(currentIndex + 1) % polyLength];
676 float currentCrossUmbra = currentToCentroid.cross(umbraDir);
677 float umbraCrossNext = umbraDir.cross(nextToCentroid);
678 if (sameDirections(isPositiveCross, currentCrossUmbra, umbraCrossNext)) {
680 ALOGD("findPolyIndex loop %d times , index %d", i, currentIndex );
685 LOG_ALWAYS_FATAL("Can't find the right polygon's edge from startPolyIndex %d", startPolyIndex);
689 // Generate the index pair for penumbra / umbra vertices, and more penumbra vertices
691 inline void genNewPenumbraAndPairWithUmbra(const Vector2* penumbra, int penumbraLength,
692 const Vector2* umbra, int umbraLength, Vector2* newPenumbra, int& newPenumbraIndex,
693 IndexPair* verticesPair, int& verticesPairIndex) {
694 // In order to keep everything in just one loop, we need to pre-compute the
695 // closest umbra vertex for the last penumbra vertex.
696 int previousClosestUmbraIndex = getClosestUmbraIndex(penumbra[penumbraLength - 1],
698 for (int i = 0; i < penumbraLength; i++) {
699 const Vector2& currentPenumbraVertex = penumbra[i];
700 // For current penumbra vertex, starting from previousClosestUmbraIndex,
701 // then check the next one until the distance increase.
702 // The last one before the increase is the umbra vertex we need to pair with.
703 float currentLengthSquared =
704 (currentPenumbraVertex - umbra[previousClosestUmbraIndex]).lengthSquared();
705 int currentClosestUmbraIndex = previousClosestUmbraIndex;
707 for (int j = 1; j < umbraLength; j++) {
708 int newUmbraIndex = (previousClosestUmbraIndex + j) % umbraLength;
709 float newLengthSquared = (currentPenumbraVertex - umbra[newUmbraIndex]).lengthSquared();
710 if (newLengthSquared > currentLengthSquared) {
711 // currentClosestUmbraIndex is the umbra vertex's index which has
712 // currently found smallest distance, so we can simply break here.
715 currentLengthSquared = newLengthSquared;
717 currentClosestUmbraIndex = newUmbraIndex;
721 if (indexDelta > 1) {
722 // For those umbra don't have penumbra, generate new penumbra vertices by interpolation.
724 // Assuming Pi for penumbra vertices, and Ui for umbra vertices.
725 // In the case like below P1 paired with U1 and P2 paired with U5.
726 // U2 to U4 are unpaired umbra vertices.
732 // We will need to generate 3 more penumbra vertices P1.1, P1.2, P1.3
733 // to pair with U2 to U4.
735 // P1 P1.1 P1.2 P1.3 P2
739 // That distance ratio b/t Ui to U1 and Ui to U5 decides its paired penumbra
740 // vertex's location.
741 int newPenumbraNumber = indexDelta - 1;
743 float accumulatedDeltaLength[indexDelta];
744 float totalDeltaLength = 0;
746 // To save time, cache the previous umbra vertex info outside the loop
747 // and update each loop.
748 Vector2 previousClosestUmbra = umbra[previousClosestUmbraIndex];
749 Vector2 skippedUmbra;
750 // Use umbra data to precompute the length b/t unpaired umbra vertices,
751 // and its ratio against the total length.
752 for (int k = 0; k < indexDelta; k++) {
753 int skippedUmbraIndex = (previousClosestUmbraIndex + k + 1) % umbraLength;
754 skippedUmbra = umbra[skippedUmbraIndex];
755 float currentDeltaLength = (skippedUmbra - previousClosestUmbra).length();
757 totalDeltaLength += currentDeltaLength;
758 accumulatedDeltaLength[k] = totalDeltaLength;
760 previousClosestUmbra = skippedUmbra;
763 const Vector2& previousPenumbra = penumbra[(i + penumbraLength - 1) % penumbraLength];
764 // Then for each unpaired umbra vertex, create a new penumbra by the ratio,
765 // and pair them togehter.
766 for (int k = 0; k < newPenumbraNumber; k++) {
767 float weightForCurrentPenumbra = 1.0f;
768 if (totalDeltaLength != 0.0f) {
769 weightForCurrentPenumbra = accumulatedDeltaLength[k] / totalDeltaLength;
771 float weightForPreviousPenumbra = 1.0f - weightForCurrentPenumbra;
773 Vector2 interpolatedPenumbra = currentPenumbraVertex * weightForCurrentPenumbra +
774 previousPenumbra * weightForPreviousPenumbra;
776 int skippedUmbraIndex = (previousClosestUmbraIndex + k + 1) % umbraLength;
777 verticesPair[verticesPairIndex].outerIndex = newPenumbraIndex;
778 verticesPair[verticesPairIndex].innerIndex = skippedUmbraIndex;
780 newPenumbra[newPenumbraIndex++] = interpolatedPenumbra;
783 verticesPair[verticesPairIndex].outerIndex = newPenumbraIndex;
784 verticesPair[verticesPairIndex].innerIndex = currentClosestUmbraIndex;
786 newPenumbra[newPenumbraIndex++] = currentPenumbraVertex;
788 previousClosestUmbraIndex = currentClosestUmbraIndex;
792 // Precompute all the polygon's vector, return true if the reference cross product is positive.
793 inline bool genPolyToCentroid(const Vector2* poly2d, int polyLength,
794 const Vector2& centroid, Vector2* polyToCentroid) {
795 for (int j = 0; j < polyLength; j++) {
796 polyToCentroid[j] = poly2d[j] - centroid;
797 // Normalize these vectors such that we can use epsilon comparison after
798 // computing their cross products with another normalized vector.
799 polyToCentroid[j].normalize();
801 float refCrossProduct = 0;
802 for (int j = 0; j < polyLength; j++) {
803 refCrossProduct = polyToCentroid[j].cross(polyToCentroid[(j + 1) % polyLength]);
804 if (refCrossProduct != 0) {
809 return refCrossProduct > 0;
812 // For one umbra vertex, shoot an ray from centroid to it.
813 // If the ray hit the polygon first, then return the intersection point as the
815 inline Vector2 getCloserVertex(const Vector2& umbraVertex, const Vector2& centroid,
816 const Vector2* poly2d, int polyLength, const Vector2* polyToCentroid,
817 bool isPositiveCross, int& previousPolyIndex) {
818 Vector2 umbraToCentroid = umbraVertex - centroid;
819 float distanceToUmbra = umbraToCentroid.length();
820 umbraToCentroid = umbraToCentroid / distanceToUmbra;
822 // previousPolyIndex is updated for each item such that we can minimize the
823 // looping inside findPolyIndex();
824 previousPolyIndex = findPolyIndex(isPositiveCross, previousPolyIndex,
825 umbraToCentroid, polyToCentroid, polyLength);
827 float dx = umbraToCentroid.x;
828 float dy = umbraToCentroid.y;
829 float distanceToIntersectPoly = rayIntersectPoints(centroid, dx, dy,
830 poly2d[previousPolyIndex], poly2d[(previousPolyIndex + 1) % polyLength]);
831 if (distanceToIntersectPoly < 0) {
832 distanceToIntersectPoly = 0;
835 // Pick the closer one as the occluded area vertex.
836 Vector2 closerVertex;
837 if (distanceToIntersectPoly < distanceToUmbra) {
838 closerVertex.x = centroid.x + dx * distanceToIntersectPoly;
839 closerVertex.y = centroid.y + dy * distanceToIntersectPoly;
841 closerVertex = umbraVertex;
848 * Generate a triangle strip given two convex polygon
850 void SpotShadow::generateTriangleStrip(bool isCasterOpaque, float shadowStrengthScale,
851 Vector2* penumbra, int penumbraLength, Vector2* umbra, int umbraLength,
852 const Vector3* poly, int polyLength, VertexBuffer& shadowTriangleStrip,
853 const Vector2& centroid) {
854 bool hasOccludedUmbraArea = false;
855 Vector2 poly2d[polyLength];
857 if (isCasterOpaque) {
858 for (int i = 0; i < polyLength; i++) {
859 poly2d[i].x = poly[i].x;
860 poly2d[i].y = poly[i].y;
862 // Make sure the centroid is inside the umbra, otherwise, fall back to the
863 // approach as if there is no occluded umbra area.
864 if (testPointInsidePolygon(centroid, poly2d, polyLength)) {
865 hasOccludedUmbraArea = true;
869 // For each penumbra vertex, find its corresponding closest umbra vertex index.
871 // Penumbra Vertices marked as Pi
872 // Umbra Vertices marked as Ui
877 // (P0) ------------------------------------------------(P5)
887 // (U4)-----------------------------------(U3) (P6)
889 // At least, like P0, P1, P2, they will find the matching umbra as U0.
890 // If we jump over some umbra vertex without matching penumbra vertex, then
891 // we will generate some new penumbra vertex by interpolation. Like P6 is
892 // matching U3, but U2 is not matched with any penumbra vertex.
893 // So interpolate P5.1 out and match U2.
894 // In this way, every umbra vertex will have a matching penumbra vertex.
896 // The total pair number can be as high as umbraLength + penumbraLength.
897 const int maxNewPenumbraLength = umbraLength + penumbraLength;
898 IndexPair verticesPair[maxNewPenumbraLength];
899 int verticesPairIndex = 0;
901 // Cache all the existing penumbra vertices and newly interpolated vertices into a
903 Vector2 newPenumbra[maxNewPenumbraLength];
904 int newPenumbraIndex = 0;
906 // For each penumbra vertex, find its closet umbra vertex by comparing the
907 // neighbor umbra vertices.
908 genNewPenumbraAndPairWithUmbra(penumbra, penumbraLength, umbra, umbraLength, newPenumbra,
909 newPenumbraIndex, verticesPair, verticesPairIndex);
910 ShadowTessellator::checkOverflow(verticesPairIndex, maxNewPenumbraLength, "Spot pair");
911 ShadowTessellator::checkOverflow(newPenumbraIndex, maxNewPenumbraLength, "Spot new penumbra");
913 for (int i = 0; i < umbraLength; i++) {
914 ALOGD("umbra i %d, [%f, %f]", i, umbra[i].x, umbra[i].y);
916 for (int i = 0; i < newPenumbraIndex; i++) {
917 ALOGD("new penumbra i %d, [%f, %f]", i, newPenumbra[i].x, newPenumbra[i].y);
919 for (int i = 0; i < verticesPairIndex; i++) {
920 ALOGD("index i %d, [%d, %d]", i, verticesPair[i].outerIndex, verticesPair[i].innerIndex);
924 // For the size of vertex buffer, we need 3 rings, one has newPenumbraSize,
925 // one has umbraLength, the last one has at most umbraLength.
927 // For the size of index buffer, the umbra area needs (2 * umbraLength + 2).
928 // The penumbra one can vary a bit, but it is bounded by (2 * verticesPairIndex + 2).
929 // And 2 more for jumping between penumbra to umbra.
930 const int newPenumbraLength = newPenumbraIndex;
931 const int totalVertexCount = newPenumbraLength + umbraLength * 2;
932 const int totalIndexCount = 2 * umbraLength + 2 * verticesPairIndex + 6;
933 AlphaVertex* shadowVertices =
934 shadowTriangleStrip.alloc<AlphaVertex>(totalVertexCount);
935 uint16_t* indexBuffer =
936 shadowTriangleStrip.allocIndices<uint16_t>(totalIndexCount);
937 int vertexBufferIndex = 0;
938 int indexBufferIndex = 0;
940 // Fill the IB and VB for the penumbra area.
941 for (int i = 0; i < newPenumbraLength; i++) {
942 AlphaVertex::set(&shadowVertices[vertexBufferIndex++], newPenumbra[i].x,
943 newPenumbra[i].y, PENUMBRA_ALPHA);
945 for (int i = 0; i < umbraLength; i++) {
946 AlphaVertex::set(&shadowVertices[vertexBufferIndex++], umbra[i].x, umbra[i].y,
950 for (int i = 0; i < verticesPairIndex; i++) {
951 indexBuffer[indexBufferIndex++] = verticesPair[i].outerIndex;
952 // All umbra index need to be offseted by newPenumbraSize.
953 indexBuffer[indexBufferIndex++] = verticesPair[i].innerIndex + newPenumbraLength;
955 indexBuffer[indexBufferIndex++] = verticesPair[0].outerIndex;
956 indexBuffer[indexBufferIndex++] = verticesPair[0].innerIndex + newPenumbraLength;
958 // Now fill the IB and VB for the umbra area.
959 // First duplicated the index from previous strip and the first one for the
960 // degenerated triangles.
961 indexBuffer[indexBufferIndex] = indexBuffer[indexBufferIndex - 1];
963 indexBuffer[indexBufferIndex++] = newPenumbraLength + 0;
964 // Save the first VB index for umbra area in order to close the loop.
965 int savedStartIndex = vertexBufferIndex;
967 if (hasOccludedUmbraArea) {
968 // Precompute all the polygon's vector, and the reference cross product,
969 // in order to find the right polygon edge for the ray to intersect.
970 Vector2 polyToCentroid[polyLength];
971 bool isPositiveCross = genPolyToCentroid(poly2d, polyLength, centroid, polyToCentroid);
973 // Because both the umbra and polygon are going in the same direction,
974 // we can save the previous polygon index to make sure we have less polygon
975 // vertex to compute for each ray.
976 int previousPolyIndex = 0;
977 for (int i = 0; i < umbraLength; i++) {
978 // Shoot a ray from centroid to each umbra vertices and pick the one with
979 // shorter distance to the centroid, b/t the umbra vertex or the intersection point.
980 Vector2 closerVertex = getCloserVertex(umbra[i], centroid, poly2d, polyLength,
981 polyToCentroid, isPositiveCross, previousPolyIndex);
983 // We already stored the umbra vertices, just need to add the occlued umbra's ones.
984 indexBuffer[indexBufferIndex++] = newPenumbraLength + i;
985 indexBuffer[indexBufferIndex++] = vertexBufferIndex;
986 AlphaVertex::set(&shadowVertices[vertexBufferIndex++],
987 closerVertex.x, closerVertex.y, UMBRA_ALPHA);
990 // If there is no occluded umbra at all, then draw the triangle fan
991 // starting from the centroid to all umbra vertices.
992 int lastCentroidIndex = vertexBufferIndex;
993 AlphaVertex::set(&shadowVertices[vertexBufferIndex++], centroid.x,
994 centroid.y, UMBRA_ALPHA);
995 for (int i = 0; i < umbraLength; i++) {
996 indexBuffer[indexBufferIndex++] = newPenumbraLength + i;
997 indexBuffer[indexBufferIndex++] = lastCentroidIndex;
1000 // Closing the umbra area triangle's loop here.
1001 indexBuffer[indexBufferIndex++] = newPenumbraLength;
1002 indexBuffer[indexBufferIndex++] = savedStartIndex;
1004 // At the end, update the real index and vertex buffer size.
1005 shadowTriangleStrip.updateVertexCount(vertexBufferIndex);
1006 shadowTriangleStrip.updateIndexCount(indexBufferIndex);
1007 ShadowTessellator::checkOverflow(vertexBufferIndex, totalVertexCount, "Spot Vertex Buffer");
1008 ShadowTessellator::checkOverflow(indexBufferIndex, totalIndexCount, "Spot Index Buffer");
1010 shadowTriangleStrip.setMeshFeatureFlags(VertexBuffer::kAlpha | VertexBuffer::kIndices);
1011 shadowTriangleStrip.computeBounds<AlphaVertex>();
1016 #define TEST_POINT_NUMBER 128
1018 * Calculate the bounds for generating random test points.
1020 void SpotShadow::updateBound(const Vector2 inVector, Vector2& lowerBound,
1021 Vector2& upperBound) {
1022 if (inVector.x < lowerBound.x) {
1023 lowerBound.x = inVector.x;
1026 if (inVector.y < lowerBound.y) {
1027 lowerBound.y = inVector.y;
1030 if (inVector.x > upperBound.x) {
1031 upperBound.x = inVector.x;
1034 if (inVector.y > upperBound.y) {
1035 upperBound.y = inVector.y;
1040 * For debug purpose, when things go wrong, dump the whole polygon data.
1042 void SpotShadow::dumpPolygon(const Vector2* poly, int polyLength, const char* polyName) {
1043 for (int i = 0; i < polyLength; i++) {
1044 ALOGD("polygon %s i %d x %f y %f", polyName, i, poly[i].x, poly[i].y);
1049 * For debug purpose, when things go wrong, dump the whole polygon data.
1051 void SpotShadow::dumpPolygon(const Vector3* poly, int polyLength, const char* polyName) {
1052 for (int i = 0; i < polyLength; i++) {
1053 ALOGD("polygon %s i %d x %f y %f z %f", polyName, i, poly[i].x, poly[i].y, poly[i].z);
1058 * Test whether the polygon is convex.
1060 bool SpotShadow::testConvex(const Vector2* polygon, int polygonLength,
1062 bool isConvex = true;
1063 for (int i = 0; i < polygonLength; i++) {
1064 Vector2 start = polygon[i];
1065 Vector2 middle = polygon[(i + 1) % polygonLength];
1066 Vector2 end = polygon[(i + 2) % polygonLength];
1068 float delta = (float(middle.x) - start.x) * (float(end.y) - start.y) -
1069 (float(middle.y) - start.y) * (float(end.x) - start.x);
1070 bool isCCWOrCoLinear = (delta >= EPSILON);
1072 if (isCCWOrCoLinear) {
1073 ALOGW("(Error Type 2): polygon (%s) is not a convex b/c start (x %f, y %f),"
1074 "middle (x %f, y %f) and end (x %f, y %f) , delta is %f !!!",
1075 name, start.x, start.y, middle.x, middle.y, end.x, end.y, delta);
1084 * Test whether or not the polygon (intersection) is within the 2 input polygons.
1085 * Using Marte Carlo method, we generate a random point, and if it is inside the
1086 * intersection, then it must be inside both source polygons.
1088 void SpotShadow::testIntersection(const Vector2* poly1, int poly1Length,
1089 const Vector2* poly2, int poly2Length,
1090 const Vector2* intersection, int intersectionLength) {
1091 // Find the min and max of x and y.
1092 Vector2 lowerBound = {FLT_MAX, FLT_MAX};
1093 Vector2 upperBound = {-FLT_MAX, -FLT_MAX};
1094 for (int i = 0; i < poly1Length; i++) {
1095 updateBound(poly1[i], lowerBound, upperBound);
1097 for (int i = 0; i < poly2Length; i++) {
1098 updateBound(poly2[i], lowerBound, upperBound);
1101 bool dumpPoly = false;
1102 for (int k = 0; k < TEST_POINT_NUMBER; k++) {
1103 // Generate a random point between minX, minY and maxX, maxY.
1104 float randomX = rand() / float(RAND_MAX);
1105 float randomY = rand() / float(RAND_MAX);
1108 testPoint.x = lowerBound.x + randomX * (upperBound.x - lowerBound.x);
1109 testPoint.y = lowerBound.y + randomY * (upperBound.y - lowerBound.y);
1111 // If the random point is in both poly 1 and 2, then it must be intersection.
1112 if (testPointInsidePolygon(testPoint, intersection, intersectionLength)) {
1113 if (!testPointInsidePolygon(testPoint, poly1, poly1Length)) {
1115 ALOGW("(Error Type 1): one point (%f, %f) in the intersection is"
1116 " not in the poly1",
1117 testPoint.x, testPoint.y);
1120 if (!testPointInsidePolygon(testPoint, poly2, poly2Length)) {
1122 ALOGW("(Error Type 1): one point (%f, %f) in the intersection is"
1123 " not in the poly2",
1124 testPoint.x, testPoint.y);
1130 dumpPolygon(intersection, intersectionLength, "intersection");
1131 for (int i = 1; i < intersectionLength; i++) {
1132 Vector2 delta = intersection[i] - intersection[i - 1];
1133 ALOGD("Intersetion i, %d Vs i-1 is delta %f", i, delta.lengthSquared());
1136 dumpPolygon(poly1, poly1Length, "poly 1");
1137 dumpPolygon(poly2, poly2Length, "poly 2");
1142 }; // namespace uirenderer
1143 }; // namespace android