blob: 9b0a1aadf0bf394332b64a2f36206d694e9a8ac1 [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
ztenghuiecf091e2015-02-17 13:26:10 -080045// For performance, we use (1 - alpha) value for the shader input.
46#define TRANSFORMED_PENUMBRA_ALPHA 1.0f
47#define TRANSFORMED_UMBRA_ALPHA 0.0f
ztenghui7b4516e2014-01-07 10:42:55 -080048
Chris Craik9db58c02015-08-19 15:19:18 -070049#include "SpotShadow.h"
50
51#include "ShadowTessellator.h"
52#include "Vertex.h"
53#include "VertexBuffer.h"
54#include "utils/MathUtils.h"
55
John Reck1e4209e2015-07-01 09:54:47 -070056#include <algorithm>
ztenghui7b4516e2014-01-07 10:42:55 -080057#include <math.h>
ztenghuif5ca8b42014-01-27 15:53:28 -080058#include <stdlib.h>
ztenghui7b4516e2014-01-07 10:42:55 -080059#include <utils/Log.h>
60
ztenghuic50a03d2014-08-21 13:47:54 -070061// TODO: After we settle down the new algorithm, we can remove the old one and
62// its utility functions.
63// Right now, we still need to keep it for comparison purpose and future expansion.
ztenghui7b4516e2014-01-07 10:42:55 -080064namespace android {
65namespace uirenderer {
66
ztenghui9122b1b2014-10-03 11:21:11 -070067static const float EPSILON = 1e-7;
Chris Craik726118b2014-03-07 18:27:49 -080068
ztenghui7b4516e2014-01-07 10:42:55 -080069/**
ztenghuic50a03d2014-08-21 13:47:54 -070070 * For each polygon's vertex, the light center will project it to the receiver
71 * as one of the outline vertex.
72 * For each outline vertex, we need to store the position and normal.
73 * Normal here is defined against the edge by the current vertex and the next vertex.
74 */
75struct OutlineData {
76 Vector2 position;
77 Vector2 normal;
78 float radius;
79};
80
81/**
ztenghui512e6432014-09-10 13:08:20 -070082 * For each vertex, we need to keep track of its angle, whether it is penumbra or
83 * umbra, and its corresponding vertex index.
84 */
85struct SpotShadow::VertexAngleData {
86 // The angle to the vertex from the centroid.
87 float mAngle;
88 // True is the vertex comes from penumbra, otherwise it comes from umbra.
89 bool mIsPenumbra;
90 // The index of the vertex described by this data.
91 int mVertexIndex;
92 void set(float angle, bool isPenumbra, int index) {
93 mAngle = angle;
94 mIsPenumbra = isPenumbra;
95 mVertexIndex = index;
96 }
97};
98
99/**
Chris Craik726118b2014-03-07 18:27:49 -0800100 * Calculate the angle between and x and a y coordinate.
101 * The atan2 range from -PI to PI.
ztenghui7b4516e2014-01-07 10:42:55 -0800102 */
Chris Craikb79a3e32014-03-11 12:20:17 -0700103static float angle(const Vector2& point, const Vector2& center) {
Chris Craik726118b2014-03-07 18:27:49 -0800104 return atan2(point.y - center.y, point.x - center.x);
105}
106
107/**
108 * Calculate the intersection of a ray with the line segment defined by two points.
109 *
110 * Returns a negative value in error conditions.
111
112 * @param rayOrigin The start of the ray
113 * @param dx The x vector of the ray
114 * @param dy The y vector of the ray
115 * @param p1 The first point defining the line segment
116 * @param p2 The second point defining the line segment
117 * @return The distance along the ray if it intersects with the line segment, negative if otherwise
118 */
Chris Craikb79a3e32014-03-11 12:20:17 -0700119static float rayIntersectPoints(const Vector2& rayOrigin, float dx, float dy,
Chris Craik726118b2014-03-07 18:27:49 -0800120 const Vector2& p1, const Vector2& p2) {
121 // The math below is derived from solving this formula, basically the
122 // intersection point should stay on both the ray and the edge of (p1, p2).
123 // solve([p1x+t*(p2x-p1x)=dx*t2+px,p1y+t*(p2y-p1y)=dy*t2+py],[t,t2]);
124
ztenghui9122b1b2014-10-03 11:21:11 -0700125 float divisor = (dx * (p1.y - p2.y) + dy * p2.x - dy * p1.x);
Chris Craik726118b2014-03-07 18:27:49 -0800126 if (divisor == 0) return -1.0f; // error, invalid divisor
127
128#if DEBUG_SHADOW
ztenghui9122b1b2014-10-03 11:21:11 -0700129 float interpVal = (dx * (p1.y - rayOrigin.y) + dy * rayOrigin.x - dy * p1.x) / divisor;
ztenghui99af9422014-03-14 14:35:54 -0700130 if (interpVal < 0 || interpVal > 1) {
131 ALOGW("rayIntersectPoints is hitting outside the segment %f", interpVal);
132 }
Chris Craik726118b2014-03-07 18:27:49 -0800133#endif
134
ztenghui9122b1b2014-10-03 11:21:11 -0700135 float distance = (p1.x * (rayOrigin.y - p2.y) + p2.x * (p1.y - rayOrigin.y) +
Chris Craik726118b2014-03-07 18:27:49 -0800136 rayOrigin.x * (p2.y - p1.y)) / divisor;
137
138 return distance; // may be negative in error cases
ztenghui7b4516e2014-01-07 10:42:55 -0800139}
140
141/**
ztenghui7b4516e2014-01-07 10:42:55 -0800142 * Sort points by their X coordinates
143 *
144 * @param points the points as a Vector2 array.
145 * @param pointsLength the number of vertices of the polygon.
146 */
147void SpotShadow::xsort(Vector2* points, int pointsLength) {
John Reck1e4209e2015-07-01 09:54:47 -0700148 auto cmp = [](const Vector2& a, const Vector2& b) -> bool {
149 return a.x < b.x;
150 };
151 std::sort(points, points + pointsLength, cmp);
ztenghui7b4516e2014-01-07 10:42:55 -0800152}
153
154/**
155 * compute the convex hull of a collection of Points
156 *
157 * @param points the points as a Vector2 array.
158 * @param pointsLength the number of vertices of the polygon.
159 * @param retPoly pre allocated array of floats to put the vertices
160 * @return the number of points in the polygon 0 if no intersection
161 */
162int SpotShadow::hull(Vector2* points, int pointsLength, Vector2* retPoly) {
163 xsort(points, pointsLength);
164 int n = pointsLength;
165 Vector2 lUpper[n];
166 lUpper[0] = points[0];
167 lUpper[1] = points[1];
168
169 int lUpperSize = 2;
170
171 for (int i = 2; i < n; i++) {
172 lUpper[lUpperSize] = points[i];
173 lUpperSize++;
174
ztenghuif5ca8b42014-01-27 15:53:28 -0800175 while (lUpperSize > 2 && !ccw(
176 lUpper[lUpperSize - 3].x, lUpper[lUpperSize - 3].y,
177 lUpper[lUpperSize - 2].x, lUpper[lUpperSize - 2].y,
178 lUpper[lUpperSize - 1].x, lUpper[lUpperSize - 1].y)) {
ztenghui7b4516e2014-01-07 10:42:55 -0800179 // Remove the middle point of the three last
180 lUpper[lUpperSize - 2].x = lUpper[lUpperSize - 1].x;
181 lUpper[lUpperSize - 2].y = lUpper[lUpperSize - 1].y;
182 lUpperSize--;
183 }
184 }
185
186 Vector2 lLower[n];
187 lLower[0] = points[n - 1];
188 lLower[1] = points[n - 2];
189
190 int lLowerSize = 2;
191
192 for (int i = n - 3; i >= 0; i--) {
193 lLower[lLowerSize] = points[i];
194 lLowerSize++;
195
ztenghuif5ca8b42014-01-27 15:53:28 -0800196 while (lLowerSize > 2 && !ccw(
197 lLower[lLowerSize - 3].x, lLower[lLowerSize - 3].y,
198 lLower[lLowerSize - 2].x, lLower[lLowerSize - 2].y,
199 lLower[lLowerSize - 1].x, lLower[lLowerSize - 1].y)) {
ztenghui7b4516e2014-01-07 10:42:55 -0800200 // Remove the middle point of the three last
201 lLower[lLowerSize - 2] = lLower[lLowerSize - 1];
202 lLowerSize--;
203 }
204 }
ztenghui7b4516e2014-01-07 10:42:55 -0800205
Chris Craik726118b2014-03-07 18:27:49 -0800206 // output points in CW ordering
207 const int total = lUpperSize + lLowerSize - 2;
208 int outIndex = total - 1;
ztenghui7b4516e2014-01-07 10:42:55 -0800209 for (int i = 0; i < lUpperSize; i++) {
Chris Craik726118b2014-03-07 18:27:49 -0800210 retPoly[outIndex] = lUpper[i];
211 outIndex--;
ztenghui7b4516e2014-01-07 10:42:55 -0800212 }
213
214 for (int i = 1; i < lLowerSize - 1; i++) {
Chris Craik726118b2014-03-07 18:27:49 -0800215 retPoly[outIndex] = lLower[i];
216 outIndex--;
ztenghui7b4516e2014-01-07 10:42:55 -0800217 }
218 // TODO: Add test harness which verify that all the points are inside the hull.
Chris Craik726118b2014-03-07 18:27:49 -0800219 return total;
ztenghui7b4516e2014-01-07 10:42:55 -0800220}
221
222/**
ztenghuif5ca8b42014-01-27 15:53:28 -0800223 * Test whether the 3 points form a counter clockwise turn.
ztenghui7b4516e2014-01-07 10:42:55 -0800224 *
ztenghui7b4516e2014-01-07 10:42:55 -0800225 * @return true if a right hand turn
226 */
ztenghui9122b1b2014-10-03 11:21:11 -0700227bool SpotShadow::ccw(float ax, float ay, float bx, float by,
228 float cx, float cy) {
ztenghui7b4516e2014-01-07 10:42:55 -0800229 return (bx - ax) * (cy - ay) - (by - ay) * (cx - ax) > EPSILON;
230}
231
232/**
ztenghui7b4516e2014-01-07 10:42:55 -0800233 * Sort points about a center point
234 *
235 * @param poly The in and out polyogon as a Vector2 array.
236 * @param polyLength The number of vertices of the polygon.
237 * @param center the center ctr[0] = x , ctr[1] = y to sort around.
238 */
239void SpotShadow::sort(Vector2* poly, int polyLength, const Vector2& center) {
240 quicksortCirc(poly, 0, polyLength - 1, center);
241}
242
243/**
ztenghui7b4516e2014-01-07 10:42:55 -0800244 * Swap points pointed to by i and j
245 */
246void SpotShadow::swap(Vector2* points, int i, int j) {
247 Vector2 temp = points[i];
248 points[i] = points[j];
249 points[j] = temp;
250}
251
252/**
253 * quick sort implementation about the center.
254 */
255void SpotShadow::quicksortCirc(Vector2* points, int low, int high,
256 const Vector2& center) {
257 int i = low, j = high;
258 int p = low + (high - low) / 2;
259 float pivot = angle(points[p], center);
260 while (i <= j) {
Chris Craik726118b2014-03-07 18:27:49 -0800261 while (angle(points[i], center) > pivot) {
ztenghui7b4516e2014-01-07 10:42:55 -0800262 i++;
263 }
Chris Craik726118b2014-03-07 18:27:49 -0800264 while (angle(points[j], center) < pivot) {
ztenghui7b4516e2014-01-07 10:42:55 -0800265 j--;
266 }
267
268 if (i <= j) {
269 swap(points, i, j);
270 i++;
271 j--;
272 }
273 }
274 if (low < j) quicksortCirc(points, low, j, center);
275 if (i < high) quicksortCirc(points, i, high, center);
276}
277
278/**
ztenghui7b4516e2014-01-07 10:42:55 -0800279 * Test whether a point is inside the polygon.
280 *
281 * @param testPoint the point to test
282 * @param poly the polygon
283 * @return true if the testPoint is inside the poly.
284 */
285bool SpotShadow::testPointInsidePolygon(const Vector2 testPoint,
286 const Vector2* poly, int len) {
287 bool c = false;
ztenghui9122b1b2014-10-03 11:21:11 -0700288 float testx = testPoint.x;
289 float testy = testPoint.y;
ztenghui7b4516e2014-01-07 10:42:55 -0800290 for (int i = 0, j = len - 1; i < len; j = i++) {
ztenghui9122b1b2014-10-03 11:21:11 -0700291 float startX = poly[j].x;
292 float startY = poly[j].y;
293 float endX = poly[i].x;
294 float endY = poly[i].y;
ztenghui7b4516e2014-01-07 10:42:55 -0800295
ztenghui512e6432014-09-10 13:08:20 -0700296 if (((endY > testy) != (startY > testy))
297 && (testx < (startX - endX) * (testy - endY)
ztenghui7b4516e2014-01-07 10:42:55 -0800298 / (startY - endY) + endX)) {
299 c = !c;
300 }
301 }
302 return c;
303}
304
305/**
306 * Make the polygon turn clockwise.
307 *
308 * @param polygon the polygon as a Vector2 array.
309 * @param len the number of points of the polygon
310 */
311void SpotShadow::makeClockwise(Vector2* polygon, int len) {
Chris Craikd41c4d82015-01-05 15:51:13 -0800312 if (polygon == nullptr || len == 0) {
ztenghui7b4516e2014-01-07 10:42:55 -0800313 return;
314 }
ztenghui2e023f32014-04-28 16:43:13 -0700315 if (!ShadowTessellator::isClockwise(polygon, len)) {
ztenghui7b4516e2014-01-07 10:42:55 -0800316 reverse(polygon, len);
317 }
318}
319
320/**
ztenghui7b4516e2014-01-07 10:42:55 -0800321 * Reverse the polygon
322 *
323 * @param polygon the polygon as a Vector2 array
324 * @param len the number of points of the polygon
325 */
326void SpotShadow::reverse(Vector2* polygon, int len) {
327 int n = len / 2;
328 for (int i = 0; i < n; i++) {
329 Vector2 tmp = polygon[i];
330 int k = len - 1 - i;
331 polygon[i] = polygon[k];
332 polygon[k] = tmp;
333 }
334}
335
336/**
ztenghui7b4516e2014-01-07 10:42:55 -0800337 * Compute a horizontal circular polygon about point (x , y , height) of radius
338 * (size)
339 *
340 * @param points number of the points of the output polygon.
341 * @param lightCenter the center of the light.
342 * @param size the light size.
343 * @param ret result polygon.
344 */
345void SpotShadow::computeLightPolygon(int points, const Vector3& lightCenter,
346 float size, Vector3* ret) {
347 // TODO: Caching all the sin / cos values and store them in a look up table.
348 for (int i = 0; i < points; i++) {
ztenghui9122b1b2014-10-03 11:21:11 -0700349 float angle = 2 * i * M_PI / points;
Chris Craik726118b2014-03-07 18:27:49 -0800350 ret[i].x = cosf(angle) * size + lightCenter.x;
351 ret[i].y = sinf(angle) * size + lightCenter.y;
ztenghui7b4516e2014-01-07 10:42:55 -0800352 ret[i].z = lightCenter.z;
353 }
354}
355
356/**
ztenghui512e6432014-09-10 13:08:20 -0700357 * From light center, project one vertex to the z=0 surface and get the outline.
ztenghui7b4516e2014-01-07 10:42:55 -0800358 *
ztenghui512e6432014-09-10 13:08:20 -0700359 * @param outline The result which is the outline position.
360 * @param lightCenter The center of light.
361 * @param polyVertex The input polygon's vertex.
362 *
363 * @return float The ratio of (polygon.z / light.z - polygon.z)
ztenghui7b4516e2014-01-07 10:42:55 -0800364 */
ztenghuic50a03d2014-08-21 13:47:54 -0700365float SpotShadow::projectCasterToOutline(Vector2& outline,
366 const Vector3& lightCenter, const Vector3& polyVertex) {
367 float lightToPolyZ = lightCenter.z - polyVertex.z;
368 float ratioZ = CASTER_Z_CAP_RATIO;
369 if (lightToPolyZ != 0) {
370 // If any caster's vertex is almost above the light, we just keep it as 95%
371 // of the height of the light.
ztenghui3bd3fa12014-08-25 14:42:27 -0700372 ratioZ = MathUtils::clamp(polyVertex.z / lightToPolyZ, 0.0f, CASTER_Z_CAP_RATIO);
ztenghuic50a03d2014-08-21 13:47:54 -0700373 }
374
375 outline.x = polyVertex.x - ratioZ * (lightCenter.x - polyVertex.x);
376 outline.y = polyVertex.y - ratioZ * (lightCenter.y - polyVertex.y);
377 return ratioZ;
378}
379
380/**
381 * Generate the shadow spot light of shape lightPoly and a object poly
382 *
383 * @param isCasterOpaque whether the caster is opaque
384 * @param lightCenter the center of the light
385 * @param lightSize the radius of the light
386 * @param poly x,y,z vertexes of a convex polygon that occludes the light source
387 * @param polyLength number of vertexes of the occluding polygon
388 * @param shadowTriangleStrip return an (x,y,alpha) triangle strip representing the shadow. Return
389 * empty strip if error.
390 */
391void SpotShadow::createSpotShadow(bool isCasterOpaque, const Vector3& lightCenter,
392 float lightSize, const Vector3* poly, int polyLength, const Vector3& polyCentroid,
393 VertexBuffer& shadowTriangleStrip) {
ztenghui3bd3fa12014-08-25 14:42:27 -0700394 if (CC_UNLIKELY(lightCenter.z <= 0)) {
395 ALOGW("Relative Light Z is not positive. No spot shadow!");
396 return;
397 }
ztenghui512e6432014-09-10 13:08:20 -0700398 if (CC_UNLIKELY(polyLength < 3)) {
399#if DEBUG_SHADOW
400 ALOGW("Invalid polygon length. No spot shadow!");
401#endif
402 return;
403 }
ztenghuic50a03d2014-08-21 13:47:54 -0700404 OutlineData outlineData[polyLength];
405 Vector2 outlineCentroid;
406 // Calculate the projected outline for each polygon's vertices from the light center.
407 //
408 // O Light
409 // /
410 // /
411 // . Polygon vertex
412 // /
413 // /
414 // O Outline vertices
415 //
416 // Ratio = (Poly - Outline) / (Light - Poly)
417 // Outline.x = Poly.x - Ratio * (Light.x - Poly.x)
418 // Outline's radius / Light's radius = Ratio
419
420 // Compute the last outline vertex to make sure we can get the normal and outline
421 // in one single loop.
422 projectCasterToOutline(outlineData[polyLength - 1].position, lightCenter,
423 poly[polyLength - 1]);
424
425 // Take the outline's polygon, calculate the normal for each outline edge.
426 int currentNormalIndex = polyLength - 1;
427 int nextNormalIndex = 0;
428
429 for (int i = 0; i < polyLength; i++) {
430 float ratioZ = projectCasterToOutline(outlineData[i].position,
431 lightCenter, poly[i]);
432 outlineData[i].radius = ratioZ * lightSize;
433
434 outlineData[currentNormalIndex].normal = ShadowTessellator::calculateNormal(
435 outlineData[currentNormalIndex].position,
436 outlineData[nextNormalIndex].position);
437 currentNormalIndex = (currentNormalIndex + 1) % polyLength;
438 nextNormalIndex++;
439 }
440
441 projectCasterToOutline(outlineCentroid, lightCenter, polyCentroid);
442
443 int penumbraIndex = 0;
ztenghui512e6432014-09-10 13:08:20 -0700444 // Then each polygon's vertex produce at minmal 2 penumbra vertices.
445 // Since the size can be dynamic here, we keep track of the size and update
446 // the real size at the end.
447 int allocatedPenumbraLength = 2 * polyLength + SPOT_MAX_EXTRA_CORNER_VERTEX_NUMBER;
448 Vector2 penumbra[allocatedPenumbraLength];
449 int totalExtraCornerSliceNumber = 0;
ztenghuic50a03d2014-08-21 13:47:54 -0700450
451 Vector2 umbra[polyLength];
ztenghuic50a03d2014-08-21 13:47:54 -0700452
ztenghui512e6432014-09-10 13:08:20 -0700453 // When centroid is covered by all circles from outline, then we consider
454 // the umbra is invalid, and we will tune down the shadow strength.
ztenghuic50a03d2014-08-21 13:47:54 -0700455 bool hasValidUmbra = true;
ztenghui512e6432014-09-10 13:08:20 -0700456 // We need the minimal of RaitoVI to decrease the spot shadow strength accordingly.
457 float minRaitoVI = FLT_MAX;
ztenghuic50a03d2014-08-21 13:47:54 -0700458
459 for (int i = 0; i < polyLength; i++) {
460 // Generate all the penumbra's vertices only using the (outline vertex + normal * radius)
461 // There is no guarantee that the penumbra is still convex, but for
462 // each outline vertex, it will connect to all its corresponding penumbra vertices as
463 // triangle fans. And for neighber penumbra vertex, it will be a trapezoid.
464 //
465 // Penumbra Vertices marked as Pi
466 // Outline Vertices marked as Vi
467 // (P3)
468 // (P2) | ' (P4)
469 // (P1)' | | '
470 // ' | | '
471 // (P0) ------------------------------------------------(P5)
472 // | (V0) |(V1)
473 // | |
474 // | |
475 // | |
476 // | |
477 // | |
478 // | |
479 // | |
480 // | |
481 // (V3)-----------------------------------(V2)
482 int preNormalIndex = (i + polyLength - 1) % polyLength;
ztenghuic50a03d2014-08-21 13:47:54 -0700483
ztenghui512e6432014-09-10 13:08:20 -0700484 const Vector2& previousNormal = outlineData[preNormalIndex].normal;
485 const Vector2& currentNormal = outlineData[i].normal;
486
487 // Depending on how roundness we want for each corner, we can subdivide
ztenghuic50a03d2014-08-21 13:47:54 -0700488 // further here and/or introduce some heuristic to decide how much the
489 // subdivision should be.
ztenghui512e6432014-09-10 13:08:20 -0700490 int currentExtraSliceNumber = ShadowTessellator::getExtraVertexNumber(
491 previousNormal, currentNormal, SPOT_CORNER_RADIANS_DIVISOR);
ztenghuic50a03d2014-08-21 13:47:54 -0700492
ztenghui512e6432014-09-10 13:08:20 -0700493 int currentCornerSliceNumber = 1 + currentExtraSliceNumber;
494 totalExtraCornerSliceNumber += currentExtraSliceNumber;
495#if DEBUG_SHADOW
496 ALOGD("currentExtraSliceNumber should be %d", currentExtraSliceNumber);
497 ALOGD("currentCornerSliceNumber should be %d", currentCornerSliceNumber);
498 ALOGD("totalCornerSliceNumber is %d", totalExtraCornerSliceNumber);
499#endif
500 if (CC_UNLIKELY(totalExtraCornerSliceNumber > SPOT_MAX_EXTRA_CORNER_VERTEX_NUMBER)) {
501 currentCornerSliceNumber = 1;
502 }
503 for (int k = 0; k <= currentCornerSliceNumber; k++) {
504 Vector2 avgNormal =
505 (previousNormal * (currentCornerSliceNumber - k) + currentNormal * k) /
506 currentCornerSliceNumber;
507 avgNormal.normalize();
508 penumbra[penumbraIndex++] = outlineData[i].position +
509 avgNormal * outlineData[i].radius;
510 }
ztenghuic50a03d2014-08-21 13:47:54 -0700511
ztenghuic50a03d2014-08-21 13:47:54 -0700512
513 // Compute the umbra by the intersection from the outline's centroid!
514 //
515 // (V) ------------------------------------
516 // | ' |
517 // | ' |
518 // | ' (I) |
519 // | ' |
520 // | ' (C) |
521 // | |
522 // | |
523 // | |
524 // | |
525 // ------------------------------------
526 //
527 // Connect a line b/t the outline vertex (V) and the centroid (C), it will
528 // intersect with the outline vertex's circle at point (I).
529 // Now, ratioVI = VI / VC, ratioIC = IC / VC
530 // Then the intersetion point can be computed as Ixy = Vxy * ratioIC + Cxy * ratioVI;
531 //
ztenghui512e6432014-09-10 13:08:20 -0700532 // When all of the outline circles cover the the outline centroid, (like I is
ztenghuic50a03d2014-08-21 13:47:54 -0700533 // on the other side of C), there is no real umbra any more, so we just fake
534 // a small area around the centroid as the umbra, and tune down the spot
535 // shadow's umbra strength to simulate the effect the whole shadow will
536 // become lighter in this case.
537 // The ratio can be simulated by using the inverse of maximum of ratioVI for
538 // all (V).
ztenghui512e6432014-09-10 13:08:20 -0700539 float distOutline = (outlineData[i].position - outlineCentroid).length();
ztenghui3bd3fa12014-08-25 14:42:27 -0700540 if (CC_UNLIKELY(distOutline == 0)) {
ztenghuic50a03d2014-08-21 13:47:54 -0700541 // If the outline has 0 area, then there is no spot shadow anyway.
542 ALOGW("Outline has 0 area, no spot shadow!");
543 return;
544 }
ztenghui512e6432014-09-10 13:08:20 -0700545
546 float ratioVI = outlineData[i].radius / distOutline;
Chris Craik9db58c02015-08-19 15:19:18 -0700547 minRaitoVI = std::min(minRaitoVI, ratioVI);
ztenghui512e6432014-09-10 13:08:20 -0700548 if (ratioVI >= (1 - FAKE_UMBRA_SIZE_RATIO)) {
549 ratioVI = (1 - FAKE_UMBRA_SIZE_RATIO);
ztenghuic50a03d2014-08-21 13:47:54 -0700550 }
551 // When we know we don't have valid umbra, don't bother to compute the
552 // values below. But we can't skip the loop yet since we want to know the
553 // maximum ratio.
ztenghui512e6432014-09-10 13:08:20 -0700554 float ratioIC = 1 - ratioVI;
555 umbra[i] = outlineData[i].position * ratioIC + outlineCentroid * ratioVI;
ztenghuic50a03d2014-08-21 13:47:54 -0700556 }
557
ztenghui512e6432014-09-10 13:08:20 -0700558 hasValidUmbra = (minRaitoVI <= 1.0);
ztenghuic50a03d2014-08-21 13:47:54 -0700559 float shadowStrengthScale = 1.0;
560 if (!hasValidUmbra) {
ztenghui512e6432014-09-10 13:08:20 -0700561#if DEBUG_SHADOW
ztenghuic50a03d2014-08-21 13:47:54 -0700562 ALOGW("The object is too close to the light or too small, no real umbra!");
ztenghui512e6432014-09-10 13:08:20 -0700563#endif
ztenghuic50a03d2014-08-21 13:47:54 -0700564 for (int i = 0; i < polyLength; i++) {
565 umbra[i] = outlineData[i].position * FAKE_UMBRA_SIZE_RATIO +
ztenghui512e6432014-09-10 13:08:20 -0700566 outlineCentroid * (1 - FAKE_UMBRA_SIZE_RATIO);
ztenghuic50a03d2014-08-21 13:47:54 -0700567 }
ztenghui512e6432014-09-10 13:08:20 -0700568 shadowStrengthScale = 1.0 / minRaitoVI;
ztenghuic50a03d2014-08-21 13:47:54 -0700569 }
570
ztenghui512e6432014-09-10 13:08:20 -0700571 int penumbraLength = penumbraIndex;
572 int umbraLength = polyLength;
573
ztenghuic50a03d2014-08-21 13:47:54 -0700574#if DEBUG_SHADOW
ztenghui512e6432014-09-10 13:08:20 -0700575 ALOGD("penumbraLength is %d , allocatedPenumbraLength %d", penumbraLength, allocatedPenumbraLength);
ztenghuic50a03d2014-08-21 13:47:54 -0700576 dumpPolygon(poly, polyLength, "input poly");
ztenghuic50a03d2014-08-21 13:47:54 -0700577 dumpPolygon(penumbra, penumbraLength, "penumbra");
ztenghui512e6432014-09-10 13:08:20 -0700578 dumpPolygon(umbra, umbraLength, "umbra");
ztenghuic50a03d2014-08-21 13:47:54 -0700579 ALOGD("hasValidUmbra is %d and shadowStrengthScale is %f", hasValidUmbra, shadowStrengthScale);
580#endif
581
ztenghui512e6432014-09-10 13:08:20 -0700582 // The penumbra and umbra needs to be in convex shape to keep consistency
583 // and quality.
584 // Since we are still shooting rays to penumbra, it needs to be convex.
585 // Umbra can be represented as a fan from the centroid, but visually umbra
586 // looks nicer when it is convex.
587 Vector2 finalUmbra[umbraLength];
588 Vector2 finalPenumbra[penumbraLength];
589 int finalUmbraLength = hull(umbra, umbraLength, finalUmbra);
590 int finalPenumbraLength = hull(penumbra, penumbraLength, finalPenumbra);
591
592 generateTriangleStrip(isCasterOpaque, shadowStrengthScale, finalPenumbra,
593 finalPenumbraLength, finalUmbra, finalUmbraLength, poly, polyLength,
594 shadowTriangleStrip, outlineCentroid);
595
ztenghuic50a03d2014-08-21 13:47:54 -0700596}
597
ztenghui7b4516e2014-01-07 10:42:55 -0800598/**
ztenghui7b4516e2014-01-07 10:42:55 -0800599 * This is only for experimental purpose.
600 * After intersections are calculated, we could smooth the polygon if needed.
601 * So far, we don't think it is more appealing yet.
602 *
603 * @param level The level of smoothness.
604 * @param rays The total number of rays.
605 * @param rayDist (In and Out) The distance for each ray.
606 *
607 */
608void SpotShadow::smoothPolygon(int level, int rays, float* rayDist) {
609 for (int k = 0; k < level; k++) {
610 for (int i = 0; i < rays; i++) {
611 float p1 = rayDist[(rays - 1 + i) % rays];
612 float p2 = rayDist[i];
613 float p3 = rayDist[(i + 1) % rays];
614 rayDist[i] = (p1 + p2 * 2 + p3) / 4;
615 }
616 }
617}
618
ztenghuid2dcd6f2014-10-29 16:04:29 -0700619// Index pair is meant for storing the tessellation information for the penumbra
620// area. One index must come from exterior tangent of the circles, the other one
621// must come from the interior tangent of the circles.
622struct IndexPair {
623 int outerIndex;
624 int innerIndex;
625};
ztenghui512e6432014-09-10 13:08:20 -0700626
ztenghuid2dcd6f2014-10-29 16:04:29 -0700627// For one penumbra vertex, find the cloest umbra vertex and return its index.
628inline int getClosestUmbraIndex(const Vector2& pivot, const Vector2* polygon, int polygonLength) {
629 float minLengthSquared = FLT_MAX;
ztenghui512e6432014-09-10 13:08:20 -0700630 int resultIndex = -1;
ztenghuid2dcd6f2014-10-29 16:04:29 -0700631 bool hasDecreased = false;
632 // Starting with some negative offset, assuming both umbra and penumbra are starting
633 // at the same angle, this can help to find the result faster.
634 // Normally, loop 3 times, we can find the closest point.
635 int offset = polygonLength - 2;
636 for (int i = 0; i < polygonLength; i++) {
637 int currentIndex = (i + offset) % polygonLength;
638 float currentLengthSquared = (pivot - polygon[currentIndex]).lengthSquared();
639 if (currentLengthSquared < minLengthSquared) {
640 if (minLengthSquared != FLT_MAX) {
641 hasDecreased = true;
ztenghui512e6432014-09-10 13:08:20 -0700642 }
ztenghuid2dcd6f2014-10-29 16:04:29 -0700643 minLengthSquared = currentLengthSquared;
644 resultIndex = currentIndex;
645 } else if (currentLengthSquared > minLengthSquared && hasDecreased) {
646 // Early break b/c we have found the closet one and now the length
647 // is increasing again.
648 break;
ztenghui512e6432014-09-10 13:08:20 -0700649 }
650 }
ztenghuid2dcd6f2014-10-29 16:04:29 -0700651 if(resultIndex == -1) {
652 ALOGE("resultIndex is -1, the polygon must be invalid!");
653 resultIndex = 0;
ztenghui512e6432014-09-10 13:08:20 -0700654 }
655 return resultIndex;
656}
657
ztenghui39320632014-11-12 10:56:15 -0800658// Allow some epsilon here since the later ray intersection did allow for some small
659// floating point error, when the intersection point is slightly outside the segment.
ztenghuid2dcd6f2014-10-29 16:04:29 -0700660inline bool sameDirections(bool isPositiveCross, float a, float b) {
661 if (isPositiveCross) {
ztenghui39320632014-11-12 10:56:15 -0800662 return a >= -EPSILON && b >= -EPSILON;
ztenghuid2dcd6f2014-10-29 16:04:29 -0700663 } else {
ztenghui39320632014-11-12 10:56:15 -0800664 return a <= EPSILON && b <= EPSILON;
ztenghui512e6432014-09-10 13:08:20 -0700665 }
ztenghuid2dcd6f2014-10-29 16:04:29 -0700666}
ztenghui512e6432014-09-10 13:08:20 -0700667
ztenghuid2dcd6f2014-10-29 16:04:29 -0700668// Find the right polygon edge to shoot the ray at.
669inline int findPolyIndex(bool isPositiveCross, int startPolyIndex, const Vector2& umbraDir,
670 const Vector2* polyToCentroid, int polyLength) {
671 // Make sure we loop with a bound.
672 for (int i = 0; i < polyLength; i++) {
673 int currentIndex = (i + startPolyIndex) % polyLength;
674 const Vector2& currentToCentroid = polyToCentroid[currentIndex];
675 const Vector2& nextToCentroid = polyToCentroid[(currentIndex + 1) % polyLength];
ztenghui512e6432014-09-10 13:08:20 -0700676
ztenghuid2dcd6f2014-10-29 16:04:29 -0700677 float currentCrossUmbra = currentToCentroid.cross(umbraDir);
678 float umbraCrossNext = umbraDir.cross(nextToCentroid);
679 if (sameDirections(isPositiveCross, currentCrossUmbra, umbraCrossNext)) {
ztenghui512e6432014-09-10 13:08:20 -0700680#if DEBUG_SHADOW
ztenghuid2dcd6f2014-10-29 16:04:29 -0700681 ALOGD("findPolyIndex loop %d times , index %d", i, currentIndex );
ztenghui512e6432014-09-10 13:08:20 -0700682#endif
ztenghuid2dcd6f2014-10-29 16:04:29 -0700683 return currentIndex;
ztenghui512e6432014-09-10 13:08:20 -0700684 }
ztenghuid2dcd6f2014-10-29 16:04:29 -0700685 }
686 LOG_ALWAYS_FATAL("Can't find the right polygon's edge from startPolyIndex %d", startPolyIndex);
687 return -1;
688}
ztenghui512e6432014-09-10 13:08:20 -0700689
ztenghuid2dcd6f2014-10-29 16:04:29 -0700690// Generate the index pair for penumbra / umbra vertices, and more penumbra vertices
691// if needed.
692inline void genNewPenumbraAndPairWithUmbra(const Vector2* penumbra, int penumbraLength,
693 const Vector2* umbra, int umbraLength, Vector2* newPenumbra, int& newPenumbraIndex,
694 IndexPair* verticesPair, int& verticesPairIndex) {
695 // In order to keep everything in just one loop, we need to pre-compute the
696 // closest umbra vertex for the last penumbra vertex.
697 int previousClosestUmbraIndex = getClosestUmbraIndex(penumbra[penumbraLength - 1],
698 umbra, umbraLength);
699 for (int i = 0; i < penumbraLength; i++) {
700 const Vector2& currentPenumbraVertex = penumbra[i];
701 // For current penumbra vertex, starting from previousClosestUmbraIndex,
702 // then check the next one until the distance increase.
703 // The last one before the increase is the umbra vertex we need to pair with.
ztenghui39320632014-11-12 10:56:15 -0800704 float currentLengthSquared =
705 (currentPenumbraVertex - umbra[previousClosestUmbraIndex]).lengthSquared();
706 int currentClosestUmbraIndex = previousClosestUmbraIndex;
ztenghuid2dcd6f2014-10-29 16:04:29 -0700707 int indexDelta = 0;
708 for (int j = 1; j < umbraLength; j++) {
709 int newUmbraIndex = (previousClosestUmbraIndex + j) % umbraLength;
710 float newLengthSquared = (currentPenumbraVertex - umbra[newUmbraIndex]).lengthSquared();
711 if (newLengthSquared > currentLengthSquared) {
ztenghui39320632014-11-12 10:56:15 -0800712 // currentClosestUmbraIndex is the umbra vertex's index which has
713 // currently found smallest distance, so we can simply break here.
ztenghuid2dcd6f2014-10-29 16:04:29 -0700714 break;
715 } else {
716 currentLengthSquared = newLengthSquared;
717 indexDelta++;
ztenghui39320632014-11-12 10:56:15 -0800718 currentClosestUmbraIndex = newUmbraIndex;
ztenghui512e6432014-09-10 13:08:20 -0700719 }
ztenghuid2dcd6f2014-10-29 16:04:29 -0700720 }
ztenghuid2dcd6f2014-10-29 16:04:29 -0700721
722 if (indexDelta > 1) {
723 // For those umbra don't have penumbra, generate new penumbra vertices by interpolation.
724 //
725 // Assuming Pi for penumbra vertices, and Ui for umbra vertices.
726 // In the case like below P1 paired with U1 and P2 paired with U5.
727 // U2 to U4 are unpaired umbra vertices.
728 //
729 // P1 P2
730 // | |
731 // U1 U2 U3 U4 U5
732 //
733 // We will need to generate 3 more penumbra vertices P1.1, P1.2, P1.3
734 // to pair with U2 to U4.
735 //
736 // P1 P1.1 P1.2 P1.3 P2
737 // | | | | |
738 // U1 U2 U3 U4 U5
739 //
740 // That distance ratio b/t Ui to U1 and Ui to U5 decides its paired penumbra
741 // vertex's location.
742 int newPenumbraNumber = indexDelta - 1;
743
744 float accumulatedDeltaLength[newPenumbraNumber];
745 float totalDeltaLength = 0;
746
747 // To save time, cache the previous umbra vertex info outside the loop
748 // and update each loop.
749 Vector2 previousClosestUmbra = umbra[previousClosestUmbraIndex];
750 Vector2 skippedUmbra;
751 // Use umbra data to precompute the length b/t unpaired umbra vertices,
752 // and its ratio against the total length.
753 for (int k = 0; k < indexDelta; k++) {
754 int skippedUmbraIndex = (previousClosestUmbraIndex + k + 1) % umbraLength;
755 skippedUmbra = umbra[skippedUmbraIndex];
756 float currentDeltaLength = (skippedUmbra - previousClosestUmbra).length();
757
758 totalDeltaLength += currentDeltaLength;
759 accumulatedDeltaLength[k] = totalDeltaLength;
760
761 previousClosestUmbra = skippedUmbra;
762 }
763
764 const Vector2& previousPenumbra = penumbra[(i + penumbraLength - 1) % penumbraLength];
765 // Then for each unpaired umbra vertex, create a new penumbra by the ratio,
766 // and pair them togehter.
767 for (int k = 0; k < newPenumbraNumber; k++) {
768 float weightForCurrentPenumbra = 1.0f;
769 if (totalDeltaLength != 0.0f) {
770 weightForCurrentPenumbra = accumulatedDeltaLength[k] / totalDeltaLength;
771 }
772 float weightForPreviousPenumbra = 1.0f - weightForCurrentPenumbra;
773
774 Vector2 interpolatedPenumbra = currentPenumbraVertex * weightForCurrentPenumbra +
775 previousPenumbra * weightForPreviousPenumbra;
776
777 int skippedUmbraIndex = (previousClosestUmbraIndex + k + 1) % umbraLength;
Andreas Gampeedaecc12014-11-10 20:54:07 -0800778 verticesPair[verticesPairIndex].outerIndex = newPenumbraIndex;
779 verticesPair[verticesPairIndex].innerIndex = skippedUmbraIndex;
780 verticesPairIndex++;
ztenghuid2dcd6f2014-10-29 16:04:29 -0700781 newPenumbra[newPenumbraIndex++] = interpolatedPenumbra;
782 }
783 }
Andreas Gampeedaecc12014-11-10 20:54:07 -0800784 verticesPair[verticesPairIndex].outerIndex = newPenumbraIndex;
785 verticesPair[verticesPairIndex].innerIndex = currentClosestUmbraIndex;
786 verticesPairIndex++;
ztenghuid2dcd6f2014-10-29 16:04:29 -0700787 newPenumbra[newPenumbraIndex++] = currentPenumbraVertex;
788
789 previousClosestUmbraIndex = currentClosestUmbraIndex;
790 }
791}
792
793// Precompute all the polygon's vector, return true if the reference cross product is positive.
794inline bool genPolyToCentroid(const Vector2* poly2d, int polyLength,
795 const Vector2& centroid, Vector2* polyToCentroid) {
796 for (int j = 0; j < polyLength; j++) {
797 polyToCentroid[j] = poly2d[j] - centroid;
ztenghui39320632014-11-12 10:56:15 -0800798 // Normalize these vectors such that we can use epsilon comparison after
799 // computing their cross products with another normalized vector.
800 polyToCentroid[j].normalize();
ztenghuid2dcd6f2014-10-29 16:04:29 -0700801 }
802 float refCrossProduct = 0;
803 for (int j = 0; j < polyLength; j++) {
804 refCrossProduct = polyToCentroid[j].cross(polyToCentroid[(j + 1) % polyLength]);
805 if (refCrossProduct != 0) {
806 break;
ztenghui512e6432014-09-10 13:08:20 -0700807 }
808 }
809
ztenghuid2dcd6f2014-10-29 16:04:29 -0700810 return refCrossProduct > 0;
811}
ztenghui512e6432014-09-10 13:08:20 -0700812
ztenghuid2dcd6f2014-10-29 16:04:29 -0700813// For one umbra vertex, shoot an ray from centroid to it.
814// If the ray hit the polygon first, then return the intersection point as the
815// closer vertex.
816inline Vector2 getCloserVertex(const Vector2& umbraVertex, const Vector2& centroid,
817 const Vector2* poly2d, int polyLength, const Vector2* polyToCentroid,
818 bool isPositiveCross, int& previousPolyIndex) {
819 Vector2 umbraToCentroid = umbraVertex - centroid;
820 float distanceToUmbra = umbraToCentroid.length();
821 umbraToCentroid = umbraToCentroid / distanceToUmbra;
822
823 // previousPolyIndex is updated for each item such that we can minimize the
824 // looping inside findPolyIndex();
825 previousPolyIndex = findPolyIndex(isPositiveCross, previousPolyIndex,
826 umbraToCentroid, polyToCentroid, polyLength);
827
828 float dx = umbraToCentroid.x;
829 float dy = umbraToCentroid.y;
830 float distanceToIntersectPoly = rayIntersectPoints(centroid, dx, dy,
831 poly2d[previousPolyIndex], poly2d[(previousPolyIndex + 1) % polyLength]);
832 if (distanceToIntersectPoly < 0) {
833 distanceToIntersectPoly = 0;
834 }
835
836 // Pick the closer one as the occluded area vertex.
837 Vector2 closerVertex;
838 if (distanceToIntersectPoly < distanceToUmbra) {
839 closerVertex.x = centroid.x + dx * distanceToIntersectPoly;
840 closerVertex.y = centroid.y + dy * distanceToIntersectPoly;
841 } else {
842 closerVertex = umbraVertex;
843 }
844
845 return closerVertex;
ztenghui512e6432014-09-10 13:08:20 -0700846}
847
848/**
849 * Generate a triangle strip given two convex polygon
850**/
Andreas Gampe64bb4132014-11-22 00:35:09 +0000851void SpotShadow::generateTriangleStrip(bool isCasterOpaque, float shadowStrengthScale,
ztenghui512e6432014-09-10 13:08:20 -0700852 Vector2* penumbra, int penumbraLength, Vector2* umbra, int umbraLength,
853 const Vector3* poly, int polyLength, VertexBuffer& shadowTriangleStrip,
854 const Vector2& centroid) {
ztenghui512e6432014-09-10 13:08:20 -0700855 bool hasOccludedUmbraArea = false;
856 Vector2 poly2d[polyLength];
857
858 if (isCasterOpaque) {
859 for (int i = 0; i < polyLength; i++) {
860 poly2d[i].x = poly[i].x;
861 poly2d[i].y = poly[i].y;
862 }
863 // Make sure the centroid is inside the umbra, otherwise, fall back to the
864 // approach as if there is no occluded umbra area.
865 if (testPointInsidePolygon(centroid, poly2d, polyLength)) {
866 hasOccludedUmbraArea = true;
867 }
868 }
869
ztenghuid2dcd6f2014-10-29 16:04:29 -0700870 // For each penumbra vertex, find its corresponding closest umbra vertex index.
871 //
872 // Penumbra Vertices marked as Pi
873 // Umbra Vertices marked as Ui
874 // (P3)
875 // (P2) | ' (P4)
876 // (P1)' | | '
877 // ' | | '
878 // (P0) ------------------------------------------------(P5)
879 // | (U0) |(U1)
880 // | |
881 // | |(U2) (P5.1)
882 // | |
883 // | |
884 // | |
885 // | |
886 // | |
887 // | |
888 // (U4)-----------------------------------(U3) (P6)
889 //
890 // At least, like P0, P1, P2, they will find the matching umbra as U0.
891 // If we jump over some umbra vertex without matching penumbra vertex, then
892 // we will generate some new penumbra vertex by interpolation. Like P6 is
893 // matching U3, but U2 is not matched with any penumbra vertex.
894 // So interpolate P5.1 out and match U2.
895 // In this way, every umbra vertex will have a matching penumbra vertex.
896 //
897 // The total pair number can be as high as umbraLength + penumbraLength.
898 const int maxNewPenumbraLength = umbraLength + penumbraLength;
899 IndexPair verticesPair[maxNewPenumbraLength];
900 int verticesPairIndex = 0;
901
902 // Cache all the existing penumbra vertices and newly interpolated vertices into a
903 // a new array.
904 Vector2 newPenumbra[maxNewPenumbraLength];
905 int newPenumbraIndex = 0;
906
907 // For each penumbra vertex, find its closet umbra vertex by comparing the
908 // neighbor umbra vertices.
909 genNewPenumbraAndPairWithUmbra(penumbra, penumbraLength, umbra, umbraLength, newPenumbra,
910 newPenumbraIndex, verticesPair, verticesPairIndex);
911 ShadowTessellator::checkOverflow(verticesPairIndex, maxNewPenumbraLength, "Spot pair");
912 ShadowTessellator::checkOverflow(newPenumbraIndex, maxNewPenumbraLength, "Spot new penumbra");
913#if DEBUG_SHADOW
914 for (int i = 0; i < umbraLength; i++) {
915 ALOGD("umbra i %d, [%f, %f]", i, umbra[i].x, umbra[i].y);
ztenghui512e6432014-09-10 13:08:20 -0700916 }
ztenghuid2dcd6f2014-10-29 16:04:29 -0700917 for (int i = 0; i < newPenumbraIndex; i++) {
918 ALOGD("new penumbra i %d, [%f, %f]", i, newPenumbra[i].x, newPenumbra[i].y);
919 }
920 for (int i = 0; i < verticesPairIndex; i++) {
921 ALOGD("index i %d, [%d, %d]", i, verticesPair[i].outerIndex, verticesPair[i].innerIndex);
922 }
923#endif
ztenghui512e6432014-09-10 13:08:20 -0700924
ztenghuid2dcd6f2014-10-29 16:04:29 -0700925 // For the size of vertex buffer, we need 3 rings, one has newPenumbraSize,
926 // one has umbraLength, the last one has at most umbraLength.
927 //
928 // For the size of index buffer, the umbra area needs (2 * umbraLength + 2).
929 // The penumbra one can vary a bit, but it is bounded by (2 * verticesPairIndex + 2).
930 // And 2 more for jumping between penumbra to umbra.
931 const int newPenumbraLength = newPenumbraIndex;
932 const int totalVertexCount = newPenumbraLength + umbraLength * 2;
933 const int totalIndexCount = 2 * umbraLength + 2 * verticesPairIndex + 6;
ztenghui512e6432014-09-10 13:08:20 -0700934 AlphaVertex* shadowVertices =
935 shadowTriangleStrip.alloc<AlphaVertex>(totalVertexCount);
936 uint16_t* indexBuffer =
937 shadowTriangleStrip.allocIndices<uint16_t>(totalIndexCount);
ztenghui512e6432014-09-10 13:08:20 -0700938 int vertexBufferIndex = 0;
ztenghuid2dcd6f2014-10-29 16:04:29 -0700939 int indexBufferIndex = 0;
ztenghui512e6432014-09-10 13:08:20 -0700940
ztenghuid2dcd6f2014-10-29 16:04:29 -0700941 // Fill the IB and VB for the penumbra area.
942 for (int i = 0; i < newPenumbraLength; i++) {
943 AlphaVertex::set(&shadowVertices[vertexBufferIndex++], newPenumbra[i].x,
ztenghuiecf091e2015-02-17 13:26:10 -0800944 newPenumbra[i].y, TRANSFORMED_PENUMBRA_ALPHA);
ztenghuid2dcd6f2014-10-29 16:04:29 -0700945 }
946 for (int i = 0; i < umbraLength; i++) {
947 AlphaVertex::set(&shadowVertices[vertexBufferIndex++], umbra[i].x, umbra[i].y,
ztenghuiecf091e2015-02-17 13:26:10 -0800948 TRANSFORMED_UMBRA_ALPHA);
ztenghui512e6432014-09-10 13:08:20 -0700949 }
950
ztenghuid2dcd6f2014-10-29 16:04:29 -0700951 for (int i = 0; i < verticesPairIndex; i++) {
952 indexBuffer[indexBufferIndex++] = verticesPair[i].outerIndex;
953 // All umbra index need to be offseted by newPenumbraSize.
954 indexBuffer[indexBufferIndex++] = verticesPair[i].innerIndex + newPenumbraLength;
955 }
956 indexBuffer[indexBufferIndex++] = verticesPair[0].outerIndex;
957 indexBuffer[indexBufferIndex++] = verticesPair[0].innerIndex + newPenumbraLength;
ztenghui512e6432014-09-10 13:08:20 -0700958
ztenghuid2dcd6f2014-10-29 16:04:29 -0700959 // Now fill the IB and VB for the umbra area.
960 // First duplicated the index from previous strip and the first one for the
961 // degenerated triangles.
962 indexBuffer[indexBufferIndex] = indexBuffer[indexBufferIndex - 1];
963 indexBufferIndex++;
964 indexBuffer[indexBufferIndex++] = newPenumbraLength + 0;
965 // Save the first VB index for umbra area in order to close the loop.
966 int savedStartIndex = vertexBufferIndex;
967
ztenghui512e6432014-09-10 13:08:20 -0700968 if (hasOccludedUmbraArea) {
ztenghuid2dcd6f2014-10-29 16:04:29 -0700969 // Precompute all the polygon's vector, and the reference cross product,
970 // in order to find the right polygon edge for the ray to intersect.
971 Vector2 polyToCentroid[polyLength];
972 bool isPositiveCross = genPolyToCentroid(poly2d, polyLength, centroid, polyToCentroid);
ztenghui512e6432014-09-10 13:08:20 -0700973
ztenghuid2dcd6f2014-10-29 16:04:29 -0700974 // Because both the umbra and polygon are going in the same direction,
975 // we can save the previous polygon index to make sure we have less polygon
976 // vertex to compute for each ray.
977 int previousPolyIndex = 0;
978 for (int i = 0; i < umbraLength; i++) {
979 // Shoot a ray from centroid to each umbra vertices and pick the one with
980 // shorter distance to the centroid, b/t the umbra vertex or the intersection point.
981 Vector2 closerVertex = getCloserVertex(umbra[i], centroid, poly2d, polyLength,
982 polyToCentroid, isPositiveCross, previousPolyIndex);
983
984 // We already stored the umbra vertices, just need to add the occlued umbra's ones.
985 indexBuffer[indexBufferIndex++] = newPenumbraLength + i;
986 indexBuffer[indexBufferIndex++] = vertexBufferIndex;
987 AlphaVertex::set(&shadowVertices[vertexBufferIndex++],
ztenghuiecf091e2015-02-17 13:26:10 -0800988 closerVertex.x, closerVertex.y, TRANSFORMED_UMBRA_ALPHA);
ztenghui512e6432014-09-10 13:08:20 -0700989 }
ztenghui512e6432014-09-10 13:08:20 -0700990 } else {
ztenghuid2dcd6f2014-10-29 16:04:29 -0700991 // If there is no occluded umbra at all, then draw the triangle fan
992 // starting from the centroid to all umbra vertices.
ztenghui512e6432014-09-10 13:08:20 -0700993 int lastCentroidIndex = vertexBufferIndex;
994 AlphaVertex::set(&shadowVertices[vertexBufferIndex++], centroid.x,
ztenghuiecf091e2015-02-17 13:26:10 -0800995 centroid.y, TRANSFORMED_UMBRA_ALPHA);
ztenghuid2dcd6f2014-10-29 16:04:29 -0700996 for (int i = 0; i < umbraLength; i++) {
997 indexBuffer[indexBufferIndex++] = newPenumbraLength + i;
ztenghui512e6432014-09-10 13:08:20 -0700998 indexBuffer[indexBufferIndex++] = lastCentroidIndex;
999 }
ztenghui512e6432014-09-10 13:08:20 -07001000 }
ztenghuid2dcd6f2014-10-29 16:04:29 -07001001 // Closing the umbra area triangle's loop here.
1002 indexBuffer[indexBufferIndex++] = newPenumbraLength;
1003 indexBuffer[indexBufferIndex++] = savedStartIndex;
ztenghui512e6432014-09-10 13:08:20 -07001004
1005 // At the end, update the real index and vertex buffer size.
1006 shadowTriangleStrip.updateVertexCount(vertexBufferIndex);
1007 shadowTriangleStrip.updateIndexCount(indexBufferIndex);
1008 ShadowTessellator::checkOverflow(vertexBufferIndex, totalVertexCount, "Spot Vertex Buffer");
1009 ShadowTessellator::checkOverflow(indexBufferIndex, totalIndexCount, "Spot Index Buffer");
1010
Chris Craik117bdbc2015-02-05 10:12:38 -08001011 shadowTriangleStrip.setMeshFeatureFlags(VertexBuffer::kAlpha | VertexBuffer::kIndices);
ztenghui512e6432014-09-10 13:08:20 -07001012 shadowTriangleStrip.computeBounds<AlphaVertex>();
1013}
1014
ztenghuif5ca8b42014-01-27 15:53:28 -08001015#if DEBUG_SHADOW
1016
1017#define TEST_POINT_NUMBER 128
ztenghuif5ca8b42014-01-27 15:53:28 -08001018/**
1019 * Calculate the bounds for generating random test points.
1020 */
1021void SpotShadow::updateBound(const Vector2 inVector, Vector2& lowerBound,
ztenghui512e6432014-09-10 13:08:20 -07001022 Vector2& upperBound) {
ztenghuif5ca8b42014-01-27 15:53:28 -08001023 if (inVector.x < lowerBound.x) {
1024 lowerBound.x = inVector.x;
1025 }
1026
1027 if (inVector.y < lowerBound.y) {
1028 lowerBound.y = inVector.y;
1029 }
1030
1031 if (inVector.x > upperBound.x) {
1032 upperBound.x = inVector.x;
1033 }
1034
1035 if (inVector.y > upperBound.y) {
1036 upperBound.y = inVector.y;
1037 }
1038}
1039
1040/**
1041 * For debug purpose, when things go wrong, dump the whole polygon data.
1042 */
ztenghuic50a03d2014-08-21 13:47:54 -07001043void SpotShadow::dumpPolygon(const Vector2* poly, int polyLength, const char* polyName) {
1044 for (int i = 0; i < polyLength; i++) {
1045 ALOGD("polygon %s i %d x %f y %f", polyName, i, poly[i].x, poly[i].y);
1046 }
1047}
1048
1049/**
1050 * For debug purpose, when things go wrong, dump the whole polygon data.
1051 */
1052void SpotShadow::dumpPolygon(const Vector3* poly, int polyLength, const char* polyName) {
ztenghuif5ca8b42014-01-27 15:53:28 -08001053 for (int i = 0; i < polyLength; i++) {
1054 ALOGD("polygon %s i %d x %f y %f", polyName, i, poly[i].x, poly[i].y);
1055 }
1056}
1057
1058/**
1059 * Test whether the polygon is convex.
1060 */
1061bool SpotShadow::testConvex(const Vector2* polygon, int polygonLength,
1062 const char* name) {
1063 bool isConvex = true;
1064 for (int i = 0; i < polygonLength; i++) {
1065 Vector2 start = polygon[i];
1066 Vector2 middle = polygon[(i + 1) % polygonLength];
1067 Vector2 end = polygon[(i + 2) % polygonLength];
1068
ztenghui9122b1b2014-10-03 11:21:11 -07001069 float delta = (float(middle.x) - start.x) * (float(end.y) - start.y) -
1070 (float(middle.y) - start.y) * (float(end.x) - start.x);
ztenghuif5ca8b42014-01-27 15:53:28 -08001071 bool isCCWOrCoLinear = (delta >= EPSILON);
1072
1073 if (isCCWOrCoLinear) {
ztenghui50ecf842014-03-11 16:52:30 -07001074 ALOGW("(Error Type 2): polygon (%s) is not a convex b/c start (x %f, y %f),"
ztenghuif5ca8b42014-01-27 15:53:28 -08001075 "middle (x %f, y %f) and end (x %f, y %f) , delta is %f !!!",
1076 name, start.x, start.y, middle.x, middle.y, end.x, end.y, delta);
1077 isConvex = false;
1078 break;
1079 }
1080 }
1081 return isConvex;
1082}
1083
1084/**
1085 * Test whether or not the polygon (intersection) is within the 2 input polygons.
1086 * Using Marte Carlo method, we generate a random point, and if it is inside the
1087 * intersection, then it must be inside both source polygons.
1088 */
1089void SpotShadow::testIntersection(const Vector2* poly1, int poly1Length,
1090 const Vector2* poly2, int poly2Length,
1091 const Vector2* intersection, int intersectionLength) {
1092 // Find the min and max of x and y.
ztenghuic50a03d2014-08-21 13:47:54 -07001093 Vector2 lowerBound = {FLT_MAX, FLT_MAX};
1094 Vector2 upperBound = {-FLT_MAX, -FLT_MAX};
ztenghuif5ca8b42014-01-27 15:53:28 -08001095 for (int i = 0; i < poly1Length; i++) {
1096 updateBound(poly1[i], lowerBound, upperBound);
1097 }
1098 for (int i = 0; i < poly2Length; i++) {
1099 updateBound(poly2[i], lowerBound, upperBound);
1100 }
1101
1102 bool dumpPoly = false;
1103 for (int k = 0; k < TEST_POINT_NUMBER; k++) {
1104 // Generate a random point between minX, minY and maxX, maxY.
ztenghui9122b1b2014-10-03 11:21:11 -07001105 float randomX = rand() / float(RAND_MAX);
1106 float randomY = rand() / float(RAND_MAX);
ztenghuif5ca8b42014-01-27 15:53:28 -08001107
1108 Vector2 testPoint;
1109 testPoint.x = lowerBound.x + randomX * (upperBound.x - lowerBound.x);
1110 testPoint.y = lowerBound.y + randomY * (upperBound.y - lowerBound.y);
1111
1112 // If the random point is in both poly 1 and 2, then it must be intersection.
1113 if (testPointInsidePolygon(testPoint, intersection, intersectionLength)) {
1114 if (!testPointInsidePolygon(testPoint, poly1, poly1Length)) {
1115 dumpPoly = true;
ztenghui50ecf842014-03-11 16:52:30 -07001116 ALOGW("(Error Type 1): one point (%f, %f) in the intersection is"
ztenghui512e6432014-09-10 13:08:20 -07001117 " not in the poly1",
ztenghuif5ca8b42014-01-27 15:53:28 -08001118 testPoint.x, testPoint.y);
1119 }
1120
1121 if (!testPointInsidePolygon(testPoint, poly2, poly2Length)) {
1122 dumpPoly = true;
ztenghui50ecf842014-03-11 16:52:30 -07001123 ALOGW("(Error Type 1): one point (%f, %f) in the intersection is"
ztenghui512e6432014-09-10 13:08:20 -07001124 " not in the poly2",
ztenghuif5ca8b42014-01-27 15:53:28 -08001125 testPoint.x, testPoint.y);
1126 }
1127 }
1128 }
1129
1130 if (dumpPoly) {
1131 dumpPolygon(intersection, intersectionLength, "intersection");
1132 for (int i = 1; i < intersectionLength; i++) {
1133 Vector2 delta = intersection[i] - intersection[i - 1];
1134 ALOGD("Intersetion i, %d Vs i-1 is delta %f", i, delta.lengthSquared());
1135 }
1136
1137 dumpPolygon(poly1, poly1Length, "poly 1");
1138 dumpPolygon(poly2, poly2Length, "poly 2");
1139 }
1140}
1141#endif
1142
ztenghui7b4516e2014-01-07 10:42:55 -08001143}; // namespace uirenderer
1144}; // namespace android