blob: 7b0a1bc3e93e8049d05f9bb652f2ef89127d6458 [file] [log] [blame]
ztenghui7b4516e2014-01-07 10:42:55 -08001/*
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
ztenghui512e6432014-09-10 13:08:20 -070017// The highest z value can't be higher than (CASTER_Z_CAP_RATIO * light.z)
ztenghuic50a03d2014-08-21 13:47:54 -070018#define CASTER_Z_CAP_RATIO 0.95f
ztenghui512e6432014-09-10 13:08:20 -070019
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
Chris Craik138c21f2016-04-28 16:59:42 -070045#define PENUMBRA_ALPHA 0.0f
46#define UMBRA_ALPHA 1.0f
ztenghui7b4516e2014-01-07 10:42:55 -080047
Chris Craik9db58c02015-08-19 15:19:18 -070048#include "SpotShadow.h"
49
50#include "ShadowTessellator.h"
51#include "Vertex.h"
52#include "VertexBuffer.h"
53#include "utils/MathUtils.h"
54
John Reck1e4209e2015-07-01 09:54:47 -070055#include <algorithm>
ztenghui7b4516e2014-01-07 10:42:55 -080056#include <math.h>
ztenghuif5ca8b42014-01-27 15:53:28 -080057#include <stdlib.h>
ztenghui7b4516e2014-01-07 10:42:55 -080058#include <utils/Log.h>
59
ztenghuic50a03d2014-08-21 13:47:54 -070060// 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.
ztenghui7b4516e2014-01-07 10:42:55 -080063namespace android {
64namespace uirenderer {
65
ztenghui9122b1b2014-10-03 11:21:11 -070066static const float EPSILON = 1e-7;
Chris Craik726118b2014-03-07 18:27:49 -080067
ztenghui7b4516e2014-01-07 10:42:55 -080068/**
ztenghuic50a03d2014-08-21 13:47:54 -070069 * 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 */
74struct OutlineData {
75 Vector2 position;
76 Vector2 normal;
77 float radius;
78};
79
80/**
ztenghui512e6432014-09-10 13:08:20 -070081 * For each vertex, we need to keep track of its angle, whether it is penumbra or
82 * umbra, and its corresponding vertex index.
83 */
84struct 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/**
Chris Craik726118b2014-03-07 18:27:49 -080099 * Calculate the angle between and x and a y coordinate.
100 * The atan2 range from -PI to PI.
ztenghui7b4516e2014-01-07 10:42:55 -0800101 */
Chris Craikb79a3e32014-03-11 12:20:17 -0700102static float angle(const Vector2& point, const Vector2& center) {
Chris Craik726118b2014-03-07 18:27:49 -0800103 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 */
Chris Craikb79a3e32014-03-11 12:20:17 -0700118static float rayIntersectPoints(const Vector2& rayOrigin, float dx, float dy,
Chris Craik726118b2014-03-07 18:27:49 -0800119 const Vector2& p1, const Vector2& p2) {
120 // The math below is derived from solving this formula, basically the
121 // intersection point should stay on both the ray and the edge of (p1, p2).
122 // solve([p1x+t*(p2x-p1x)=dx*t2+px,p1y+t*(p2y-p1y)=dy*t2+py],[t,t2]);
123
ztenghui9122b1b2014-10-03 11:21:11 -0700124 float divisor = (dx * (p1.y - p2.y) + dy * p2.x - dy * p1.x);
Chris Craik726118b2014-03-07 18:27:49 -0800125 if (divisor == 0) return -1.0f; // error, invalid divisor
126
127#if DEBUG_SHADOW
ztenghui9122b1b2014-10-03 11:21:11 -0700128 float interpVal = (dx * (p1.y - rayOrigin.y) + dy * rayOrigin.x - dy * p1.x) / divisor;
ztenghui99af9422014-03-14 14:35:54 -0700129 if (interpVal < 0 || interpVal > 1) {
130 ALOGW("rayIntersectPoints is hitting outside the segment %f", interpVal);
131 }
Chris Craik726118b2014-03-07 18:27:49 -0800132#endif
133
ztenghui9122b1b2014-10-03 11:21:11 -0700134 float distance = (p1.x * (rayOrigin.y - p2.y) + p2.x * (p1.y - rayOrigin.y) +
Chris Craik726118b2014-03-07 18:27:49 -0800135 rayOrigin.x * (p2.y - p1.y)) / divisor;
136
137 return distance; // may be negative in error cases
ztenghui7b4516e2014-01-07 10:42:55 -0800138}
139
140/**
ztenghui7b4516e2014-01-07 10:42:55 -0800141 * Sort points by their X coordinates
142 *
143 * @param points the points as a Vector2 array.
144 * @param pointsLength the number of vertices of the polygon.
145 */
146void SpotShadow::xsort(Vector2* points, int pointsLength) {
John Reck1e4209e2015-07-01 09:54:47 -0700147 auto cmp = [](const Vector2& a, const Vector2& b) -> bool {
148 return a.x < b.x;
149 };
150 std::sort(points, points + pointsLength, cmp);
ztenghui7b4516e2014-01-07 10:42:55 -0800151}
152
153/**
154 * compute the convex hull of a collection of Points
155 *
156 * @param points the points as a Vector2 array.
157 * @param pointsLength the number of vertices of the polygon.
158 * @param retPoly pre allocated array of floats to put the vertices
159 * @return the number of points in the polygon 0 if no intersection
160 */
161int SpotShadow::hull(Vector2* points, int pointsLength, Vector2* retPoly) {
162 xsort(points, pointsLength);
163 int n = pointsLength;
164 Vector2 lUpper[n];
165 lUpper[0] = points[0];
166 lUpper[1] = points[1];
167
168 int lUpperSize = 2;
169
170 for (int i = 2; i < n; i++) {
171 lUpper[lUpperSize] = points[i];
172 lUpperSize++;
173
ztenghuif5ca8b42014-01-27 15:53:28 -0800174 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)) {
ztenghui7b4516e2014-01-07 10:42:55 -0800178 // Remove the middle point of the three last
179 lUpper[lUpperSize - 2].x = lUpper[lUpperSize - 1].x;
180 lUpper[lUpperSize - 2].y = lUpper[lUpperSize - 1].y;
181 lUpperSize--;
182 }
183 }
184
185 Vector2 lLower[n];
186 lLower[0] = points[n - 1];
187 lLower[1] = points[n - 2];
188
189 int lLowerSize = 2;
190
191 for (int i = n - 3; i >= 0; i--) {
192 lLower[lLowerSize] = points[i];
193 lLowerSize++;
194
ztenghuif5ca8b42014-01-27 15:53:28 -0800195 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)) {
ztenghui7b4516e2014-01-07 10:42:55 -0800199 // Remove the middle point of the three last
200 lLower[lLowerSize - 2] = lLower[lLowerSize - 1];
201 lLowerSize--;
202 }
203 }
ztenghui7b4516e2014-01-07 10:42:55 -0800204
Chris Craik726118b2014-03-07 18:27:49 -0800205 // output points in CW ordering
206 const int total = lUpperSize + lLowerSize - 2;
207 int outIndex = total - 1;
ztenghui7b4516e2014-01-07 10:42:55 -0800208 for (int i = 0; i < lUpperSize; i++) {
Chris Craik726118b2014-03-07 18:27:49 -0800209 retPoly[outIndex] = lUpper[i];
210 outIndex--;
ztenghui7b4516e2014-01-07 10:42:55 -0800211 }
212
213 for (int i = 1; i < lLowerSize - 1; i++) {
Chris Craik726118b2014-03-07 18:27:49 -0800214 retPoly[outIndex] = lLower[i];
215 outIndex--;
ztenghui7b4516e2014-01-07 10:42:55 -0800216 }
217 // TODO: Add test harness which verify that all the points are inside the hull.
Chris Craik726118b2014-03-07 18:27:49 -0800218 return total;
ztenghui7b4516e2014-01-07 10:42:55 -0800219}
220
221/**
ztenghuif5ca8b42014-01-27 15:53:28 -0800222 * Test whether the 3 points form a counter clockwise turn.
ztenghui7b4516e2014-01-07 10:42:55 -0800223 *
ztenghui7b4516e2014-01-07 10:42:55 -0800224 * @return true if a right hand turn
225 */
ztenghui9122b1b2014-10-03 11:21:11 -0700226bool SpotShadow::ccw(float ax, float ay, float bx, float by,
227 float cx, float cy) {
ztenghui7b4516e2014-01-07 10:42:55 -0800228 return (bx - ax) * (cy - ay) - (by - ay) * (cx - ax) > EPSILON;
229}
230
231/**
ztenghui7b4516e2014-01-07 10:42:55 -0800232 * Sort points about a center point
233 *
234 * @param poly The in and out polyogon as a Vector2 array.
235 * @param polyLength The number of vertices of the polygon.
236 * @param center the center ctr[0] = x , ctr[1] = y to sort around.
237 */
238void SpotShadow::sort(Vector2* poly, int polyLength, const Vector2& center) {
239 quicksortCirc(poly, 0, polyLength - 1, center);
240}
241
242/**
ztenghui7b4516e2014-01-07 10:42:55 -0800243 * Swap points pointed to by i and j
244 */
245void SpotShadow::swap(Vector2* points, int i, int j) {
246 Vector2 temp = points[i];
247 points[i] = points[j];
248 points[j] = temp;
249}
250
251/**
252 * quick sort implementation about the center.
253 */
254void SpotShadow::quicksortCirc(Vector2* points, int low, int high,
255 const Vector2& center) {
256 int i = low, j = high;
257 int p = low + (high - low) / 2;
258 float pivot = angle(points[p], center);
259 while (i <= j) {
Chris Craik726118b2014-03-07 18:27:49 -0800260 while (angle(points[i], center) > pivot) {
ztenghui7b4516e2014-01-07 10:42:55 -0800261 i++;
262 }
Chris Craik726118b2014-03-07 18:27:49 -0800263 while (angle(points[j], center) < pivot) {
ztenghui7b4516e2014-01-07 10:42:55 -0800264 j--;
265 }
266
267 if (i <= j) {
268 swap(points, i, j);
269 i++;
270 j--;
271 }
272 }
273 if (low < j) quicksortCirc(points, low, j, center);
274 if (i < high) quicksortCirc(points, i, high, center);
275}
276
277/**
ztenghui7b4516e2014-01-07 10:42:55 -0800278 * Test whether a point is inside the polygon.
279 *
280 * @param testPoint the point to test
281 * @param poly the polygon
282 * @return true if the testPoint is inside the poly.
283 */
284bool SpotShadow::testPointInsidePolygon(const Vector2 testPoint,
285 const Vector2* poly, int len) {
286 bool c = false;
ztenghui9122b1b2014-10-03 11:21:11 -0700287 float testx = testPoint.x;
288 float testy = testPoint.y;
ztenghui7b4516e2014-01-07 10:42:55 -0800289 for (int i = 0, j = len - 1; i < len; j = i++) {
ztenghui9122b1b2014-10-03 11:21:11 -0700290 float startX = poly[j].x;
291 float startY = poly[j].y;
292 float endX = poly[i].x;
293 float endY = poly[i].y;
ztenghui7b4516e2014-01-07 10:42:55 -0800294
ztenghui512e6432014-09-10 13:08:20 -0700295 if (((endY > testy) != (startY > testy))
296 && (testx < (startX - endX) * (testy - endY)
ztenghui7b4516e2014-01-07 10:42:55 -0800297 / (startY - endY) + endX)) {
298 c = !c;
299 }
300 }
301 return c;
302}
303
304/**
ztenghui7b4516e2014-01-07 10:42:55 -0800305 * Reverse the polygon
306 *
307 * @param polygon the polygon as a Vector2 array
308 * @param len the number of points of the polygon
309 */
310void SpotShadow::reverse(Vector2* polygon, int len) {
311 int n = len / 2;
312 for (int i = 0; i < n; i++) {
313 Vector2 tmp = polygon[i];
314 int k = len - 1 - i;
315 polygon[i] = polygon[k];
316 polygon[k] = tmp;
317 }
318}
319
320/**
ztenghui7b4516e2014-01-07 10:42:55 -0800321 * Compute a horizontal circular polygon about point (x , y , height) of radius
322 * (size)
323 *
324 * @param points number of the points of the output polygon.
325 * @param lightCenter the center of the light.
326 * @param size the light size.
327 * @param ret result polygon.
328 */
329void SpotShadow::computeLightPolygon(int points, const Vector3& lightCenter,
330 float size, Vector3* ret) {
331 // TODO: Caching all the sin / cos values and store them in a look up table.
332 for (int i = 0; i < points; i++) {
ztenghui9122b1b2014-10-03 11:21:11 -0700333 float angle = 2 * i * M_PI / points;
Chris Craik726118b2014-03-07 18:27:49 -0800334 ret[i].x = cosf(angle) * size + lightCenter.x;
335 ret[i].y = sinf(angle) * size + lightCenter.y;
ztenghui7b4516e2014-01-07 10:42:55 -0800336 ret[i].z = lightCenter.z;
337 }
338}
339
340/**
ztenghui512e6432014-09-10 13:08:20 -0700341 * From light center, project one vertex to the z=0 surface and get the outline.
ztenghui7b4516e2014-01-07 10:42:55 -0800342 *
ztenghui512e6432014-09-10 13:08:20 -0700343 * @param outline The result which is the outline position.
344 * @param lightCenter The center of light.
345 * @param polyVertex The input polygon's vertex.
346 *
347 * @return float The ratio of (polygon.z / light.z - polygon.z)
ztenghui7b4516e2014-01-07 10:42:55 -0800348 */
ztenghuic50a03d2014-08-21 13:47:54 -0700349float SpotShadow::projectCasterToOutline(Vector2& outline,
350 const Vector3& lightCenter, const Vector3& polyVertex) {
351 float lightToPolyZ = lightCenter.z - polyVertex.z;
352 float ratioZ = CASTER_Z_CAP_RATIO;
353 if (lightToPolyZ != 0) {
354 // If any caster's vertex is almost above the light, we just keep it as 95%
355 // of the height of the light.
ztenghui3bd3fa12014-08-25 14:42:27 -0700356 ratioZ = MathUtils::clamp(polyVertex.z / lightToPolyZ, 0.0f, CASTER_Z_CAP_RATIO);
ztenghuic50a03d2014-08-21 13:47:54 -0700357 }
358
359 outline.x = polyVertex.x - ratioZ * (lightCenter.x - polyVertex.x);
360 outline.y = polyVertex.y - ratioZ * (lightCenter.y - polyVertex.y);
361 return ratioZ;
362}
363
364/**
365 * Generate the shadow spot light of shape lightPoly and a object poly
366 *
367 * @param isCasterOpaque whether the caster is opaque
368 * @param lightCenter the center of the light
369 * @param lightSize the radius of the light
370 * @param poly x,y,z vertexes of a convex polygon that occludes the light source
371 * @param polyLength number of vertexes of the occluding polygon
372 * @param shadowTriangleStrip return an (x,y,alpha) triangle strip representing the shadow. Return
373 * empty strip if error.
374 */
375void SpotShadow::createSpotShadow(bool isCasterOpaque, const Vector3& lightCenter,
376 float lightSize, const Vector3* poly, int polyLength, const Vector3& polyCentroid,
377 VertexBuffer& shadowTriangleStrip) {
ztenghui3bd3fa12014-08-25 14:42:27 -0700378 if (CC_UNLIKELY(lightCenter.z <= 0)) {
379 ALOGW("Relative Light Z is not positive. No spot shadow!");
380 return;
381 }
ztenghui512e6432014-09-10 13:08:20 -0700382 if (CC_UNLIKELY(polyLength < 3)) {
383#if DEBUG_SHADOW
384 ALOGW("Invalid polygon length. No spot shadow!");
385#endif
386 return;
387 }
ztenghuic50a03d2014-08-21 13:47:54 -0700388 OutlineData outlineData[polyLength];
389 Vector2 outlineCentroid;
390 // Calculate the projected outline for each polygon's vertices from the light center.
391 //
392 // O Light
393 // /
394 // /
395 // . Polygon vertex
396 // /
397 // /
398 // O Outline vertices
399 //
400 // Ratio = (Poly - Outline) / (Light - Poly)
401 // Outline.x = Poly.x - Ratio * (Light.x - Poly.x)
402 // Outline's radius / Light's radius = Ratio
403
404 // Compute the last outline vertex to make sure we can get the normal and outline
405 // in one single loop.
406 projectCasterToOutline(outlineData[polyLength - 1].position, lightCenter,
407 poly[polyLength - 1]);
408
409 // Take the outline's polygon, calculate the normal for each outline edge.
410 int currentNormalIndex = polyLength - 1;
411 int nextNormalIndex = 0;
412
413 for (int i = 0; i < polyLength; i++) {
414 float ratioZ = projectCasterToOutline(outlineData[i].position,
415 lightCenter, poly[i]);
416 outlineData[i].radius = ratioZ * lightSize;
417
418 outlineData[currentNormalIndex].normal = ShadowTessellator::calculateNormal(
419 outlineData[currentNormalIndex].position,
420 outlineData[nextNormalIndex].position);
421 currentNormalIndex = (currentNormalIndex + 1) % polyLength;
422 nextNormalIndex++;
423 }
424
425 projectCasterToOutline(outlineCentroid, lightCenter, polyCentroid);
426
427 int penumbraIndex = 0;
ztenghui512e6432014-09-10 13:08:20 -0700428 // Then each polygon's vertex produce at minmal 2 penumbra vertices.
429 // Since the size can be dynamic here, we keep track of the size and update
430 // the real size at the end.
431 int allocatedPenumbraLength = 2 * polyLength + SPOT_MAX_EXTRA_CORNER_VERTEX_NUMBER;
432 Vector2 penumbra[allocatedPenumbraLength];
433 int totalExtraCornerSliceNumber = 0;
ztenghuic50a03d2014-08-21 13:47:54 -0700434
435 Vector2 umbra[polyLength];
ztenghuic50a03d2014-08-21 13:47:54 -0700436
ztenghui512e6432014-09-10 13:08:20 -0700437 // When centroid is covered by all circles from outline, then we consider
438 // the umbra is invalid, and we will tune down the shadow strength.
ztenghuic50a03d2014-08-21 13:47:54 -0700439 bool hasValidUmbra = true;
ztenghui512e6432014-09-10 13:08:20 -0700440 // We need the minimal of RaitoVI to decrease the spot shadow strength accordingly.
441 float minRaitoVI = FLT_MAX;
ztenghuic50a03d2014-08-21 13:47:54 -0700442
443 for (int i = 0; i < polyLength; i++) {
444 // Generate all the penumbra's vertices only using the (outline vertex + normal * radius)
445 // There is no guarantee that the penumbra is still convex, but for
446 // each outline vertex, it will connect to all its corresponding penumbra vertices as
447 // triangle fans. And for neighber penumbra vertex, it will be a trapezoid.
448 //
449 // Penumbra Vertices marked as Pi
450 // Outline Vertices marked as Vi
451 // (P3)
452 // (P2) | ' (P4)
453 // (P1)' | | '
454 // ' | | '
455 // (P0) ------------------------------------------------(P5)
456 // | (V0) |(V1)
457 // | |
458 // | |
459 // | |
460 // | |
461 // | |
462 // | |
463 // | |
464 // | |
465 // (V3)-----------------------------------(V2)
466 int preNormalIndex = (i + polyLength - 1) % polyLength;
ztenghuic50a03d2014-08-21 13:47:54 -0700467
ztenghui512e6432014-09-10 13:08:20 -0700468 const Vector2& previousNormal = outlineData[preNormalIndex].normal;
469 const Vector2& currentNormal = outlineData[i].normal;
470
471 // Depending on how roundness we want for each corner, we can subdivide
ztenghuic50a03d2014-08-21 13:47:54 -0700472 // further here and/or introduce some heuristic to decide how much the
473 // subdivision should be.
ztenghui512e6432014-09-10 13:08:20 -0700474 int currentExtraSliceNumber = ShadowTessellator::getExtraVertexNumber(
475 previousNormal, currentNormal, SPOT_CORNER_RADIANS_DIVISOR);
ztenghuic50a03d2014-08-21 13:47:54 -0700476
ztenghui512e6432014-09-10 13:08:20 -0700477 int currentCornerSliceNumber = 1 + currentExtraSliceNumber;
478 totalExtraCornerSliceNumber += currentExtraSliceNumber;
479#if DEBUG_SHADOW
480 ALOGD("currentExtraSliceNumber should be %d", currentExtraSliceNumber);
481 ALOGD("currentCornerSliceNumber should be %d", currentCornerSliceNumber);
482 ALOGD("totalCornerSliceNumber is %d", totalExtraCornerSliceNumber);
483#endif
484 if (CC_UNLIKELY(totalExtraCornerSliceNumber > SPOT_MAX_EXTRA_CORNER_VERTEX_NUMBER)) {
485 currentCornerSliceNumber = 1;
486 }
487 for (int k = 0; k <= currentCornerSliceNumber; k++) {
488 Vector2 avgNormal =
489 (previousNormal * (currentCornerSliceNumber - k) + currentNormal * k) /
490 currentCornerSliceNumber;
491 avgNormal.normalize();
492 penumbra[penumbraIndex++] = outlineData[i].position +
493 avgNormal * outlineData[i].radius;
494 }
ztenghuic50a03d2014-08-21 13:47:54 -0700495
ztenghuic50a03d2014-08-21 13:47:54 -0700496
497 // Compute the umbra by the intersection from the outline's centroid!
498 //
499 // (V) ------------------------------------
500 // | ' |
501 // | ' |
502 // | ' (I) |
503 // | ' |
504 // | ' (C) |
505 // | |
506 // | |
507 // | |
508 // | |
509 // ------------------------------------
510 //
511 // Connect a line b/t the outline vertex (V) and the centroid (C), it will
512 // intersect with the outline vertex's circle at point (I).
513 // Now, ratioVI = VI / VC, ratioIC = IC / VC
514 // Then the intersetion point can be computed as Ixy = Vxy * ratioIC + Cxy * ratioVI;
515 //
ztenghui512e6432014-09-10 13:08:20 -0700516 // When all of the outline circles cover the the outline centroid, (like I is
ztenghuic50a03d2014-08-21 13:47:54 -0700517 // on the other side of C), there is no real umbra any more, so we just fake
518 // a small area around the centroid as the umbra, and tune down the spot
519 // shadow's umbra strength to simulate the effect the whole shadow will
520 // become lighter in this case.
521 // The ratio can be simulated by using the inverse of maximum of ratioVI for
522 // all (V).
ztenghui512e6432014-09-10 13:08:20 -0700523 float distOutline = (outlineData[i].position - outlineCentroid).length();
ztenghui3bd3fa12014-08-25 14:42:27 -0700524 if (CC_UNLIKELY(distOutline == 0)) {
ztenghuic50a03d2014-08-21 13:47:54 -0700525 // If the outline has 0 area, then there is no spot shadow anyway.
526 ALOGW("Outline has 0 area, no spot shadow!");
527 return;
528 }
ztenghui512e6432014-09-10 13:08:20 -0700529
530 float ratioVI = outlineData[i].radius / distOutline;
Chris Craik9db58c02015-08-19 15:19:18 -0700531 minRaitoVI = std::min(minRaitoVI, ratioVI);
ztenghui512e6432014-09-10 13:08:20 -0700532 if (ratioVI >= (1 - FAKE_UMBRA_SIZE_RATIO)) {
533 ratioVI = (1 - FAKE_UMBRA_SIZE_RATIO);
ztenghuic50a03d2014-08-21 13:47:54 -0700534 }
535 // When we know we don't have valid umbra, don't bother to compute the
536 // values below. But we can't skip the loop yet since we want to know the
537 // maximum ratio.
ztenghui512e6432014-09-10 13:08:20 -0700538 float ratioIC = 1 - ratioVI;
539 umbra[i] = outlineData[i].position * ratioIC + outlineCentroid * ratioVI;
ztenghuic50a03d2014-08-21 13:47:54 -0700540 }
541
ztenghui512e6432014-09-10 13:08:20 -0700542 hasValidUmbra = (minRaitoVI <= 1.0);
ztenghuic50a03d2014-08-21 13:47:54 -0700543 float shadowStrengthScale = 1.0;
544 if (!hasValidUmbra) {
ztenghui512e6432014-09-10 13:08:20 -0700545#if DEBUG_SHADOW
ztenghuic50a03d2014-08-21 13:47:54 -0700546 ALOGW("The object is too close to the light or too small, no real umbra!");
ztenghui512e6432014-09-10 13:08:20 -0700547#endif
ztenghuic50a03d2014-08-21 13:47:54 -0700548 for (int i = 0; i < polyLength; i++) {
549 umbra[i] = outlineData[i].position * FAKE_UMBRA_SIZE_RATIO +
ztenghui512e6432014-09-10 13:08:20 -0700550 outlineCentroid * (1 - FAKE_UMBRA_SIZE_RATIO);
ztenghuic50a03d2014-08-21 13:47:54 -0700551 }
ztenghui512e6432014-09-10 13:08:20 -0700552 shadowStrengthScale = 1.0 / minRaitoVI;
ztenghuic50a03d2014-08-21 13:47:54 -0700553 }
554
ztenghui512e6432014-09-10 13:08:20 -0700555 int penumbraLength = penumbraIndex;
556 int umbraLength = polyLength;
557
ztenghuic50a03d2014-08-21 13:47:54 -0700558#if DEBUG_SHADOW
ztenghui512e6432014-09-10 13:08:20 -0700559 ALOGD("penumbraLength is %d , allocatedPenumbraLength %d", penumbraLength, allocatedPenumbraLength);
ztenghuic50a03d2014-08-21 13:47:54 -0700560 dumpPolygon(poly, polyLength, "input poly");
ztenghuic50a03d2014-08-21 13:47:54 -0700561 dumpPolygon(penumbra, penumbraLength, "penumbra");
ztenghui512e6432014-09-10 13:08:20 -0700562 dumpPolygon(umbra, umbraLength, "umbra");
ztenghuic50a03d2014-08-21 13:47:54 -0700563 ALOGD("hasValidUmbra is %d and shadowStrengthScale is %f", hasValidUmbra, shadowStrengthScale);
564#endif
565
ztenghui512e6432014-09-10 13:08:20 -0700566 // The penumbra and umbra needs to be in convex shape to keep consistency
567 // and quality.
568 // Since we are still shooting rays to penumbra, it needs to be convex.
569 // Umbra can be represented as a fan from the centroid, but visually umbra
570 // looks nicer when it is convex.
571 Vector2 finalUmbra[umbraLength];
572 Vector2 finalPenumbra[penumbraLength];
573 int finalUmbraLength = hull(umbra, umbraLength, finalUmbra);
574 int finalPenumbraLength = hull(penumbra, penumbraLength, finalPenumbra);
575
576 generateTriangleStrip(isCasterOpaque, shadowStrengthScale, finalPenumbra,
577 finalPenumbraLength, finalUmbra, finalUmbraLength, poly, polyLength,
578 shadowTriangleStrip, outlineCentroid);
579
ztenghuic50a03d2014-08-21 13:47:54 -0700580}
581
ztenghui7b4516e2014-01-07 10:42:55 -0800582/**
ztenghui7b4516e2014-01-07 10:42:55 -0800583 * This is only for experimental purpose.
584 * After intersections are calculated, we could smooth the polygon if needed.
585 * So far, we don't think it is more appealing yet.
586 *
587 * @param level The level of smoothness.
588 * @param rays The total number of rays.
589 * @param rayDist (In and Out) The distance for each ray.
590 *
591 */
592void SpotShadow::smoothPolygon(int level, int rays, float* rayDist) {
593 for (int k = 0; k < level; k++) {
594 for (int i = 0; i < rays; i++) {
595 float p1 = rayDist[(rays - 1 + i) % rays];
596 float p2 = rayDist[i];
597 float p3 = rayDist[(i + 1) % rays];
598 rayDist[i] = (p1 + p2 * 2 + p3) / 4;
599 }
600 }
601}
602
ztenghuid2dcd6f2014-10-29 16:04:29 -0700603// Index pair is meant for storing the tessellation information for the penumbra
604// area. One index must come from exterior tangent of the circles, the other one
605// must come from the interior tangent of the circles.
606struct IndexPair {
607 int outerIndex;
608 int innerIndex;
609};
ztenghui512e6432014-09-10 13:08:20 -0700610
ztenghuid2dcd6f2014-10-29 16:04:29 -0700611// For one penumbra vertex, find the cloest umbra vertex and return its index.
612inline int getClosestUmbraIndex(const Vector2& pivot, const Vector2* polygon, int polygonLength) {
613 float minLengthSquared = FLT_MAX;
ztenghui512e6432014-09-10 13:08:20 -0700614 int resultIndex = -1;
ztenghuid2dcd6f2014-10-29 16:04:29 -0700615 bool hasDecreased = false;
616 // Starting with some negative offset, assuming both umbra and penumbra are starting
617 // at the same angle, this can help to find the result faster.
618 // Normally, loop 3 times, we can find the closest point.
619 int offset = polygonLength - 2;
620 for (int i = 0; i < polygonLength; i++) {
621 int currentIndex = (i + offset) % polygonLength;
622 float currentLengthSquared = (pivot - polygon[currentIndex]).lengthSquared();
623 if (currentLengthSquared < minLengthSquared) {
624 if (minLengthSquared != FLT_MAX) {
625 hasDecreased = true;
ztenghui512e6432014-09-10 13:08:20 -0700626 }
ztenghuid2dcd6f2014-10-29 16:04:29 -0700627 minLengthSquared = currentLengthSquared;
628 resultIndex = currentIndex;
629 } else if (currentLengthSquared > minLengthSquared && hasDecreased) {
630 // Early break b/c we have found the closet one and now the length
631 // is increasing again.
632 break;
ztenghui512e6432014-09-10 13:08:20 -0700633 }
634 }
ztenghuid2dcd6f2014-10-29 16:04:29 -0700635 if(resultIndex == -1) {
636 ALOGE("resultIndex is -1, the polygon must be invalid!");
637 resultIndex = 0;
ztenghui512e6432014-09-10 13:08:20 -0700638 }
639 return resultIndex;
640}
641
ztenghui39320632014-11-12 10:56:15 -0800642// Allow some epsilon here since the later ray intersection did allow for some small
643// floating point error, when the intersection point is slightly outside the segment.
ztenghuid2dcd6f2014-10-29 16:04:29 -0700644inline bool sameDirections(bool isPositiveCross, float a, float b) {
645 if (isPositiveCross) {
ztenghui39320632014-11-12 10:56:15 -0800646 return a >= -EPSILON && b >= -EPSILON;
ztenghuid2dcd6f2014-10-29 16:04:29 -0700647 } else {
ztenghui39320632014-11-12 10:56:15 -0800648 return a <= EPSILON && b <= EPSILON;
ztenghui512e6432014-09-10 13:08:20 -0700649 }
ztenghuid2dcd6f2014-10-29 16:04:29 -0700650}
ztenghui512e6432014-09-10 13:08:20 -0700651
ztenghuid2dcd6f2014-10-29 16:04:29 -0700652// Find the right polygon edge to shoot the ray at.
653inline int findPolyIndex(bool isPositiveCross, int startPolyIndex, const Vector2& umbraDir,
654 const Vector2* polyToCentroid, int polyLength) {
655 // Make sure we loop with a bound.
656 for (int i = 0; i < polyLength; i++) {
657 int currentIndex = (i + startPolyIndex) % polyLength;
658 const Vector2& currentToCentroid = polyToCentroid[currentIndex];
659 const Vector2& nextToCentroid = polyToCentroid[(currentIndex + 1) % polyLength];
ztenghui512e6432014-09-10 13:08:20 -0700660
ztenghuid2dcd6f2014-10-29 16:04:29 -0700661 float currentCrossUmbra = currentToCentroid.cross(umbraDir);
662 float umbraCrossNext = umbraDir.cross(nextToCentroid);
663 if (sameDirections(isPositiveCross, currentCrossUmbra, umbraCrossNext)) {
ztenghui512e6432014-09-10 13:08:20 -0700664#if DEBUG_SHADOW
ztenghuid2dcd6f2014-10-29 16:04:29 -0700665 ALOGD("findPolyIndex loop %d times , index %d", i, currentIndex );
ztenghui512e6432014-09-10 13:08:20 -0700666#endif
ztenghuid2dcd6f2014-10-29 16:04:29 -0700667 return currentIndex;
ztenghui512e6432014-09-10 13:08:20 -0700668 }
ztenghuid2dcd6f2014-10-29 16:04:29 -0700669 }
670 LOG_ALWAYS_FATAL("Can't find the right polygon's edge from startPolyIndex %d", startPolyIndex);
671 return -1;
672}
ztenghui512e6432014-09-10 13:08:20 -0700673
ztenghuid2dcd6f2014-10-29 16:04:29 -0700674// Generate the index pair for penumbra / umbra vertices, and more penumbra vertices
675// if needed.
676inline void genNewPenumbraAndPairWithUmbra(const Vector2* penumbra, int penumbraLength,
677 const Vector2* umbra, int umbraLength, Vector2* newPenumbra, int& newPenumbraIndex,
678 IndexPair* verticesPair, int& verticesPairIndex) {
679 // In order to keep everything in just one loop, we need to pre-compute the
680 // closest umbra vertex for the last penumbra vertex.
681 int previousClosestUmbraIndex = getClosestUmbraIndex(penumbra[penumbraLength - 1],
682 umbra, umbraLength);
683 for (int i = 0; i < penumbraLength; i++) {
684 const Vector2& currentPenumbraVertex = penumbra[i];
685 // For current penumbra vertex, starting from previousClosestUmbraIndex,
686 // then check the next one until the distance increase.
687 // The last one before the increase is the umbra vertex we need to pair with.
ztenghui39320632014-11-12 10:56:15 -0800688 float currentLengthSquared =
689 (currentPenumbraVertex - umbra[previousClosestUmbraIndex]).lengthSquared();
690 int currentClosestUmbraIndex = previousClosestUmbraIndex;
ztenghuid2dcd6f2014-10-29 16:04:29 -0700691 int indexDelta = 0;
692 for (int j = 1; j < umbraLength; j++) {
693 int newUmbraIndex = (previousClosestUmbraIndex + j) % umbraLength;
694 float newLengthSquared = (currentPenumbraVertex - umbra[newUmbraIndex]).lengthSquared();
695 if (newLengthSquared > currentLengthSquared) {
ztenghui39320632014-11-12 10:56:15 -0800696 // currentClosestUmbraIndex is the umbra vertex's index which has
697 // currently found smallest distance, so we can simply break here.
ztenghuid2dcd6f2014-10-29 16:04:29 -0700698 break;
699 } else {
700 currentLengthSquared = newLengthSquared;
701 indexDelta++;
ztenghui39320632014-11-12 10:56:15 -0800702 currentClosestUmbraIndex = newUmbraIndex;
ztenghui512e6432014-09-10 13:08:20 -0700703 }
ztenghuid2dcd6f2014-10-29 16:04:29 -0700704 }
ztenghuid2dcd6f2014-10-29 16:04:29 -0700705
706 if (indexDelta > 1) {
707 // For those umbra don't have penumbra, generate new penumbra vertices by interpolation.
708 //
709 // Assuming Pi for penumbra vertices, and Ui for umbra vertices.
710 // In the case like below P1 paired with U1 and P2 paired with U5.
711 // U2 to U4 are unpaired umbra vertices.
712 //
713 // P1 P2
714 // | |
715 // U1 U2 U3 U4 U5
716 //
717 // We will need to generate 3 more penumbra vertices P1.1, P1.2, P1.3
718 // to pair with U2 to U4.
719 //
720 // P1 P1.1 P1.2 P1.3 P2
721 // | | | | |
722 // U1 U2 U3 U4 U5
723 //
724 // That distance ratio b/t Ui to U1 and Ui to U5 decides its paired penumbra
725 // vertex's location.
726 int newPenumbraNumber = indexDelta - 1;
727
Keith Moka1f56312015-11-10 16:52:05 -0800728 float accumulatedDeltaLength[indexDelta];
ztenghuid2dcd6f2014-10-29 16:04:29 -0700729 float totalDeltaLength = 0;
730
731 // To save time, cache the previous umbra vertex info outside the loop
732 // and update each loop.
733 Vector2 previousClosestUmbra = umbra[previousClosestUmbraIndex];
734 Vector2 skippedUmbra;
735 // Use umbra data to precompute the length b/t unpaired umbra vertices,
736 // and its ratio against the total length.
737 for (int k = 0; k < indexDelta; k++) {
738 int skippedUmbraIndex = (previousClosestUmbraIndex + k + 1) % umbraLength;
739 skippedUmbra = umbra[skippedUmbraIndex];
740 float currentDeltaLength = (skippedUmbra - previousClosestUmbra).length();
741
742 totalDeltaLength += currentDeltaLength;
743 accumulatedDeltaLength[k] = totalDeltaLength;
744
745 previousClosestUmbra = skippedUmbra;
746 }
747
748 const Vector2& previousPenumbra = penumbra[(i + penumbraLength - 1) % penumbraLength];
749 // Then for each unpaired umbra vertex, create a new penumbra by the ratio,
750 // and pair them togehter.
751 for (int k = 0; k < newPenumbraNumber; k++) {
752 float weightForCurrentPenumbra = 1.0f;
753 if (totalDeltaLength != 0.0f) {
754 weightForCurrentPenumbra = accumulatedDeltaLength[k] / totalDeltaLength;
755 }
756 float weightForPreviousPenumbra = 1.0f - weightForCurrentPenumbra;
757
758 Vector2 interpolatedPenumbra = currentPenumbraVertex * weightForCurrentPenumbra +
759 previousPenumbra * weightForPreviousPenumbra;
760
761 int skippedUmbraIndex = (previousClosestUmbraIndex + k + 1) % umbraLength;
Andreas Gampeedaecc12014-11-10 20:54:07 -0800762 verticesPair[verticesPairIndex].outerIndex = newPenumbraIndex;
763 verticesPair[verticesPairIndex].innerIndex = skippedUmbraIndex;
764 verticesPairIndex++;
ztenghuid2dcd6f2014-10-29 16:04:29 -0700765 newPenumbra[newPenumbraIndex++] = interpolatedPenumbra;
766 }
767 }
Andreas Gampeedaecc12014-11-10 20:54:07 -0800768 verticesPair[verticesPairIndex].outerIndex = newPenumbraIndex;
769 verticesPair[verticesPairIndex].innerIndex = currentClosestUmbraIndex;
770 verticesPairIndex++;
ztenghuid2dcd6f2014-10-29 16:04:29 -0700771 newPenumbra[newPenumbraIndex++] = currentPenumbraVertex;
772
773 previousClosestUmbraIndex = currentClosestUmbraIndex;
774 }
775}
776
777// Precompute all the polygon's vector, return true if the reference cross product is positive.
778inline bool genPolyToCentroid(const Vector2* poly2d, int polyLength,
779 const Vector2& centroid, Vector2* polyToCentroid) {
780 for (int j = 0; j < polyLength; j++) {
781 polyToCentroid[j] = poly2d[j] - centroid;
ztenghui39320632014-11-12 10:56:15 -0800782 // Normalize these vectors such that we can use epsilon comparison after
783 // computing their cross products with another normalized vector.
784 polyToCentroid[j].normalize();
ztenghuid2dcd6f2014-10-29 16:04:29 -0700785 }
786 float refCrossProduct = 0;
787 for (int j = 0; j < polyLength; j++) {
788 refCrossProduct = polyToCentroid[j].cross(polyToCentroid[(j + 1) % polyLength]);
789 if (refCrossProduct != 0) {
790 break;
ztenghui512e6432014-09-10 13:08:20 -0700791 }
792 }
793
ztenghuid2dcd6f2014-10-29 16:04:29 -0700794 return refCrossProduct > 0;
795}
ztenghui512e6432014-09-10 13:08:20 -0700796
ztenghuid2dcd6f2014-10-29 16:04:29 -0700797// For one umbra vertex, shoot an ray from centroid to it.
798// If the ray hit the polygon first, then return the intersection point as the
799// closer vertex.
800inline Vector2 getCloserVertex(const Vector2& umbraVertex, const Vector2& centroid,
801 const Vector2* poly2d, int polyLength, const Vector2* polyToCentroid,
802 bool isPositiveCross, int& previousPolyIndex) {
803 Vector2 umbraToCentroid = umbraVertex - centroid;
804 float distanceToUmbra = umbraToCentroid.length();
805 umbraToCentroid = umbraToCentroid / distanceToUmbra;
806
807 // previousPolyIndex is updated for each item such that we can minimize the
808 // looping inside findPolyIndex();
809 previousPolyIndex = findPolyIndex(isPositiveCross, previousPolyIndex,
810 umbraToCentroid, polyToCentroid, polyLength);
811
812 float dx = umbraToCentroid.x;
813 float dy = umbraToCentroid.y;
814 float distanceToIntersectPoly = rayIntersectPoints(centroid, dx, dy,
815 poly2d[previousPolyIndex], poly2d[(previousPolyIndex + 1) % polyLength]);
816 if (distanceToIntersectPoly < 0) {
817 distanceToIntersectPoly = 0;
818 }
819
820 // Pick the closer one as the occluded area vertex.
821 Vector2 closerVertex;
822 if (distanceToIntersectPoly < distanceToUmbra) {
823 closerVertex.x = centroid.x + dx * distanceToIntersectPoly;
824 closerVertex.y = centroid.y + dy * distanceToIntersectPoly;
825 } else {
826 closerVertex = umbraVertex;
827 }
828
829 return closerVertex;
ztenghui512e6432014-09-10 13:08:20 -0700830}
831
832/**
833 * Generate a triangle strip given two convex polygon
834**/
Andreas Gampe64bb4132014-11-22 00:35:09 +0000835void SpotShadow::generateTriangleStrip(bool isCasterOpaque, float shadowStrengthScale,
ztenghui512e6432014-09-10 13:08:20 -0700836 Vector2* penumbra, int penumbraLength, Vector2* umbra, int umbraLength,
837 const Vector3* poly, int polyLength, VertexBuffer& shadowTriangleStrip,
838 const Vector2& centroid) {
ztenghui512e6432014-09-10 13:08:20 -0700839 bool hasOccludedUmbraArea = false;
840 Vector2 poly2d[polyLength];
841
842 if (isCasterOpaque) {
843 for (int i = 0; i < polyLength; i++) {
844 poly2d[i].x = poly[i].x;
845 poly2d[i].y = poly[i].y;
846 }
847 // Make sure the centroid is inside the umbra, otherwise, fall back to the
848 // approach as if there is no occluded umbra area.
849 if (testPointInsidePolygon(centroid, poly2d, polyLength)) {
850 hasOccludedUmbraArea = true;
851 }
852 }
853
ztenghuid2dcd6f2014-10-29 16:04:29 -0700854 // For each penumbra vertex, find its corresponding closest umbra vertex index.
855 //
856 // Penumbra Vertices marked as Pi
857 // Umbra Vertices marked as Ui
858 // (P3)
859 // (P2) | ' (P4)
860 // (P1)' | | '
861 // ' | | '
862 // (P0) ------------------------------------------------(P5)
863 // | (U0) |(U1)
864 // | |
865 // | |(U2) (P5.1)
866 // | |
867 // | |
868 // | |
869 // | |
870 // | |
871 // | |
872 // (U4)-----------------------------------(U3) (P6)
873 //
874 // At least, like P0, P1, P2, they will find the matching umbra as U0.
875 // If we jump over some umbra vertex without matching penumbra vertex, then
876 // we will generate some new penumbra vertex by interpolation. Like P6 is
877 // matching U3, but U2 is not matched with any penumbra vertex.
878 // So interpolate P5.1 out and match U2.
879 // In this way, every umbra vertex will have a matching penumbra vertex.
880 //
881 // The total pair number can be as high as umbraLength + penumbraLength.
882 const int maxNewPenumbraLength = umbraLength + penumbraLength;
883 IndexPair verticesPair[maxNewPenumbraLength];
884 int verticesPairIndex = 0;
885
886 // Cache all the existing penumbra vertices and newly interpolated vertices into a
887 // a new array.
888 Vector2 newPenumbra[maxNewPenumbraLength];
889 int newPenumbraIndex = 0;
890
891 // For each penumbra vertex, find its closet umbra vertex by comparing the
892 // neighbor umbra vertices.
893 genNewPenumbraAndPairWithUmbra(penumbra, penumbraLength, umbra, umbraLength, newPenumbra,
894 newPenumbraIndex, verticesPair, verticesPairIndex);
895 ShadowTessellator::checkOverflow(verticesPairIndex, maxNewPenumbraLength, "Spot pair");
896 ShadowTessellator::checkOverflow(newPenumbraIndex, maxNewPenumbraLength, "Spot new penumbra");
897#if DEBUG_SHADOW
898 for (int i = 0; i < umbraLength; i++) {
899 ALOGD("umbra i %d, [%f, %f]", i, umbra[i].x, umbra[i].y);
ztenghui512e6432014-09-10 13:08:20 -0700900 }
ztenghuid2dcd6f2014-10-29 16:04:29 -0700901 for (int i = 0; i < newPenumbraIndex; i++) {
902 ALOGD("new penumbra i %d, [%f, %f]", i, newPenumbra[i].x, newPenumbra[i].y);
903 }
904 for (int i = 0; i < verticesPairIndex; i++) {
905 ALOGD("index i %d, [%d, %d]", i, verticesPair[i].outerIndex, verticesPair[i].innerIndex);
906 }
907#endif
ztenghui512e6432014-09-10 13:08:20 -0700908
ztenghuid2dcd6f2014-10-29 16:04:29 -0700909 // For the size of vertex buffer, we need 3 rings, one has newPenumbraSize,
910 // one has umbraLength, the last one has at most umbraLength.
911 //
912 // For the size of index buffer, the umbra area needs (2 * umbraLength + 2).
913 // The penumbra one can vary a bit, but it is bounded by (2 * verticesPairIndex + 2).
914 // And 2 more for jumping between penumbra to umbra.
915 const int newPenumbraLength = newPenumbraIndex;
916 const int totalVertexCount = newPenumbraLength + umbraLength * 2;
917 const int totalIndexCount = 2 * umbraLength + 2 * verticesPairIndex + 6;
ztenghui512e6432014-09-10 13:08:20 -0700918 AlphaVertex* shadowVertices =
919 shadowTriangleStrip.alloc<AlphaVertex>(totalVertexCount);
920 uint16_t* indexBuffer =
921 shadowTriangleStrip.allocIndices<uint16_t>(totalIndexCount);
ztenghui512e6432014-09-10 13:08:20 -0700922 int vertexBufferIndex = 0;
ztenghuid2dcd6f2014-10-29 16:04:29 -0700923 int indexBufferIndex = 0;
ztenghui512e6432014-09-10 13:08:20 -0700924
ztenghuid2dcd6f2014-10-29 16:04:29 -0700925 // Fill the IB and VB for the penumbra area.
926 for (int i = 0; i < newPenumbraLength; i++) {
927 AlphaVertex::set(&shadowVertices[vertexBufferIndex++], newPenumbra[i].x,
Chris Craik138c21f2016-04-28 16:59:42 -0700928 newPenumbra[i].y, PENUMBRA_ALPHA);
ztenghuid2dcd6f2014-10-29 16:04:29 -0700929 }
Teng-Hui Zhu9c555562016-10-03 14:26:21 -0700930 // Since the umbra can be a faked one when the occluder is too high, the umbra should be lighter
931 // in this case.
932 float scaledUmbraAlpha = UMBRA_ALPHA * shadowStrengthScale;
933
ztenghuid2dcd6f2014-10-29 16:04:29 -0700934 for (int i = 0; i < umbraLength; i++) {
935 AlphaVertex::set(&shadowVertices[vertexBufferIndex++], umbra[i].x, umbra[i].y,
Teng-Hui Zhu9c555562016-10-03 14:26:21 -0700936 scaledUmbraAlpha);
ztenghui512e6432014-09-10 13:08:20 -0700937 }
938
ztenghuid2dcd6f2014-10-29 16:04:29 -0700939 for (int i = 0; i < verticesPairIndex; i++) {
940 indexBuffer[indexBufferIndex++] = verticesPair[i].outerIndex;
941 // All umbra index need to be offseted by newPenumbraSize.
942 indexBuffer[indexBufferIndex++] = verticesPair[i].innerIndex + newPenumbraLength;
943 }
944 indexBuffer[indexBufferIndex++] = verticesPair[0].outerIndex;
945 indexBuffer[indexBufferIndex++] = verticesPair[0].innerIndex + newPenumbraLength;
ztenghui512e6432014-09-10 13:08:20 -0700946
ztenghuid2dcd6f2014-10-29 16:04:29 -0700947 // Now fill the IB and VB for the umbra area.
948 // First duplicated the index from previous strip and the first one for the
949 // degenerated triangles.
950 indexBuffer[indexBufferIndex] = indexBuffer[indexBufferIndex - 1];
951 indexBufferIndex++;
952 indexBuffer[indexBufferIndex++] = newPenumbraLength + 0;
953 // Save the first VB index for umbra area in order to close the loop.
954 int savedStartIndex = vertexBufferIndex;
955
ztenghui512e6432014-09-10 13:08:20 -0700956 if (hasOccludedUmbraArea) {
ztenghuid2dcd6f2014-10-29 16:04:29 -0700957 // Precompute all the polygon's vector, and the reference cross product,
958 // in order to find the right polygon edge for the ray to intersect.
959 Vector2 polyToCentroid[polyLength];
960 bool isPositiveCross = genPolyToCentroid(poly2d, polyLength, centroid, polyToCentroid);
ztenghui512e6432014-09-10 13:08:20 -0700961
ztenghuid2dcd6f2014-10-29 16:04:29 -0700962 // Because both the umbra and polygon are going in the same direction,
963 // we can save the previous polygon index to make sure we have less polygon
964 // vertex to compute for each ray.
965 int previousPolyIndex = 0;
966 for (int i = 0; i < umbraLength; i++) {
967 // Shoot a ray from centroid to each umbra vertices and pick the one with
968 // shorter distance to the centroid, b/t the umbra vertex or the intersection point.
969 Vector2 closerVertex = getCloserVertex(umbra[i], centroid, poly2d, polyLength,
970 polyToCentroid, isPositiveCross, previousPolyIndex);
971
972 // We already stored the umbra vertices, just need to add the occlued umbra's ones.
973 indexBuffer[indexBufferIndex++] = newPenumbraLength + i;
974 indexBuffer[indexBufferIndex++] = vertexBufferIndex;
975 AlphaVertex::set(&shadowVertices[vertexBufferIndex++],
Teng-Hui Zhu9c555562016-10-03 14:26:21 -0700976 closerVertex.x, closerVertex.y, scaledUmbraAlpha);
ztenghui512e6432014-09-10 13:08:20 -0700977 }
ztenghui512e6432014-09-10 13:08:20 -0700978 } else {
ztenghuid2dcd6f2014-10-29 16:04:29 -0700979 // If there is no occluded umbra at all, then draw the triangle fan
980 // starting from the centroid to all umbra vertices.
ztenghui512e6432014-09-10 13:08:20 -0700981 int lastCentroidIndex = vertexBufferIndex;
982 AlphaVertex::set(&shadowVertices[vertexBufferIndex++], centroid.x,
Teng-Hui Zhu9c555562016-10-03 14:26:21 -0700983 centroid.y, scaledUmbraAlpha);
ztenghuid2dcd6f2014-10-29 16:04:29 -0700984 for (int i = 0; i < umbraLength; i++) {
985 indexBuffer[indexBufferIndex++] = newPenumbraLength + i;
ztenghui512e6432014-09-10 13:08:20 -0700986 indexBuffer[indexBufferIndex++] = lastCentroidIndex;
987 }
ztenghui512e6432014-09-10 13:08:20 -0700988 }
ztenghuid2dcd6f2014-10-29 16:04:29 -0700989 // Closing the umbra area triangle's loop here.
990 indexBuffer[indexBufferIndex++] = newPenumbraLength;
991 indexBuffer[indexBufferIndex++] = savedStartIndex;
ztenghui512e6432014-09-10 13:08:20 -0700992
993 // At the end, update the real index and vertex buffer size.
994 shadowTriangleStrip.updateVertexCount(vertexBufferIndex);
995 shadowTriangleStrip.updateIndexCount(indexBufferIndex);
996 ShadowTessellator::checkOverflow(vertexBufferIndex, totalVertexCount, "Spot Vertex Buffer");
997 ShadowTessellator::checkOverflow(indexBufferIndex, totalIndexCount, "Spot Index Buffer");
998
Chris Craik117bdbc2015-02-05 10:12:38 -0800999 shadowTriangleStrip.setMeshFeatureFlags(VertexBuffer::kAlpha | VertexBuffer::kIndices);
ztenghui512e6432014-09-10 13:08:20 -07001000 shadowTriangleStrip.computeBounds<AlphaVertex>();
1001}
1002
ztenghuif5ca8b42014-01-27 15:53:28 -08001003#if DEBUG_SHADOW
1004
1005#define TEST_POINT_NUMBER 128
ztenghuif5ca8b42014-01-27 15:53:28 -08001006/**
1007 * Calculate the bounds for generating random test points.
1008 */
1009void SpotShadow::updateBound(const Vector2 inVector, Vector2& lowerBound,
ztenghui512e6432014-09-10 13:08:20 -07001010 Vector2& upperBound) {
ztenghuif5ca8b42014-01-27 15:53:28 -08001011 if (inVector.x < lowerBound.x) {
1012 lowerBound.x = inVector.x;
1013 }
1014
1015 if (inVector.y < lowerBound.y) {
1016 lowerBound.y = inVector.y;
1017 }
1018
1019 if (inVector.x > upperBound.x) {
1020 upperBound.x = inVector.x;
1021 }
1022
1023 if (inVector.y > upperBound.y) {
1024 upperBound.y = inVector.y;
1025 }
1026}
1027
1028/**
1029 * For debug purpose, when things go wrong, dump the whole polygon data.
1030 */
ztenghuic50a03d2014-08-21 13:47:54 -07001031void SpotShadow::dumpPolygon(const Vector2* poly, int polyLength, const char* polyName) {
1032 for (int i = 0; i < polyLength; i++) {
1033 ALOGD("polygon %s i %d x %f y %f", polyName, i, poly[i].x, poly[i].y);
1034 }
1035}
1036
1037/**
1038 * For debug purpose, when things go wrong, dump the whole polygon data.
1039 */
1040void SpotShadow::dumpPolygon(const Vector3* poly, int polyLength, const char* polyName) {
ztenghuif5ca8b42014-01-27 15:53:28 -08001041 for (int i = 0; i < polyLength; i++) {
Teng-Hui Zhu8d0ec382015-10-01 16:49:16 -07001042 ALOGD("polygon %s i %d x %f y %f z %f", polyName, i, poly[i].x, poly[i].y, poly[i].z);
ztenghuif5ca8b42014-01-27 15:53:28 -08001043 }
1044}
1045
1046/**
1047 * Test whether the polygon is convex.
1048 */
1049bool SpotShadow::testConvex(const Vector2* polygon, int polygonLength,
1050 const char* name) {
1051 bool isConvex = true;
1052 for (int i = 0; i < polygonLength; i++) {
1053 Vector2 start = polygon[i];
1054 Vector2 middle = polygon[(i + 1) % polygonLength];
1055 Vector2 end = polygon[(i + 2) % polygonLength];
1056
ztenghui9122b1b2014-10-03 11:21:11 -07001057 float delta = (float(middle.x) - start.x) * (float(end.y) - start.y) -
1058 (float(middle.y) - start.y) * (float(end.x) - start.x);
ztenghuif5ca8b42014-01-27 15:53:28 -08001059 bool isCCWOrCoLinear = (delta >= EPSILON);
1060
1061 if (isCCWOrCoLinear) {
ztenghui50ecf842014-03-11 16:52:30 -07001062 ALOGW("(Error Type 2): polygon (%s) is not a convex b/c start (x %f, y %f),"
ztenghuif5ca8b42014-01-27 15:53:28 -08001063 "middle (x %f, y %f) and end (x %f, y %f) , delta is %f !!!",
1064 name, start.x, start.y, middle.x, middle.y, end.x, end.y, delta);
1065 isConvex = false;
1066 break;
1067 }
1068 }
1069 return isConvex;
1070}
1071
1072/**
1073 * Test whether or not the polygon (intersection) is within the 2 input polygons.
1074 * Using Marte Carlo method, we generate a random point, and if it is inside the
1075 * intersection, then it must be inside both source polygons.
1076 */
1077void SpotShadow::testIntersection(const Vector2* poly1, int poly1Length,
1078 const Vector2* poly2, int poly2Length,
1079 const Vector2* intersection, int intersectionLength) {
1080 // Find the min and max of x and y.
ztenghuic50a03d2014-08-21 13:47:54 -07001081 Vector2 lowerBound = {FLT_MAX, FLT_MAX};
1082 Vector2 upperBound = {-FLT_MAX, -FLT_MAX};
ztenghuif5ca8b42014-01-27 15:53:28 -08001083 for (int i = 0; i < poly1Length; i++) {
1084 updateBound(poly1[i], lowerBound, upperBound);
1085 }
1086 for (int i = 0; i < poly2Length; i++) {
1087 updateBound(poly2[i], lowerBound, upperBound);
1088 }
1089
1090 bool dumpPoly = false;
1091 for (int k = 0; k < TEST_POINT_NUMBER; k++) {
1092 // Generate a random point between minX, minY and maxX, maxY.
ztenghui9122b1b2014-10-03 11:21:11 -07001093 float randomX = rand() / float(RAND_MAX);
1094 float randomY = rand() / float(RAND_MAX);
ztenghuif5ca8b42014-01-27 15:53:28 -08001095
1096 Vector2 testPoint;
1097 testPoint.x = lowerBound.x + randomX * (upperBound.x - lowerBound.x);
1098 testPoint.y = lowerBound.y + randomY * (upperBound.y - lowerBound.y);
1099
1100 // If the random point is in both poly 1 and 2, then it must be intersection.
1101 if (testPointInsidePolygon(testPoint, intersection, intersectionLength)) {
1102 if (!testPointInsidePolygon(testPoint, poly1, poly1Length)) {
1103 dumpPoly = true;
ztenghui50ecf842014-03-11 16:52:30 -07001104 ALOGW("(Error Type 1): one point (%f, %f) in the intersection is"
ztenghui512e6432014-09-10 13:08:20 -07001105 " not in the poly1",
ztenghuif5ca8b42014-01-27 15:53:28 -08001106 testPoint.x, testPoint.y);
1107 }
1108
1109 if (!testPointInsidePolygon(testPoint, poly2, poly2Length)) {
1110 dumpPoly = true;
ztenghui50ecf842014-03-11 16:52:30 -07001111 ALOGW("(Error Type 1): one point (%f, %f) in the intersection is"
ztenghui512e6432014-09-10 13:08:20 -07001112 " not in the poly2",
ztenghuif5ca8b42014-01-27 15:53:28 -08001113 testPoint.x, testPoint.y);
1114 }
1115 }
1116 }
1117
1118 if (dumpPoly) {
1119 dumpPolygon(intersection, intersectionLength, "intersection");
1120 for (int i = 1; i < intersectionLength; i++) {
1121 Vector2 delta = intersection[i] - intersection[i - 1];
1122 ALOGD("Intersetion i, %d Vs i-1 is delta %f", i, delta.lengthSquared());
1123 }
1124
1125 dumpPolygon(poly1, poly1Length, "poly 1");
1126 dumpPolygon(poly2, poly2Length, "poly 2");
1127 }
1128}
1129#endif
1130
ztenghui7b4516e2014-01-07 10:42:55 -08001131}; // namespace uirenderer
1132}; // namespace android