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 #define LOG_TAG "OpenGLRenderer"
19 // The highest z value can't be higher than (CASTER_Z_CAP_RATIO * light.z)
20 #define CASTER_Z_CAP_RATIO 0.95f
22 // When there is no umbra, then just fake the umbra using
23 // centroid * (1 - FAKE_UMBRA_SIZE_RATIO) + outline * FAKE_UMBRA_SIZE_RATIO
24 #define FAKE_UMBRA_SIZE_RATIO 0.05f
26 // When the polygon is about 90 vertices, the penumbra + umbra can reach 270 rays.
27 // That is consider pretty fine tessllated polygon so far.
28 // This is just to prevent using too much some memory when edge slicing is not
30 #define FINE_TESSELLATED_POLYGON_RAY_NUMBER 270
32 * Extra vertices for the corner for smoother corner.
33 * Only for outer loop.
34 * Note that we use such extra memory to avoid an extra loop.
36 // For half circle, we could add EXTRA_VERTEX_PER_PI vertices.
37 // Set to 1 if we don't want to have any.
38 #define SPOT_EXTRA_CORNER_VERTEX_PER_PI 18
40 // For the whole polygon, the sum of all the deltas b/t normals is 2 * M_PI,
41 // therefore, the maximum number of extra vertices will be twice bigger.
42 #define SPOT_MAX_EXTRA_CORNER_VERTEX_NUMBER (2 * SPOT_EXTRA_CORNER_VERTEX_PER_PI)
44 // For each RADIANS_DIVISOR, we would allocate one more vertex b/t the normals.
45 #define SPOT_CORNER_RADIANS_DIVISOR (M_PI / SPOT_EXTRA_CORNER_VERTEX_PER_PI)
50 #include <utils/Log.h>
52 #include "ShadowTessellator.h"
53 #include "SpotShadow.h"
55 #include "VertexBuffer.h"
56 #include "utils/MathUtils.h"
58 // TODO: After we settle down the new algorithm, we can remove the old one and
59 // its utility functions.
60 // Right now, we still need to keep it for comparison purpose and future expansion.
62 namespace uirenderer {
64 static const float EPSILON = 1e-7;
67 * For each polygon's vertex, the light center will project it to the receiver
68 * as one of the outline vertex.
69 * For each outline vertex, we need to store the position and normal.
70 * Normal here is defined against the edge by the current vertex and the next vertex.
79 * For each vertex, we need to keep track of its angle, whether it is penumbra or
80 * umbra, and its corresponding vertex index.
82 struct SpotShadow::VertexAngleData {
83 // The angle to the vertex from the centroid.
85 // True is the vertex comes from penumbra, otherwise it comes from umbra.
87 // The index of the vertex described by this data.
89 void set(float angle, bool isPenumbra, int index) {
91 mIsPenumbra = isPenumbra;
97 * Calculate the angle between and x and a y coordinate.
98 * The atan2 range from -PI to PI.
100 static float angle(const Vector2& point, const Vector2& center) {
101 return atan2(point.y - center.y, point.x - center.x);
105 * Calculate the intersection of a ray with the line segment defined by two points.
107 * Returns a negative value in error conditions.
109 * @param rayOrigin The start of the ray
110 * @param dx The x vector of the ray
111 * @param dy The y vector of the ray
112 * @param p1 The first point defining the line segment
113 * @param p2 The second point defining the line segment
114 * @return The distance along the ray if it intersects with the line segment, negative if otherwise
116 static float rayIntersectPoints(const Vector2& rayOrigin, float dx, float dy,
117 const Vector2& p1, const Vector2& p2) {
118 // The math below is derived from solving this formula, basically the
119 // intersection point should stay on both the ray and the edge of (p1, p2).
120 // solve([p1x+t*(p2x-p1x)=dx*t2+px,p1y+t*(p2y-p1y)=dy*t2+py],[t,t2]);
122 float divisor = (dx * (p1.y - p2.y) + dy * p2.x - dy * p1.x);
123 if (divisor == 0) return -1.0f; // error, invalid divisor
126 float interpVal = (dx * (p1.y - rayOrigin.y) + dy * rayOrigin.x - dy * p1.x) / divisor;
127 if (interpVal < 0 || interpVal > 1) {
128 ALOGW("rayIntersectPoints is hitting outside the segment %f", interpVal);
132 float distance = (p1.x * (rayOrigin.y - p2.y) + p2.x * (p1.y - rayOrigin.y) +
133 rayOrigin.x * (p2.y - p1.y)) / divisor;
135 return distance; // may be negative in error cases
139 * Sort points by their X coordinates
141 * @param points the points as a Vector2 array.
142 * @param pointsLength the number of vertices of the polygon.
144 void SpotShadow::xsort(Vector2* points, int pointsLength) {
145 quicksortX(points, 0, pointsLength - 1);
149 * compute the convex hull of a collection of Points
151 * @param points the points as a Vector2 array.
152 * @param pointsLength the number of vertices of the polygon.
153 * @param retPoly pre allocated array of floats to put the vertices
154 * @return the number of points in the polygon 0 if no intersection
156 int SpotShadow::hull(Vector2* points, int pointsLength, Vector2* retPoly) {
157 xsort(points, pointsLength);
158 int n = pointsLength;
160 lUpper[0] = points[0];
161 lUpper[1] = points[1];
165 for (int i = 2; i < n; i++) {
166 lUpper[lUpperSize] = points[i];
169 while (lUpperSize > 2 && !ccw(
170 lUpper[lUpperSize - 3].x, lUpper[lUpperSize - 3].y,
171 lUpper[lUpperSize - 2].x, lUpper[lUpperSize - 2].y,
172 lUpper[lUpperSize - 1].x, lUpper[lUpperSize - 1].y)) {
173 // Remove the middle point of the three last
174 lUpper[lUpperSize - 2].x = lUpper[lUpperSize - 1].x;
175 lUpper[lUpperSize - 2].y = lUpper[lUpperSize - 1].y;
181 lLower[0] = points[n - 1];
182 lLower[1] = points[n - 2];
186 for (int i = n - 3; i >= 0; i--) {
187 lLower[lLowerSize] = points[i];
190 while (lLowerSize > 2 && !ccw(
191 lLower[lLowerSize - 3].x, lLower[lLowerSize - 3].y,
192 lLower[lLowerSize - 2].x, lLower[lLowerSize - 2].y,
193 lLower[lLowerSize - 1].x, lLower[lLowerSize - 1].y)) {
194 // Remove the middle point of the three last
195 lLower[lLowerSize - 2] = lLower[lLowerSize - 1];
200 // output points in CW ordering
201 const int total = lUpperSize + lLowerSize - 2;
202 int outIndex = total - 1;
203 for (int i = 0; i < lUpperSize; i++) {
204 retPoly[outIndex] = lUpper[i];
208 for (int i = 1; i < lLowerSize - 1; i++) {
209 retPoly[outIndex] = lLower[i];
212 // TODO: Add test harness which verify that all the points are inside the hull.
217 * Test whether the 3 points form a counter clockwise turn.
219 * @return true if a right hand turn
221 bool SpotShadow::ccw(float ax, float ay, float bx, float by,
222 float cx, float cy) {
223 return (bx - ax) * (cy - ay) - (by - ay) * (cx - ax) > EPSILON;
227 * Sort points about a center point
229 * @param poly The in and out polyogon as a Vector2 array.
230 * @param polyLength The number of vertices of the polygon.
231 * @param center the center ctr[0] = x , ctr[1] = y to sort around.
233 void SpotShadow::sort(Vector2* poly, int polyLength, const Vector2& center) {
234 quicksortCirc(poly, 0, polyLength - 1, center);
238 * Swap points pointed to by i and j
240 void SpotShadow::swap(Vector2* points, int i, int j) {
241 Vector2 temp = points[i];
242 points[i] = points[j];
247 * quick sort implementation about the center.
249 void SpotShadow::quicksortCirc(Vector2* points, int low, int high,
250 const Vector2& center) {
251 int i = low, j = high;
252 int p = low + (high - low) / 2;
253 float pivot = angle(points[p], center);
255 while (angle(points[i], center) > pivot) {
258 while (angle(points[j], center) < pivot) {
268 if (low < j) quicksortCirc(points, low, j, center);
269 if (i < high) quicksortCirc(points, i, high, center);
273 * Sort points by x axis
275 * @param points points to sort
276 * @param low start index
277 * @param high end index
279 void SpotShadow::quicksortX(Vector2* points, int low, int high) {
280 int i = low, j = high;
281 int p = low + (high - low) / 2;
282 float pivot = points[p].x;
284 while (points[i].x < pivot) {
287 while (points[j].x > pivot) {
297 if (low < j) quicksortX(points, low, j);
298 if (i < high) quicksortX(points, i, high);
302 * Test whether a point is inside the polygon.
304 * @param testPoint the point to test
305 * @param poly the polygon
306 * @return true if the testPoint is inside the poly.
308 bool SpotShadow::testPointInsidePolygon(const Vector2 testPoint,
309 const Vector2* poly, int len) {
311 float testx = testPoint.x;
312 float testy = testPoint.y;
313 for (int i = 0, j = len - 1; i < len; j = i++) {
314 float startX = poly[j].x;
315 float startY = poly[j].y;
316 float endX = poly[i].x;
317 float endY = poly[i].y;
319 if (((endY > testy) != (startY > testy))
320 && (testx < (startX - endX) * (testy - endY)
321 / (startY - endY) + endX)) {
329 * Make the polygon turn clockwise.
331 * @param polygon the polygon as a Vector2 array.
332 * @param len the number of points of the polygon
334 void SpotShadow::makeClockwise(Vector2* polygon, int len) {
335 if (polygon == nullptr || len == 0) {
338 if (!ShadowTessellator::isClockwise(polygon, len)) {
339 reverse(polygon, len);
344 * Reverse the polygon
346 * @param polygon the polygon as a Vector2 array
347 * @param len the number of points of the polygon
349 void SpotShadow::reverse(Vector2* polygon, int len) {
351 for (int i = 0; i < n; i++) {
352 Vector2 tmp = polygon[i];
354 polygon[i] = polygon[k];
360 * Compute a horizontal circular polygon about point (x , y , height) of radius
363 * @param points number of the points of the output polygon.
364 * @param lightCenter the center of the light.
365 * @param size the light size.
366 * @param ret result polygon.
368 void SpotShadow::computeLightPolygon(int points, const Vector3& lightCenter,
369 float size, Vector3* ret) {
370 // TODO: Caching all the sin / cos values and store them in a look up table.
371 for (int i = 0; i < points; i++) {
372 float angle = 2 * i * M_PI / points;
373 ret[i].x = cosf(angle) * size + lightCenter.x;
374 ret[i].y = sinf(angle) * size + lightCenter.y;
375 ret[i].z = lightCenter.z;
380 * From light center, project one vertex to the z=0 surface and get the outline.
382 * @param outline The result which is the outline position.
383 * @param lightCenter The center of light.
384 * @param polyVertex The input polygon's vertex.
386 * @return float The ratio of (polygon.z / light.z - polygon.z)
388 float SpotShadow::projectCasterToOutline(Vector2& outline,
389 const Vector3& lightCenter, const Vector3& polyVertex) {
390 float lightToPolyZ = lightCenter.z - polyVertex.z;
391 float ratioZ = CASTER_Z_CAP_RATIO;
392 if (lightToPolyZ != 0) {
393 // If any caster's vertex is almost above the light, we just keep it as 95%
394 // of the height of the light.
395 ratioZ = MathUtils::clamp(polyVertex.z / lightToPolyZ, 0.0f, CASTER_Z_CAP_RATIO);
398 outline.x = polyVertex.x - ratioZ * (lightCenter.x - polyVertex.x);
399 outline.y = polyVertex.y - ratioZ * (lightCenter.y - polyVertex.y);
404 * Generate the shadow spot light of shape lightPoly and a object poly
406 * @param isCasterOpaque whether the caster is opaque
407 * @param lightCenter the center of the light
408 * @param lightSize the radius of the light
409 * @param poly x,y,z vertexes of a convex polygon that occludes the light source
410 * @param polyLength number of vertexes of the occluding polygon
411 * @param shadowTriangleStrip return an (x,y,alpha) triangle strip representing the shadow. Return
412 * empty strip if error.
414 void SpotShadow::createSpotShadow(bool isCasterOpaque, const Vector3& lightCenter,
415 float lightSize, const Vector3* poly, int polyLength, const Vector3& polyCentroid,
416 VertexBuffer& shadowTriangleStrip) {
417 if (CC_UNLIKELY(lightCenter.z <= 0)) {
418 ALOGW("Relative Light Z is not positive. No spot shadow!");
421 if (CC_UNLIKELY(polyLength < 3)) {
423 ALOGW("Invalid polygon length. No spot shadow!");
427 OutlineData outlineData[polyLength];
428 Vector2 outlineCentroid;
429 // Calculate the projected outline for each polygon's vertices from the light center.
437 // O Outline vertices
439 // Ratio = (Poly - Outline) / (Light - Poly)
440 // Outline.x = Poly.x - Ratio * (Light.x - Poly.x)
441 // Outline's radius / Light's radius = Ratio
443 // Compute the last outline vertex to make sure we can get the normal and outline
444 // in one single loop.
445 projectCasterToOutline(outlineData[polyLength - 1].position, lightCenter,
446 poly[polyLength - 1]);
448 // Take the outline's polygon, calculate the normal for each outline edge.
449 int currentNormalIndex = polyLength - 1;
450 int nextNormalIndex = 0;
452 for (int i = 0; i < polyLength; i++) {
453 float ratioZ = projectCasterToOutline(outlineData[i].position,
454 lightCenter, poly[i]);
455 outlineData[i].radius = ratioZ * lightSize;
457 outlineData[currentNormalIndex].normal = ShadowTessellator::calculateNormal(
458 outlineData[currentNormalIndex].position,
459 outlineData[nextNormalIndex].position);
460 currentNormalIndex = (currentNormalIndex + 1) % polyLength;
464 projectCasterToOutline(outlineCentroid, lightCenter, polyCentroid);
466 int penumbraIndex = 0;
467 // Then each polygon's vertex produce at minmal 2 penumbra vertices.
468 // Since the size can be dynamic here, we keep track of the size and update
469 // the real size at the end.
470 int allocatedPenumbraLength = 2 * polyLength + SPOT_MAX_EXTRA_CORNER_VERTEX_NUMBER;
471 Vector2 penumbra[allocatedPenumbraLength];
472 int totalExtraCornerSliceNumber = 0;
474 Vector2 umbra[polyLength];
476 // When centroid is covered by all circles from outline, then we consider
477 // the umbra is invalid, and we will tune down the shadow strength.
478 bool hasValidUmbra = true;
479 // We need the minimal of RaitoVI to decrease the spot shadow strength accordingly.
480 float minRaitoVI = FLT_MAX;
482 for (int i = 0; i < polyLength; i++) {
483 // Generate all the penumbra's vertices only using the (outline vertex + normal * radius)
484 // There is no guarantee that the penumbra is still convex, but for
485 // each outline vertex, it will connect to all its corresponding penumbra vertices as
486 // triangle fans. And for neighber penumbra vertex, it will be a trapezoid.
488 // Penumbra Vertices marked as Pi
489 // Outline Vertices marked as Vi
494 // (P0) ------------------------------------------------(P5)
504 // (V3)-----------------------------------(V2)
505 int preNormalIndex = (i + polyLength - 1) % polyLength;
507 const Vector2& previousNormal = outlineData[preNormalIndex].normal;
508 const Vector2& currentNormal = outlineData[i].normal;
510 // Depending on how roundness we want for each corner, we can subdivide
511 // further here and/or introduce some heuristic to decide how much the
512 // subdivision should be.
513 int currentExtraSliceNumber = ShadowTessellator::getExtraVertexNumber(
514 previousNormal, currentNormal, SPOT_CORNER_RADIANS_DIVISOR);
516 int currentCornerSliceNumber = 1 + currentExtraSliceNumber;
517 totalExtraCornerSliceNumber += currentExtraSliceNumber;
519 ALOGD("currentExtraSliceNumber should be %d", currentExtraSliceNumber);
520 ALOGD("currentCornerSliceNumber should be %d", currentCornerSliceNumber);
521 ALOGD("totalCornerSliceNumber is %d", totalExtraCornerSliceNumber);
523 if (CC_UNLIKELY(totalExtraCornerSliceNumber > SPOT_MAX_EXTRA_CORNER_VERTEX_NUMBER)) {
524 currentCornerSliceNumber = 1;
526 for (int k = 0; k <= currentCornerSliceNumber; k++) {
528 (previousNormal * (currentCornerSliceNumber - k) + currentNormal * k) /
529 currentCornerSliceNumber;
530 avgNormal.normalize();
531 penumbra[penumbraIndex++] = outlineData[i].position +
532 avgNormal * outlineData[i].radius;
536 // Compute the umbra by the intersection from the outline's centroid!
538 // (V) ------------------------------------
548 // ------------------------------------
550 // Connect a line b/t the outline vertex (V) and the centroid (C), it will
551 // intersect with the outline vertex's circle at point (I).
552 // Now, ratioVI = VI / VC, ratioIC = IC / VC
553 // Then the intersetion point can be computed as Ixy = Vxy * ratioIC + Cxy * ratioVI;
555 // When all of the outline circles cover the the outline centroid, (like I is
556 // on the other side of C), there is no real umbra any more, so we just fake
557 // a small area around the centroid as the umbra, and tune down the spot
558 // shadow's umbra strength to simulate the effect the whole shadow will
559 // become lighter in this case.
560 // The ratio can be simulated by using the inverse of maximum of ratioVI for
562 float distOutline = (outlineData[i].position - outlineCentroid).length();
563 if (CC_UNLIKELY(distOutline == 0)) {
564 // If the outline has 0 area, then there is no spot shadow anyway.
565 ALOGW("Outline has 0 area, no spot shadow!");
569 float ratioVI = outlineData[i].radius / distOutline;
570 minRaitoVI = MathUtils::min(minRaitoVI, ratioVI);
571 if (ratioVI >= (1 - FAKE_UMBRA_SIZE_RATIO)) {
572 ratioVI = (1 - FAKE_UMBRA_SIZE_RATIO);
574 // When we know we don't have valid umbra, don't bother to compute the
575 // values below. But we can't skip the loop yet since we want to know the
577 float ratioIC = 1 - ratioVI;
578 umbra[i] = outlineData[i].position * ratioIC + outlineCentroid * ratioVI;
581 hasValidUmbra = (minRaitoVI <= 1.0);
582 float shadowStrengthScale = 1.0;
583 if (!hasValidUmbra) {
585 ALOGW("The object is too close to the light or too small, no real umbra!");
587 for (int i = 0; i < polyLength; i++) {
588 umbra[i] = outlineData[i].position * FAKE_UMBRA_SIZE_RATIO +
589 outlineCentroid * (1 - FAKE_UMBRA_SIZE_RATIO);
591 shadowStrengthScale = 1.0 / minRaitoVI;
594 int penumbraLength = penumbraIndex;
595 int umbraLength = polyLength;
598 ALOGD("penumbraLength is %d , allocatedPenumbraLength %d", penumbraLength, allocatedPenumbraLength);
599 dumpPolygon(poly, polyLength, "input poly");
600 dumpPolygon(penumbra, penumbraLength, "penumbra");
601 dumpPolygon(umbra, umbraLength, "umbra");
602 ALOGD("hasValidUmbra is %d and shadowStrengthScale is %f", hasValidUmbra, shadowStrengthScale);
605 // The penumbra and umbra needs to be in convex shape to keep consistency
607 // Since we are still shooting rays to penumbra, it needs to be convex.
608 // Umbra can be represented as a fan from the centroid, but visually umbra
609 // looks nicer when it is convex.
610 Vector2 finalUmbra[umbraLength];
611 Vector2 finalPenumbra[penumbraLength];
612 int finalUmbraLength = hull(umbra, umbraLength, finalUmbra);
613 int finalPenumbraLength = hull(penumbra, penumbraLength, finalPenumbra);
615 generateTriangleStrip(isCasterOpaque, shadowStrengthScale, finalPenumbra,
616 finalPenumbraLength, finalUmbra, finalUmbraLength, poly, polyLength,
617 shadowTriangleStrip, outlineCentroid);
622 * This is only for experimental purpose.
623 * After intersections are calculated, we could smooth the polygon if needed.
624 * So far, we don't think it is more appealing yet.
626 * @param level The level of smoothness.
627 * @param rays The total number of rays.
628 * @param rayDist (In and Out) The distance for each ray.
631 void SpotShadow::smoothPolygon(int level, int rays, float* rayDist) {
632 for (int k = 0; k < level; k++) {
633 for (int i = 0; i < rays; i++) {
634 float p1 = rayDist[(rays - 1 + i) % rays];
635 float p2 = rayDist[i];
636 float p3 = rayDist[(i + 1) % rays];
637 rayDist[i] = (p1 + p2 * 2 + p3) / 4;
642 // Index pair is meant for storing the tessellation information for the penumbra
643 // area. One index must come from exterior tangent of the circles, the other one
644 // must come from the interior tangent of the circles.
650 // For one penumbra vertex, find the cloest umbra vertex and return its index.
651 inline int getClosestUmbraIndex(const Vector2& pivot, const Vector2* polygon, int polygonLength) {
652 float minLengthSquared = FLT_MAX;
653 int resultIndex = -1;
654 bool hasDecreased = false;
655 // Starting with some negative offset, assuming both umbra and penumbra are starting
656 // at the same angle, this can help to find the result faster.
657 // Normally, loop 3 times, we can find the closest point.
658 int offset = polygonLength - 2;
659 for (int i = 0; i < polygonLength; i++) {
660 int currentIndex = (i + offset) % polygonLength;
661 float currentLengthSquared = (pivot - polygon[currentIndex]).lengthSquared();
662 if (currentLengthSquared < minLengthSquared) {
663 if (minLengthSquared != FLT_MAX) {
666 minLengthSquared = currentLengthSquared;
667 resultIndex = currentIndex;
668 } else if (currentLengthSquared > minLengthSquared && hasDecreased) {
669 // Early break b/c we have found the closet one and now the length
670 // is increasing again.
674 if(resultIndex == -1) {
675 ALOGE("resultIndex is -1, the polygon must be invalid!");
681 // Allow some epsilon here since the later ray intersection did allow for some small
682 // floating point error, when the intersection point is slightly outside the segment.
683 inline bool sameDirections(bool isPositiveCross, float a, float b) {
684 if (isPositiveCross) {
685 return a >= -EPSILON && b >= -EPSILON;
687 return a <= EPSILON && b <= EPSILON;
691 // Find the right polygon edge to shoot the ray at.
692 inline int findPolyIndex(bool isPositiveCross, int startPolyIndex, const Vector2& umbraDir,
693 const Vector2* polyToCentroid, int polyLength) {
694 // Make sure we loop with a bound.
695 for (int i = 0; i < polyLength; i++) {
696 int currentIndex = (i + startPolyIndex) % polyLength;
697 const Vector2& currentToCentroid = polyToCentroid[currentIndex];
698 const Vector2& nextToCentroid = polyToCentroid[(currentIndex + 1) % polyLength];
700 float currentCrossUmbra = currentToCentroid.cross(umbraDir);
701 float umbraCrossNext = umbraDir.cross(nextToCentroid);
702 if (sameDirections(isPositiveCross, currentCrossUmbra, umbraCrossNext)) {
704 ALOGD("findPolyIndex loop %d times , index %d", i, currentIndex );
709 LOG_ALWAYS_FATAL("Can't find the right polygon's edge from startPolyIndex %d", startPolyIndex);
713 // Generate the index pair for penumbra / umbra vertices, and more penumbra vertices
715 inline void genNewPenumbraAndPairWithUmbra(const Vector2* penumbra, int penumbraLength,
716 const Vector2* umbra, int umbraLength, Vector2* newPenumbra, int& newPenumbraIndex,
717 IndexPair* verticesPair, int& verticesPairIndex) {
718 // In order to keep everything in just one loop, we need to pre-compute the
719 // closest umbra vertex for the last penumbra vertex.
720 int previousClosestUmbraIndex = getClosestUmbraIndex(penumbra[penumbraLength - 1],
722 for (int i = 0; i < penumbraLength; i++) {
723 const Vector2& currentPenumbraVertex = penumbra[i];
724 // For current penumbra vertex, starting from previousClosestUmbraIndex,
725 // then check the next one until the distance increase.
726 // The last one before the increase is the umbra vertex we need to pair with.
727 float currentLengthSquared =
728 (currentPenumbraVertex - umbra[previousClosestUmbraIndex]).lengthSquared();
729 int currentClosestUmbraIndex = previousClosestUmbraIndex;
731 for (int j = 1; j < umbraLength; j++) {
732 int newUmbraIndex = (previousClosestUmbraIndex + j) % umbraLength;
733 float newLengthSquared = (currentPenumbraVertex - umbra[newUmbraIndex]).lengthSquared();
734 if (newLengthSquared > currentLengthSquared) {
735 // currentClosestUmbraIndex is the umbra vertex's index which has
736 // currently found smallest distance, so we can simply break here.
739 currentLengthSquared = newLengthSquared;
741 currentClosestUmbraIndex = newUmbraIndex;
745 if (indexDelta > 1) {
746 // For those umbra don't have penumbra, generate new penumbra vertices by interpolation.
748 // Assuming Pi for penumbra vertices, and Ui for umbra vertices.
749 // In the case like below P1 paired with U1 and P2 paired with U5.
750 // U2 to U4 are unpaired umbra vertices.
756 // We will need to generate 3 more penumbra vertices P1.1, P1.2, P1.3
757 // to pair with U2 to U4.
759 // P1 P1.1 P1.2 P1.3 P2
763 // That distance ratio b/t Ui to U1 and Ui to U5 decides its paired penumbra
764 // vertex's location.
765 int newPenumbraNumber = indexDelta - 1;
767 float accumulatedDeltaLength[newPenumbraNumber];
768 float totalDeltaLength = 0;
770 // To save time, cache the previous umbra vertex info outside the loop
771 // and update each loop.
772 Vector2 previousClosestUmbra = umbra[previousClosestUmbraIndex];
773 Vector2 skippedUmbra;
774 // Use umbra data to precompute the length b/t unpaired umbra vertices,
775 // and its ratio against the total length.
776 for (int k = 0; k < indexDelta; k++) {
777 int skippedUmbraIndex = (previousClosestUmbraIndex + k + 1) % umbraLength;
778 skippedUmbra = umbra[skippedUmbraIndex];
779 float currentDeltaLength = (skippedUmbra - previousClosestUmbra).length();
781 totalDeltaLength += currentDeltaLength;
782 accumulatedDeltaLength[k] = totalDeltaLength;
784 previousClosestUmbra = skippedUmbra;
787 const Vector2& previousPenumbra = penumbra[(i + penumbraLength - 1) % penumbraLength];
788 // Then for each unpaired umbra vertex, create a new penumbra by the ratio,
789 // and pair them togehter.
790 for (int k = 0; k < newPenumbraNumber; k++) {
791 float weightForCurrentPenumbra = 1.0f;
792 if (totalDeltaLength != 0.0f) {
793 weightForCurrentPenumbra = accumulatedDeltaLength[k] / totalDeltaLength;
795 float weightForPreviousPenumbra = 1.0f - weightForCurrentPenumbra;
797 Vector2 interpolatedPenumbra = currentPenumbraVertex * weightForCurrentPenumbra +
798 previousPenumbra * weightForPreviousPenumbra;
800 int skippedUmbraIndex = (previousClosestUmbraIndex + k + 1) % umbraLength;
801 verticesPair[verticesPairIndex].outerIndex = newPenumbraIndex;
802 verticesPair[verticesPairIndex].innerIndex = skippedUmbraIndex;
804 newPenumbra[newPenumbraIndex++] = interpolatedPenumbra;
807 verticesPair[verticesPairIndex].outerIndex = newPenumbraIndex;
808 verticesPair[verticesPairIndex].innerIndex = currentClosestUmbraIndex;
810 newPenumbra[newPenumbraIndex++] = currentPenumbraVertex;
812 previousClosestUmbraIndex = currentClosestUmbraIndex;
816 // Precompute all the polygon's vector, return true if the reference cross product is positive.
817 inline bool genPolyToCentroid(const Vector2* poly2d, int polyLength,
818 const Vector2& centroid, Vector2* polyToCentroid) {
819 for (int j = 0; j < polyLength; j++) {
820 polyToCentroid[j] = poly2d[j] - centroid;
821 // Normalize these vectors such that we can use epsilon comparison after
822 // computing their cross products with another normalized vector.
823 polyToCentroid[j].normalize();
825 float refCrossProduct = 0;
826 for (int j = 0; j < polyLength; j++) {
827 refCrossProduct = polyToCentroid[j].cross(polyToCentroid[(j + 1) % polyLength]);
828 if (refCrossProduct != 0) {
833 return refCrossProduct > 0;
836 // For one umbra vertex, shoot an ray from centroid to it.
837 // If the ray hit the polygon first, then return the intersection point as the
839 inline Vector2 getCloserVertex(const Vector2& umbraVertex, const Vector2& centroid,
840 const Vector2* poly2d, int polyLength, const Vector2* polyToCentroid,
841 bool isPositiveCross, int& previousPolyIndex) {
842 Vector2 umbraToCentroid = umbraVertex - centroid;
843 float distanceToUmbra = umbraToCentroid.length();
844 umbraToCentroid = umbraToCentroid / distanceToUmbra;
846 // previousPolyIndex is updated for each item such that we can minimize the
847 // looping inside findPolyIndex();
848 previousPolyIndex = findPolyIndex(isPositiveCross, previousPolyIndex,
849 umbraToCentroid, polyToCentroid, polyLength);
851 float dx = umbraToCentroid.x;
852 float dy = umbraToCentroid.y;
853 float distanceToIntersectPoly = rayIntersectPoints(centroid, dx, dy,
854 poly2d[previousPolyIndex], poly2d[(previousPolyIndex + 1) % polyLength]);
855 if (distanceToIntersectPoly < 0) {
856 distanceToIntersectPoly = 0;
859 // Pick the closer one as the occluded area vertex.
860 Vector2 closerVertex;
861 if (distanceToIntersectPoly < distanceToUmbra) {
862 closerVertex.x = centroid.x + dx * distanceToIntersectPoly;
863 closerVertex.y = centroid.y + dy * distanceToIntersectPoly;
865 closerVertex = umbraVertex;
872 * Generate a triangle strip given two convex polygon
874 void SpotShadow::generateTriangleStrip(bool isCasterOpaque, float shadowStrengthScale,
875 Vector2* penumbra, int penumbraLength, Vector2* umbra, int umbraLength,
876 const Vector3* poly, int polyLength, VertexBuffer& shadowTriangleStrip,
877 const Vector2& centroid) {
878 bool hasOccludedUmbraArea = false;
879 Vector2 poly2d[polyLength];
881 if (isCasterOpaque) {
882 for (int i = 0; i < polyLength; i++) {
883 poly2d[i].x = poly[i].x;
884 poly2d[i].y = poly[i].y;
886 // Make sure the centroid is inside the umbra, otherwise, fall back to the
887 // approach as if there is no occluded umbra area.
888 if (testPointInsidePolygon(centroid, poly2d, polyLength)) {
889 hasOccludedUmbraArea = true;
893 // For each penumbra vertex, find its corresponding closest umbra vertex index.
895 // Penumbra Vertices marked as Pi
896 // Umbra Vertices marked as Ui
901 // (P0) ------------------------------------------------(P5)
911 // (U4)-----------------------------------(U3) (P6)
913 // At least, like P0, P1, P2, they will find the matching umbra as U0.
914 // If we jump over some umbra vertex without matching penumbra vertex, then
915 // we will generate some new penumbra vertex by interpolation. Like P6 is
916 // matching U3, but U2 is not matched with any penumbra vertex.
917 // So interpolate P5.1 out and match U2.
918 // In this way, every umbra vertex will have a matching penumbra vertex.
920 // The total pair number can be as high as umbraLength + penumbraLength.
921 const int maxNewPenumbraLength = umbraLength + penumbraLength;
922 IndexPair verticesPair[maxNewPenumbraLength];
923 int verticesPairIndex = 0;
925 // Cache all the existing penumbra vertices and newly interpolated vertices into a
927 Vector2 newPenumbra[maxNewPenumbraLength];
928 int newPenumbraIndex = 0;
930 // For each penumbra vertex, find its closet umbra vertex by comparing the
931 // neighbor umbra vertices.
932 genNewPenumbraAndPairWithUmbra(penumbra, penumbraLength, umbra, umbraLength, newPenumbra,
933 newPenumbraIndex, verticesPair, verticesPairIndex);
934 ShadowTessellator::checkOverflow(verticesPairIndex, maxNewPenumbraLength, "Spot pair");
935 ShadowTessellator::checkOverflow(newPenumbraIndex, maxNewPenumbraLength, "Spot new penumbra");
937 for (int i = 0; i < umbraLength; i++) {
938 ALOGD("umbra i %d, [%f, %f]", i, umbra[i].x, umbra[i].y);
940 for (int i = 0; i < newPenumbraIndex; i++) {
941 ALOGD("new penumbra i %d, [%f, %f]", i, newPenumbra[i].x, newPenumbra[i].y);
943 for (int i = 0; i < verticesPairIndex; i++) {
944 ALOGD("index i %d, [%d, %d]", i, verticesPair[i].outerIndex, verticesPair[i].innerIndex);
948 // For the size of vertex buffer, we need 3 rings, one has newPenumbraSize,
949 // one has umbraLength, the last one has at most umbraLength.
951 // For the size of index buffer, the umbra area needs (2 * umbraLength + 2).
952 // The penumbra one can vary a bit, but it is bounded by (2 * verticesPairIndex + 2).
953 // And 2 more for jumping between penumbra to umbra.
954 const int newPenumbraLength = newPenumbraIndex;
955 const int totalVertexCount = newPenumbraLength + umbraLength * 2;
956 const int totalIndexCount = 2 * umbraLength + 2 * verticesPairIndex + 6;
957 AlphaVertex* shadowVertices =
958 shadowTriangleStrip.alloc<AlphaVertex>(totalVertexCount);
959 uint16_t* indexBuffer =
960 shadowTriangleStrip.allocIndices<uint16_t>(totalIndexCount);
961 int vertexBufferIndex = 0;
962 int indexBufferIndex = 0;
964 // Fill the IB and VB for the penumbra area.
965 for (int i = 0; i < newPenumbraLength; i++) {
966 AlphaVertex::set(&shadowVertices[vertexBufferIndex++], newPenumbra[i].x,
967 newPenumbra[i].y, 0.0f);
969 for (int i = 0; i < umbraLength; i++) {
970 AlphaVertex::set(&shadowVertices[vertexBufferIndex++], umbra[i].x, umbra[i].y,
974 for (int i = 0; i < verticesPairIndex; i++) {
975 indexBuffer[indexBufferIndex++] = verticesPair[i].outerIndex;
976 // All umbra index need to be offseted by newPenumbraSize.
977 indexBuffer[indexBufferIndex++] = verticesPair[i].innerIndex + newPenumbraLength;
979 indexBuffer[indexBufferIndex++] = verticesPair[0].outerIndex;
980 indexBuffer[indexBufferIndex++] = verticesPair[0].innerIndex + newPenumbraLength;
982 // Now fill the IB and VB for the umbra area.
983 // First duplicated the index from previous strip and the first one for the
984 // degenerated triangles.
985 indexBuffer[indexBufferIndex] = indexBuffer[indexBufferIndex - 1];
987 indexBuffer[indexBufferIndex++] = newPenumbraLength + 0;
988 // Save the first VB index for umbra area in order to close the loop.
989 int savedStartIndex = vertexBufferIndex;
991 if (hasOccludedUmbraArea) {
992 // Precompute all the polygon's vector, and the reference cross product,
993 // in order to find the right polygon edge for the ray to intersect.
994 Vector2 polyToCentroid[polyLength];
995 bool isPositiveCross = genPolyToCentroid(poly2d, polyLength, centroid, polyToCentroid);
997 // Because both the umbra and polygon are going in the same direction,
998 // we can save the previous polygon index to make sure we have less polygon
999 // vertex to compute for each ray.
1000 int previousPolyIndex = 0;
1001 for (int i = 0; i < umbraLength; i++) {
1002 // Shoot a ray from centroid to each umbra vertices and pick the one with
1003 // shorter distance to the centroid, b/t the umbra vertex or the intersection point.
1004 Vector2 closerVertex = getCloserVertex(umbra[i], centroid, poly2d, polyLength,
1005 polyToCentroid, isPositiveCross, previousPolyIndex);
1007 // We already stored the umbra vertices, just need to add the occlued umbra's ones.
1008 indexBuffer[indexBufferIndex++] = newPenumbraLength + i;
1009 indexBuffer[indexBufferIndex++] = vertexBufferIndex;
1010 AlphaVertex::set(&shadowVertices[vertexBufferIndex++],
1011 closerVertex.x, closerVertex.y, M_PI);
1014 // If there is no occluded umbra at all, then draw the triangle fan
1015 // starting from the centroid to all umbra vertices.
1016 int lastCentroidIndex = vertexBufferIndex;
1017 AlphaVertex::set(&shadowVertices[vertexBufferIndex++], centroid.x,
1019 for (int i = 0; i < umbraLength; i++) {
1020 indexBuffer[indexBufferIndex++] = newPenumbraLength + i;
1021 indexBuffer[indexBufferIndex++] = lastCentroidIndex;
1024 // Closing the umbra area triangle's loop here.
1025 indexBuffer[indexBufferIndex++] = newPenumbraLength;
1026 indexBuffer[indexBufferIndex++] = savedStartIndex;
1028 // At the end, update the real index and vertex buffer size.
1029 shadowTriangleStrip.updateVertexCount(vertexBufferIndex);
1030 shadowTriangleStrip.updateIndexCount(indexBufferIndex);
1031 ShadowTessellator::checkOverflow(vertexBufferIndex, totalVertexCount, "Spot Vertex Buffer");
1032 ShadowTessellator::checkOverflow(indexBufferIndex, totalIndexCount, "Spot Index Buffer");
1034 shadowTriangleStrip.setMeshFeatureFlags(VertexBuffer::kAlpha | VertexBuffer::kIndices);
1035 shadowTriangleStrip.computeBounds<AlphaVertex>();
1040 #define TEST_POINT_NUMBER 128
1042 * Calculate the bounds for generating random test points.
1044 void SpotShadow::updateBound(const Vector2 inVector, Vector2& lowerBound,
1045 Vector2& upperBound) {
1046 if (inVector.x < lowerBound.x) {
1047 lowerBound.x = inVector.x;
1050 if (inVector.y < lowerBound.y) {
1051 lowerBound.y = inVector.y;
1054 if (inVector.x > upperBound.x) {
1055 upperBound.x = inVector.x;
1058 if (inVector.y > upperBound.y) {
1059 upperBound.y = inVector.y;
1064 * For debug purpose, when things go wrong, dump the whole polygon data.
1066 void SpotShadow::dumpPolygon(const Vector2* poly, int polyLength, const char* polyName) {
1067 for (int i = 0; i < polyLength; i++) {
1068 ALOGD("polygon %s i %d x %f y %f", polyName, i, poly[i].x, poly[i].y);
1073 * For debug purpose, when things go wrong, dump the whole polygon data.
1075 void SpotShadow::dumpPolygon(const Vector3* poly, int polyLength, const char* polyName) {
1076 for (int i = 0; i < polyLength; i++) {
1077 ALOGD("polygon %s i %d x %f y %f", polyName, i, poly[i].x, poly[i].y);
1082 * Test whether the polygon is convex.
1084 bool SpotShadow::testConvex(const Vector2* polygon, int polygonLength,
1086 bool isConvex = true;
1087 for (int i = 0; i < polygonLength; i++) {
1088 Vector2 start = polygon[i];
1089 Vector2 middle = polygon[(i + 1) % polygonLength];
1090 Vector2 end = polygon[(i + 2) % polygonLength];
1092 float delta = (float(middle.x) - start.x) * (float(end.y) - start.y) -
1093 (float(middle.y) - start.y) * (float(end.x) - start.x);
1094 bool isCCWOrCoLinear = (delta >= EPSILON);
1096 if (isCCWOrCoLinear) {
1097 ALOGW("(Error Type 2): polygon (%s) is not a convex b/c start (x %f, y %f),"
1098 "middle (x %f, y %f) and end (x %f, y %f) , delta is %f !!!",
1099 name, start.x, start.y, middle.x, middle.y, end.x, end.y, delta);
1108 * Test whether or not the polygon (intersection) is within the 2 input polygons.
1109 * Using Marte Carlo method, we generate a random point, and if it is inside the
1110 * intersection, then it must be inside both source polygons.
1112 void SpotShadow::testIntersection(const Vector2* poly1, int poly1Length,
1113 const Vector2* poly2, int poly2Length,
1114 const Vector2* intersection, int intersectionLength) {
1115 // Find the min and max of x and y.
1116 Vector2 lowerBound = {FLT_MAX, FLT_MAX};
1117 Vector2 upperBound = {-FLT_MAX, -FLT_MAX};
1118 for (int i = 0; i < poly1Length; i++) {
1119 updateBound(poly1[i], lowerBound, upperBound);
1121 for (int i = 0; i < poly2Length; i++) {
1122 updateBound(poly2[i], lowerBound, upperBound);
1125 bool dumpPoly = false;
1126 for (int k = 0; k < TEST_POINT_NUMBER; k++) {
1127 // Generate a random point between minX, minY and maxX, maxY.
1128 float randomX = rand() / float(RAND_MAX);
1129 float randomY = rand() / float(RAND_MAX);
1132 testPoint.x = lowerBound.x + randomX * (upperBound.x - lowerBound.x);
1133 testPoint.y = lowerBound.y + randomY * (upperBound.y - lowerBound.y);
1135 // If the random point is in both poly 1 and 2, then it must be intersection.
1136 if (testPointInsidePolygon(testPoint, intersection, intersectionLength)) {
1137 if (!testPointInsidePolygon(testPoint, poly1, poly1Length)) {
1139 ALOGW("(Error Type 1): one point (%f, %f) in the intersection is"
1140 " not in the poly1",
1141 testPoint.x, testPoint.y);
1144 if (!testPointInsidePolygon(testPoint, poly2, poly2Length)) {
1146 ALOGW("(Error Type 1): one point (%f, %f) in the intersection is"
1147 " not in the poly2",
1148 testPoint.x, testPoint.y);
1154 dumpPolygon(intersection, intersectionLength, "intersection");
1155 for (int i = 1; i < intersectionLength; i++) {
1156 Vector2 delta = intersection[i] - intersection[i - 1];
1157 ALOGD("Intersetion i, %d Vs i-1 is delta %f", i, delta.lengthSquared());
1160 dumpPolygon(poly1, poly1Length, "poly 1");
1161 dumpPolygon(poly2, poly2Length, "poly 2");
1166 }; // namespace uirenderer
1167 }; // namespace android