blob: b8c98041a6bf87ad2fdd6d731f88ba8766cd393b [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
17#define LOG_TAG "OpenGLRenderer"
18
ztenghui512e6432014-09-10 13:08:20 -070019// The highest z value can't be higher than (CASTER_Z_CAP_RATIO * light.z)
ztenghuic50a03d2014-08-21 13:47:54 -070020#define CASTER_Z_CAP_RATIO 0.95f
ztenghui512e6432014-09-10 13:08:20 -070021
22// When there is no umbra, then just fake the umbra using
23// centroid * (1 - FAKE_UMBRA_SIZE_RATIO) + outline * FAKE_UMBRA_SIZE_RATIO
24#define FAKE_UMBRA_SIZE_RATIO 0.05f
25
26// When the polygon is about 90 vertices, the penumbra + umbra can reach 270 rays.
27// That is consider pretty fine tessllated polygon so far.
28// This is just to prevent using too much some memory when edge slicing is not
29// needed any more.
30#define FINE_TESSELLATED_POLYGON_RAY_NUMBER 270
31/**
32 * Extra vertices for the corner for smoother corner.
33 * Only for outer loop.
34 * Note that we use such extra memory to avoid an extra loop.
35 */
36// For half circle, we could add EXTRA_VERTEX_PER_PI vertices.
37// Set to 1 if we don't want to have any.
38#define SPOT_EXTRA_CORNER_VERTEX_PER_PI 18
39
40// For the whole polygon, the sum of all the deltas b/t normals is 2 * M_PI,
41// therefore, the maximum number of extra vertices will be twice bigger.
42#define SPOT_MAX_EXTRA_CORNER_VERTEX_NUMBER (2 * SPOT_EXTRA_CORNER_VERTEX_PER_PI)
43
44// For each RADIANS_DIVISOR, we would allocate one more vertex b/t the normals.
45#define SPOT_CORNER_RADIANS_DIVISOR (M_PI / SPOT_EXTRA_CORNER_VERTEX_PER_PI)
46
ztenghuiecf091e2015-02-17 13:26:10 -080047// For performance, we use (1 - alpha) value for the shader input.
48#define TRANSFORMED_PENUMBRA_ALPHA 1.0f
49#define TRANSFORMED_UMBRA_ALPHA 0.0f
ztenghui7b4516e2014-01-07 10:42:55 -080050
John Reck1e4209e2015-07-01 09:54:47 -070051#include <algorithm>
ztenghui7b4516e2014-01-07 10:42:55 -080052#include <math.h>
ztenghuif5ca8b42014-01-27 15:53:28 -080053#include <stdlib.h>
ztenghui7b4516e2014-01-07 10:42:55 -080054#include <utils/Log.h>
55
ztenghui63d41ab2014-02-14 13:13:41 -080056#include "ShadowTessellator.h"
ztenghui7b4516e2014-01-07 10:42:55 -080057#include "SpotShadow.h"
58#include "Vertex.h"
Tom Hudson2dc236b2014-10-15 15:46:42 -040059#include "VertexBuffer.h"
ztenghuic50a03d2014-08-21 13:47:54 -070060#include "utils/MathUtils.h"
ztenghui7b4516e2014-01-07 10:42:55 -080061
ztenghuic50a03d2014-08-21 13:47:54 -070062// TODO: After we settle down the new algorithm, we can remove the old one and
63// its utility functions.
64// Right now, we still need to keep it for comparison purpose and future expansion.
ztenghui7b4516e2014-01-07 10:42:55 -080065namespace android {
66namespace uirenderer {
67
ztenghui9122b1b2014-10-03 11:21:11 -070068static const float EPSILON = 1e-7;
Chris Craik726118b2014-03-07 18:27:49 -080069
ztenghui7b4516e2014-01-07 10:42:55 -080070/**
ztenghuic50a03d2014-08-21 13:47:54 -070071 * For each polygon's vertex, the light center will project it to the receiver
72 * as one of the outline vertex.
73 * For each outline vertex, we need to store the position and normal.
74 * Normal here is defined against the edge by the current vertex and the next vertex.
75 */
76struct OutlineData {
77 Vector2 position;
78 Vector2 normal;
79 float radius;
80};
81
82/**
ztenghui512e6432014-09-10 13:08:20 -070083 * For each vertex, we need to keep track of its angle, whether it is penumbra or
84 * umbra, and its corresponding vertex index.
85 */
86struct SpotShadow::VertexAngleData {
87 // The angle to the vertex from the centroid.
88 float mAngle;
89 // True is the vertex comes from penumbra, otherwise it comes from umbra.
90 bool mIsPenumbra;
91 // The index of the vertex described by this data.
92 int mVertexIndex;
93 void set(float angle, bool isPenumbra, int index) {
94 mAngle = angle;
95 mIsPenumbra = isPenumbra;
96 mVertexIndex = index;
97 }
98};
99
100/**
Chris Craik726118b2014-03-07 18:27:49 -0800101 * Calculate the angle between and x and a y coordinate.
102 * The atan2 range from -PI to PI.
ztenghui7b4516e2014-01-07 10:42:55 -0800103 */
Chris Craikb79a3e32014-03-11 12:20:17 -0700104static float angle(const Vector2& point, const Vector2& center) {
Chris Craik726118b2014-03-07 18:27:49 -0800105 return atan2(point.y - center.y, point.x - center.x);
106}
107
108/**
109 * Calculate the intersection of a ray with the line segment defined by two points.
110 *
111 * Returns a negative value in error conditions.
112
113 * @param rayOrigin The start of the ray
114 * @param dx The x vector of the ray
115 * @param dy The y vector of the ray
116 * @param p1 The first point defining the line segment
117 * @param p2 The second point defining the line segment
118 * @return The distance along the ray if it intersects with the line segment, negative if otherwise
119 */
Chris Craikb79a3e32014-03-11 12:20:17 -0700120static float rayIntersectPoints(const Vector2& rayOrigin, float dx, float dy,
Chris Craik726118b2014-03-07 18:27:49 -0800121 const Vector2& p1, const Vector2& p2) {
122 // The math below is derived from solving this formula, basically the
123 // intersection point should stay on both the ray and the edge of (p1, p2).
124 // solve([p1x+t*(p2x-p1x)=dx*t2+px,p1y+t*(p2y-p1y)=dy*t2+py],[t,t2]);
125
ztenghui9122b1b2014-10-03 11:21:11 -0700126 float divisor = (dx * (p1.y - p2.y) + dy * p2.x - dy * p1.x);
Chris Craik726118b2014-03-07 18:27:49 -0800127 if (divisor == 0) return -1.0f; // error, invalid divisor
128
129#if DEBUG_SHADOW
ztenghui9122b1b2014-10-03 11:21:11 -0700130 float interpVal = (dx * (p1.y - rayOrigin.y) + dy * rayOrigin.x - dy * p1.x) / divisor;
ztenghui99af9422014-03-14 14:35:54 -0700131 if (interpVal < 0 || interpVal > 1) {
132 ALOGW("rayIntersectPoints is hitting outside the segment %f", interpVal);
133 }
Chris Craik726118b2014-03-07 18:27:49 -0800134#endif
135
ztenghui9122b1b2014-10-03 11:21:11 -0700136 float distance = (p1.x * (rayOrigin.y - p2.y) + p2.x * (p1.y - rayOrigin.y) +
Chris Craik726118b2014-03-07 18:27:49 -0800137 rayOrigin.x * (p2.y - p1.y)) / divisor;
138
139 return distance; // may be negative in error cases
ztenghui7b4516e2014-01-07 10:42:55 -0800140}
141
142/**
ztenghui7b4516e2014-01-07 10:42:55 -0800143 * Sort points by their X coordinates
144 *
145 * @param points the points as a Vector2 array.
146 * @param pointsLength the number of vertices of the polygon.
147 */
148void SpotShadow::xsort(Vector2* points, int pointsLength) {
John Reck1e4209e2015-07-01 09:54:47 -0700149 auto cmp = [](const Vector2& a, const Vector2& b) -> bool {
150 return a.x < b.x;
151 };
152 std::sort(points, points + pointsLength, cmp);
ztenghui7b4516e2014-01-07 10:42:55 -0800153}
154
155/**
156 * compute the convex hull of a collection of Points
157 *
158 * @param points the points as a Vector2 array.
159 * @param pointsLength the number of vertices of the polygon.
160 * @param retPoly pre allocated array of floats to put the vertices
161 * @return the number of points in the polygon 0 if no intersection
162 */
163int SpotShadow::hull(Vector2* points, int pointsLength, Vector2* retPoly) {
164 xsort(points, pointsLength);
165 int n = pointsLength;
166 Vector2 lUpper[n];
167 lUpper[0] = points[0];
168 lUpper[1] = points[1];
169
170 int lUpperSize = 2;
171
172 for (int i = 2; i < n; i++) {
173 lUpper[lUpperSize] = points[i];
174 lUpperSize++;
175
ztenghuif5ca8b42014-01-27 15:53:28 -0800176 while (lUpperSize > 2 && !ccw(
177 lUpper[lUpperSize - 3].x, lUpper[lUpperSize - 3].y,
178 lUpper[lUpperSize - 2].x, lUpper[lUpperSize - 2].y,
179 lUpper[lUpperSize - 1].x, lUpper[lUpperSize - 1].y)) {
ztenghui7b4516e2014-01-07 10:42:55 -0800180 // Remove the middle point of the three last
181 lUpper[lUpperSize - 2].x = lUpper[lUpperSize - 1].x;
182 lUpper[lUpperSize - 2].y = lUpper[lUpperSize - 1].y;
183 lUpperSize--;
184 }
185 }
186
187 Vector2 lLower[n];
188 lLower[0] = points[n - 1];
189 lLower[1] = points[n - 2];
190
191 int lLowerSize = 2;
192
193 for (int i = n - 3; i >= 0; i--) {
194 lLower[lLowerSize] = points[i];
195 lLowerSize++;
196
ztenghuif5ca8b42014-01-27 15:53:28 -0800197 while (lLowerSize > 2 && !ccw(
198 lLower[lLowerSize - 3].x, lLower[lLowerSize - 3].y,
199 lLower[lLowerSize - 2].x, lLower[lLowerSize - 2].y,
200 lLower[lLowerSize - 1].x, lLower[lLowerSize - 1].y)) {
ztenghui7b4516e2014-01-07 10:42:55 -0800201 // Remove the middle point of the three last
202 lLower[lLowerSize - 2] = lLower[lLowerSize - 1];
203 lLowerSize--;
204 }
205 }
ztenghui7b4516e2014-01-07 10:42:55 -0800206
Chris Craik726118b2014-03-07 18:27:49 -0800207 // output points in CW ordering
208 const int total = lUpperSize + lLowerSize - 2;
209 int outIndex = total - 1;
ztenghui7b4516e2014-01-07 10:42:55 -0800210 for (int i = 0; i < lUpperSize; i++) {
Chris Craik726118b2014-03-07 18:27:49 -0800211 retPoly[outIndex] = lUpper[i];
212 outIndex--;
ztenghui7b4516e2014-01-07 10:42:55 -0800213 }
214
215 for (int i = 1; i < lLowerSize - 1; i++) {
Chris Craik726118b2014-03-07 18:27:49 -0800216 retPoly[outIndex] = lLower[i];
217 outIndex--;
ztenghui7b4516e2014-01-07 10:42:55 -0800218 }
219 // TODO: Add test harness which verify that all the points are inside the hull.
Chris Craik726118b2014-03-07 18:27:49 -0800220 return total;
ztenghui7b4516e2014-01-07 10:42:55 -0800221}
222
223/**
ztenghuif5ca8b42014-01-27 15:53:28 -0800224 * Test whether the 3 points form a counter clockwise turn.
ztenghui7b4516e2014-01-07 10:42:55 -0800225 *
ztenghui7b4516e2014-01-07 10:42:55 -0800226 * @return true if a right hand turn
227 */
ztenghui9122b1b2014-10-03 11:21:11 -0700228bool SpotShadow::ccw(float ax, float ay, float bx, float by,
229 float cx, float cy) {
ztenghui7b4516e2014-01-07 10:42:55 -0800230 return (bx - ax) * (cy - ay) - (by - ay) * (cx - ax) > EPSILON;
231}
232
233/**
ztenghui7b4516e2014-01-07 10:42:55 -0800234 * Sort points about a center point
235 *
236 * @param poly The in and out polyogon as a Vector2 array.
237 * @param polyLength The number of vertices of the polygon.
238 * @param center the center ctr[0] = x , ctr[1] = y to sort around.
239 */
240void SpotShadow::sort(Vector2* poly, int polyLength, const Vector2& center) {
241 quicksortCirc(poly, 0, polyLength - 1, center);
242}
243
244/**
ztenghui7b4516e2014-01-07 10:42:55 -0800245 * Swap points pointed to by i and j
246 */
247void SpotShadow::swap(Vector2* points, int i, int j) {
248 Vector2 temp = points[i];
249 points[i] = points[j];
250 points[j] = temp;
251}
252
253/**
254 * quick sort implementation about the center.
255 */
256void SpotShadow::quicksortCirc(Vector2* points, int low, int high,
257 const Vector2& center) {
258 int i = low, j = high;
259 int p = low + (high - low) / 2;
260 float pivot = angle(points[p], center);
261 while (i <= j) {
Chris Craik726118b2014-03-07 18:27:49 -0800262 while (angle(points[i], center) > pivot) {
ztenghui7b4516e2014-01-07 10:42:55 -0800263 i++;
264 }
Chris Craik726118b2014-03-07 18:27:49 -0800265 while (angle(points[j], center) < pivot) {
ztenghui7b4516e2014-01-07 10:42:55 -0800266 j--;
267 }
268
269 if (i <= j) {
270 swap(points, i, j);
271 i++;
272 j--;
273 }
274 }
275 if (low < j) quicksortCirc(points, low, j, center);
276 if (i < high) quicksortCirc(points, i, high, center);
277}
278
279/**
ztenghui7b4516e2014-01-07 10:42:55 -0800280 * Test whether a point is inside the polygon.
281 *
282 * @param testPoint the point to test
283 * @param poly the polygon
284 * @return true if the testPoint is inside the poly.
285 */
286bool SpotShadow::testPointInsidePolygon(const Vector2 testPoint,
287 const Vector2* poly, int len) {
288 bool c = false;
ztenghui9122b1b2014-10-03 11:21:11 -0700289 float testx = testPoint.x;
290 float testy = testPoint.y;
ztenghui7b4516e2014-01-07 10:42:55 -0800291 for (int i = 0, j = len - 1; i < len; j = i++) {
ztenghui9122b1b2014-10-03 11:21:11 -0700292 float startX = poly[j].x;
293 float startY = poly[j].y;
294 float endX = poly[i].x;
295 float endY = poly[i].y;
ztenghui7b4516e2014-01-07 10:42:55 -0800296
ztenghui512e6432014-09-10 13:08:20 -0700297 if (((endY > testy) != (startY > testy))
298 && (testx < (startX - endX) * (testy - endY)
ztenghui7b4516e2014-01-07 10:42:55 -0800299 / (startY - endY) + endX)) {
300 c = !c;
301 }
302 }
303 return c;
304}
305
306/**
307 * Make the polygon turn clockwise.
308 *
309 * @param polygon the polygon as a Vector2 array.
310 * @param len the number of points of the polygon
311 */
312void SpotShadow::makeClockwise(Vector2* polygon, int len) {
Chris Craikd41c4d82015-01-05 15:51:13 -0800313 if (polygon == nullptr || len == 0) {
ztenghui7b4516e2014-01-07 10:42:55 -0800314 return;
315 }
ztenghui2e023f32014-04-28 16:43:13 -0700316 if (!ShadowTessellator::isClockwise(polygon, len)) {
ztenghui7b4516e2014-01-07 10:42:55 -0800317 reverse(polygon, len);
318 }
319}
320
321/**
ztenghui7b4516e2014-01-07 10:42:55 -0800322 * Reverse the polygon
323 *
324 * @param polygon the polygon as a Vector2 array
325 * @param len the number of points of the polygon
326 */
327void SpotShadow::reverse(Vector2* polygon, int len) {
328 int n = len / 2;
329 for (int i = 0; i < n; i++) {
330 Vector2 tmp = polygon[i];
331 int k = len - 1 - i;
332 polygon[i] = polygon[k];
333 polygon[k] = tmp;
334 }
335}
336
337/**
ztenghui7b4516e2014-01-07 10:42:55 -0800338 * Compute a horizontal circular polygon about point (x , y , height) of radius
339 * (size)
340 *
341 * @param points number of the points of the output polygon.
342 * @param lightCenter the center of the light.
343 * @param size the light size.
344 * @param ret result polygon.
345 */
346void SpotShadow::computeLightPolygon(int points, const Vector3& lightCenter,
347 float size, Vector3* ret) {
348 // TODO: Caching all the sin / cos values and store them in a look up table.
349 for (int i = 0; i < points; i++) {
ztenghui9122b1b2014-10-03 11:21:11 -0700350 float angle = 2 * i * M_PI / points;
Chris Craik726118b2014-03-07 18:27:49 -0800351 ret[i].x = cosf(angle) * size + lightCenter.x;
352 ret[i].y = sinf(angle) * size + lightCenter.y;
ztenghui7b4516e2014-01-07 10:42:55 -0800353 ret[i].z = lightCenter.z;
354 }
355}
356
357/**
ztenghui512e6432014-09-10 13:08:20 -0700358 * From light center, project one vertex to the z=0 surface and get the outline.
ztenghui7b4516e2014-01-07 10:42:55 -0800359 *
ztenghui512e6432014-09-10 13:08:20 -0700360 * @param outline The result which is the outline position.
361 * @param lightCenter The center of light.
362 * @param polyVertex The input polygon's vertex.
363 *
364 * @return float The ratio of (polygon.z / light.z - polygon.z)
ztenghui7b4516e2014-01-07 10:42:55 -0800365 */
ztenghuic50a03d2014-08-21 13:47:54 -0700366float SpotShadow::projectCasterToOutline(Vector2& outline,
367 const Vector3& lightCenter, const Vector3& polyVertex) {
368 float lightToPolyZ = lightCenter.z - polyVertex.z;
369 float ratioZ = CASTER_Z_CAP_RATIO;
370 if (lightToPolyZ != 0) {
371 // If any caster's vertex is almost above the light, we just keep it as 95%
372 // of the height of the light.
ztenghui3bd3fa12014-08-25 14:42:27 -0700373 ratioZ = MathUtils::clamp(polyVertex.z / lightToPolyZ, 0.0f, CASTER_Z_CAP_RATIO);
ztenghuic50a03d2014-08-21 13:47:54 -0700374 }
375
376 outline.x = polyVertex.x - ratioZ * (lightCenter.x - polyVertex.x);
377 outline.y = polyVertex.y - ratioZ * (lightCenter.y - polyVertex.y);
378 return ratioZ;
379}
380
381/**
382 * Generate the shadow spot light of shape lightPoly and a object poly
383 *
384 * @param isCasterOpaque whether the caster is opaque
385 * @param lightCenter the center of the light
386 * @param lightSize the radius of the light
387 * @param poly x,y,z vertexes of a convex polygon that occludes the light source
388 * @param polyLength number of vertexes of the occluding polygon
389 * @param shadowTriangleStrip return an (x,y,alpha) triangle strip representing the shadow. Return
390 * empty strip if error.
391 */
392void SpotShadow::createSpotShadow(bool isCasterOpaque, const Vector3& lightCenter,
393 float lightSize, const Vector3* poly, int polyLength, const Vector3& polyCentroid,
394 VertexBuffer& shadowTriangleStrip) {
ztenghui3bd3fa12014-08-25 14:42:27 -0700395 if (CC_UNLIKELY(lightCenter.z <= 0)) {
396 ALOGW("Relative Light Z is not positive. No spot shadow!");
397 return;
398 }
ztenghui512e6432014-09-10 13:08:20 -0700399 if (CC_UNLIKELY(polyLength < 3)) {
400#if DEBUG_SHADOW
401 ALOGW("Invalid polygon length. No spot shadow!");
402#endif
403 return;
404 }
ztenghuic50a03d2014-08-21 13:47:54 -0700405 OutlineData outlineData[polyLength];
406 Vector2 outlineCentroid;
407 // Calculate the projected outline for each polygon's vertices from the light center.
408 //
409 // O Light
410 // /
411 // /
412 // . Polygon vertex
413 // /
414 // /
415 // O Outline vertices
416 //
417 // Ratio = (Poly - Outline) / (Light - Poly)
418 // Outline.x = Poly.x - Ratio * (Light.x - Poly.x)
419 // Outline's radius / Light's radius = Ratio
420
421 // Compute the last outline vertex to make sure we can get the normal and outline
422 // in one single loop.
423 projectCasterToOutline(outlineData[polyLength - 1].position, lightCenter,
424 poly[polyLength - 1]);
425
426 // Take the outline's polygon, calculate the normal for each outline edge.
427 int currentNormalIndex = polyLength - 1;
428 int nextNormalIndex = 0;
429
430 for (int i = 0; i < polyLength; i++) {
431 float ratioZ = projectCasterToOutline(outlineData[i].position,
432 lightCenter, poly[i]);
433 outlineData[i].radius = ratioZ * lightSize;
434
435 outlineData[currentNormalIndex].normal = ShadowTessellator::calculateNormal(
436 outlineData[currentNormalIndex].position,
437 outlineData[nextNormalIndex].position);
438 currentNormalIndex = (currentNormalIndex + 1) % polyLength;
439 nextNormalIndex++;
440 }
441
442 projectCasterToOutline(outlineCentroid, lightCenter, polyCentroid);
443
444 int penumbraIndex = 0;
ztenghui512e6432014-09-10 13:08:20 -0700445 // Then each polygon's vertex produce at minmal 2 penumbra vertices.
446 // Since the size can be dynamic here, we keep track of the size and update
447 // the real size at the end.
448 int allocatedPenumbraLength = 2 * polyLength + SPOT_MAX_EXTRA_CORNER_VERTEX_NUMBER;
449 Vector2 penumbra[allocatedPenumbraLength];
450 int totalExtraCornerSliceNumber = 0;
ztenghuic50a03d2014-08-21 13:47:54 -0700451
452 Vector2 umbra[polyLength];
ztenghuic50a03d2014-08-21 13:47:54 -0700453
ztenghui512e6432014-09-10 13:08:20 -0700454 // When centroid is covered by all circles from outline, then we consider
455 // the umbra is invalid, and we will tune down the shadow strength.
ztenghuic50a03d2014-08-21 13:47:54 -0700456 bool hasValidUmbra = true;
ztenghui512e6432014-09-10 13:08:20 -0700457 // We need the minimal of RaitoVI to decrease the spot shadow strength accordingly.
458 float minRaitoVI = FLT_MAX;
ztenghuic50a03d2014-08-21 13:47:54 -0700459
460 for (int i = 0; i < polyLength; i++) {
461 // Generate all the penumbra's vertices only using the (outline vertex + normal * radius)
462 // There is no guarantee that the penumbra is still convex, but for
463 // each outline vertex, it will connect to all its corresponding penumbra vertices as
464 // triangle fans. And for neighber penumbra vertex, it will be a trapezoid.
465 //
466 // Penumbra Vertices marked as Pi
467 // Outline Vertices marked as Vi
468 // (P3)
469 // (P2) | ' (P4)
470 // (P1)' | | '
471 // ' | | '
472 // (P0) ------------------------------------------------(P5)
473 // | (V0) |(V1)
474 // | |
475 // | |
476 // | |
477 // | |
478 // | |
479 // | |
480 // | |
481 // | |
482 // (V3)-----------------------------------(V2)
483 int preNormalIndex = (i + polyLength - 1) % polyLength;
ztenghuic50a03d2014-08-21 13:47:54 -0700484
ztenghui512e6432014-09-10 13:08:20 -0700485 const Vector2& previousNormal = outlineData[preNormalIndex].normal;
486 const Vector2& currentNormal = outlineData[i].normal;
487
488 // Depending on how roundness we want for each corner, we can subdivide
ztenghuic50a03d2014-08-21 13:47:54 -0700489 // further here and/or introduce some heuristic to decide how much the
490 // subdivision should be.
ztenghui512e6432014-09-10 13:08:20 -0700491 int currentExtraSliceNumber = ShadowTessellator::getExtraVertexNumber(
492 previousNormal, currentNormal, SPOT_CORNER_RADIANS_DIVISOR);
ztenghuic50a03d2014-08-21 13:47:54 -0700493
ztenghui512e6432014-09-10 13:08:20 -0700494 int currentCornerSliceNumber = 1 + currentExtraSliceNumber;
495 totalExtraCornerSliceNumber += currentExtraSliceNumber;
496#if DEBUG_SHADOW
497 ALOGD("currentExtraSliceNumber should be %d", currentExtraSliceNumber);
498 ALOGD("currentCornerSliceNumber should be %d", currentCornerSliceNumber);
499 ALOGD("totalCornerSliceNumber is %d", totalExtraCornerSliceNumber);
500#endif
501 if (CC_UNLIKELY(totalExtraCornerSliceNumber > SPOT_MAX_EXTRA_CORNER_VERTEX_NUMBER)) {
502 currentCornerSliceNumber = 1;
503 }
504 for (int k = 0; k <= currentCornerSliceNumber; k++) {
505 Vector2 avgNormal =
506 (previousNormal * (currentCornerSliceNumber - k) + currentNormal * k) /
507 currentCornerSliceNumber;
508 avgNormal.normalize();
509 penumbra[penumbraIndex++] = outlineData[i].position +
510 avgNormal * outlineData[i].radius;
511 }
ztenghuic50a03d2014-08-21 13:47:54 -0700512
ztenghuic50a03d2014-08-21 13:47:54 -0700513
514 // Compute the umbra by the intersection from the outline's centroid!
515 //
516 // (V) ------------------------------------
517 // | ' |
518 // | ' |
519 // | ' (I) |
520 // | ' |
521 // | ' (C) |
522 // | |
523 // | |
524 // | |
525 // | |
526 // ------------------------------------
527 //
528 // Connect a line b/t the outline vertex (V) and the centroid (C), it will
529 // intersect with the outline vertex's circle at point (I).
530 // Now, ratioVI = VI / VC, ratioIC = IC / VC
531 // Then the intersetion point can be computed as Ixy = Vxy * ratioIC + Cxy * ratioVI;
532 //
ztenghui512e6432014-09-10 13:08:20 -0700533 // When all of the outline circles cover the the outline centroid, (like I is
ztenghuic50a03d2014-08-21 13:47:54 -0700534 // on the other side of C), there is no real umbra any more, so we just fake
535 // a small area around the centroid as the umbra, and tune down the spot
536 // shadow's umbra strength to simulate the effect the whole shadow will
537 // become lighter in this case.
538 // The ratio can be simulated by using the inverse of maximum of ratioVI for
539 // all (V).
ztenghui512e6432014-09-10 13:08:20 -0700540 float distOutline = (outlineData[i].position - outlineCentroid).length();
ztenghui3bd3fa12014-08-25 14:42:27 -0700541 if (CC_UNLIKELY(distOutline == 0)) {
ztenghuic50a03d2014-08-21 13:47:54 -0700542 // If the outline has 0 area, then there is no spot shadow anyway.
543 ALOGW("Outline has 0 area, no spot shadow!");
544 return;
545 }
ztenghui512e6432014-09-10 13:08:20 -0700546
547 float ratioVI = outlineData[i].radius / distOutline;
548 minRaitoVI = MathUtils::min(minRaitoVI, ratioVI);
549 if (ratioVI >= (1 - FAKE_UMBRA_SIZE_RATIO)) {
550 ratioVI = (1 - FAKE_UMBRA_SIZE_RATIO);
ztenghuic50a03d2014-08-21 13:47:54 -0700551 }
552 // When we know we don't have valid umbra, don't bother to compute the
553 // values below. But we can't skip the loop yet since we want to know the
554 // maximum ratio.
ztenghui512e6432014-09-10 13:08:20 -0700555 float ratioIC = 1 - ratioVI;
556 umbra[i] = outlineData[i].position * ratioIC + outlineCentroid * ratioVI;
ztenghuic50a03d2014-08-21 13:47:54 -0700557 }
558
ztenghui512e6432014-09-10 13:08:20 -0700559 hasValidUmbra = (minRaitoVI <= 1.0);
ztenghuic50a03d2014-08-21 13:47:54 -0700560 float shadowStrengthScale = 1.0;
561 if (!hasValidUmbra) {
ztenghui512e6432014-09-10 13:08:20 -0700562#if DEBUG_SHADOW
ztenghuic50a03d2014-08-21 13:47:54 -0700563 ALOGW("The object is too close to the light or too small, no real umbra!");
ztenghui512e6432014-09-10 13:08:20 -0700564#endif
ztenghuic50a03d2014-08-21 13:47:54 -0700565 for (int i = 0; i < polyLength; i++) {
566 umbra[i] = outlineData[i].position * FAKE_UMBRA_SIZE_RATIO +
ztenghui512e6432014-09-10 13:08:20 -0700567 outlineCentroid * (1 - FAKE_UMBRA_SIZE_RATIO);
ztenghuic50a03d2014-08-21 13:47:54 -0700568 }
ztenghui512e6432014-09-10 13:08:20 -0700569 shadowStrengthScale = 1.0 / minRaitoVI;
ztenghuic50a03d2014-08-21 13:47:54 -0700570 }
571
ztenghui512e6432014-09-10 13:08:20 -0700572 int penumbraLength = penumbraIndex;
573 int umbraLength = polyLength;
574
ztenghuic50a03d2014-08-21 13:47:54 -0700575#if DEBUG_SHADOW
ztenghui512e6432014-09-10 13:08:20 -0700576 ALOGD("penumbraLength is %d , allocatedPenumbraLength %d", penumbraLength, allocatedPenumbraLength);
ztenghuic50a03d2014-08-21 13:47:54 -0700577 dumpPolygon(poly, polyLength, "input poly");
ztenghuic50a03d2014-08-21 13:47:54 -0700578 dumpPolygon(penumbra, penumbraLength, "penumbra");
ztenghui512e6432014-09-10 13:08:20 -0700579 dumpPolygon(umbra, umbraLength, "umbra");
ztenghuic50a03d2014-08-21 13:47:54 -0700580 ALOGD("hasValidUmbra is %d and shadowStrengthScale is %f", hasValidUmbra, shadowStrengthScale);
581#endif
582
ztenghui512e6432014-09-10 13:08:20 -0700583 // The penumbra and umbra needs to be in convex shape to keep consistency
584 // and quality.
585 // Since we are still shooting rays to penumbra, it needs to be convex.
586 // Umbra can be represented as a fan from the centroid, but visually umbra
587 // looks nicer when it is convex.
588 Vector2 finalUmbra[umbraLength];
589 Vector2 finalPenumbra[penumbraLength];
590 int finalUmbraLength = hull(umbra, umbraLength, finalUmbra);
591 int finalPenumbraLength = hull(penumbra, penumbraLength, finalPenumbra);
592
593 generateTriangleStrip(isCasterOpaque, shadowStrengthScale, finalPenumbra,
594 finalPenumbraLength, finalUmbra, finalUmbraLength, poly, polyLength,
595 shadowTriangleStrip, outlineCentroid);
596
ztenghuic50a03d2014-08-21 13:47:54 -0700597}
598
ztenghui7b4516e2014-01-07 10:42:55 -0800599/**
ztenghui7b4516e2014-01-07 10:42:55 -0800600 * This is only for experimental purpose.
601 * After intersections are calculated, we could smooth the polygon if needed.
602 * So far, we don't think it is more appealing yet.
603 *
604 * @param level The level of smoothness.
605 * @param rays The total number of rays.
606 * @param rayDist (In and Out) The distance for each ray.
607 *
608 */
609void SpotShadow::smoothPolygon(int level, int rays, float* rayDist) {
610 for (int k = 0; k < level; k++) {
611 for (int i = 0; i < rays; i++) {
612 float p1 = rayDist[(rays - 1 + i) % rays];
613 float p2 = rayDist[i];
614 float p3 = rayDist[(i + 1) % rays];
615 rayDist[i] = (p1 + p2 * 2 + p3) / 4;
616 }
617 }
618}
619
ztenghuid2dcd6f2014-10-29 16:04:29 -0700620// Index pair is meant for storing the tessellation information for the penumbra
621// area. One index must come from exterior tangent of the circles, the other one
622// must come from the interior tangent of the circles.
623struct IndexPair {
624 int outerIndex;
625 int innerIndex;
626};
ztenghui512e6432014-09-10 13:08:20 -0700627
ztenghuid2dcd6f2014-10-29 16:04:29 -0700628// For one penumbra vertex, find the cloest umbra vertex and return its index.
629inline int getClosestUmbraIndex(const Vector2& pivot, const Vector2* polygon, int polygonLength) {
630 float minLengthSquared = FLT_MAX;
ztenghui512e6432014-09-10 13:08:20 -0700631 int resultIndex = -1;
ztenghuid2dcd6f2014-10-29 16:04:29 -0700632 bool hasDecreased = false;
633 // Starting with some negative offset, assuming both umbra and penumbra are starting
634 // at the same angle, this can help to find the result faster.
635 // Normally, loop 3 times, we can find the closest point.
636 int offset = polygonLength - 2;
637 for (int i = 0; i < polygonLength; i++) {
638 int currentIndex = (i + offset) % polygonLength;
639 float currentLengthSquared = (pivot - polygon[currentIndex]).lengthSquared();
640 if (currentLengthSquared < minLengthSquared) {
641 if (minLengthSquared != FLT_MAX) {
642 hasDecreased = true;
ztenghui512e6432014-09-10 13:08:20 -0700643 }
ztenghuid2dcd6f2014-10-29 16:04:29 -0700644 minLengthSquared = currentLengthSquared;
645 resultIndex = currentIndex;
646 } else if (currentLengthSquared > minLengthSquared && hasDecreased) {
647 // Early break b/c we have found the closet one and now the length
648 // is increasing again.
649 break;
ztenghui512e6432014-09-10 13:08:20 -0700650 }
651 }
ztenghuid2dcd6f2014-10-29 16:04:29 -0700652 if(resultIndex == -1) {
653 ALOGE("resultIndex is -1, the polygon must be invalid!");
654 resultIndex = 0;
ztenghui512e6432014-09-10 13:08:20 -0700655 }
656 return resultIndex;
657}
658
ztenghui39320632014-11-12 10:56:15 -0800659// Allow some epsilon here since the later ray intersection did allow for some small
660// floating point error, when the intersection point is slightly outside the segment.
ztenghuid2dcd6f2014-10-29 16:04:29 -0700661inline bool sameDirections(bool isPositiveCross, float a, float b) {
662 if (isPositiveCross) {
ztenghui39320632014-11-12 10:56:15 -0800663 return a >= -EPSILON && b >= -EPSILON;
ztenghuid2dcd6f2014-10-29 16:04:29 -0700664 } else {
ztenghui39320632014-11-12 10:56:15 -0800665 return a <= EPSILON && b <= EPSILON;
ztenghui512e6432014-09-10 13:08:20 -0700666 }
ztenghuid2dcd6f2014-10-29 16:04:29 -0700667}
ztenghui512e6432014-09-10 13:08:20 -0700668
ztenghuid2dcd6f2014-10-29 16:04:29 -0700669// Find the right polygon edge to shoot the ray at.
670inline int findPolyIndex(bool isPositiveCross, int startPolyIndex, const Vector2& umbraDir,
671 const Vector2* polyToCentroid, int polyLength) {
672 // Make sure we loop with a bound.
673 for (int i = 0; i < polyLength; i++) {
674 int currentIndex = (i + startPolyIndex) % polyLength;
675 const Vector2& currentToCentroid = polyToCentroid[currentIndex];
676 const Vector2& nextToCentroid = polyToCentroid[(currentIndex + 1) % polyLength];
ztenghui512e6432014-09-10 13:08:20 -0700677
ztenghuid2dcd6f2014-10-29 16:04:29 -0700678 float currentCrossUmbra = currentToCentroid.cross(umbraDir);
679 float umbraCrossNext = umbraDir.cross(nextToCentroid);
680 if (sameDirections(isPositiveCross, currentCrossUmbra, umbraCrossNext)) {
ztenghui512e6432014-09-10 13:08:20 -0700681#if DEBUG_SHADOW
ztenghuid2dcd6f2014-10-29 16:04:29 -0700682 ALOGD("findPolyIndex loop %d times , index %d", i, currentIndex );
ztenghui512e6432014-09-10 13:08:20 -0700683#endif
ztenghuid2dcd6f2014-10-29 16:04:29 -0700684 return currentIndex;
ztenghui512e6432014-09-10 13:08:20 -0700685 }
ztenghuid2dcd6f2014-10-29 16:04:29 -0700686 }
687 LOG_ALWAYS_FATAL("Can't find the right polygon's edge from startPolyIndex %d", startPolyIndex);
688 return -1;
689}
ztenghui512e6432014-09-10 13:08:20 -0700690
ztenghuid2dcd6f2014-10-29 16:04:29 -0700691// Generate the index pair for penumbra / umbra vertices, and more penumbra vertices
692// if needed.
693inline void genNewPenumbraAndPairWithUmbra(const Vector2* penumbra, int penumbraLength,
694 const Vector2* umbra, int umbraLength, Vector2* newPenumbra, int& newPenumbraIndex,
695 IndexPair* verticesPair, int& verticesPairIndex) {
696 // In order to keep everything in just one loop, we need to pre-compute the
697 // closest umbra vertex for the last penumbra vertex.
698 int previousClosestUmbraIndex = getClosestUmbraIndex(penumbra[penumbraLength - 1],
699 umbra, umbraLength);
700 for (int i = 0; i < penumbraLength; i++) {
701 const Vector2& currentPenumbraVertex = penumbra[i];
702 // For current penumbra vertex, starting from previousClosestUmbraIndex,
703 // then check the next one until the distance increase.
704 // The last one before the increase is the umbra vertex we need to pair with.
ztenghui39320632014-11-12 10:56:15 -0800705 float currentLengthSquared =
706 (currentPenumbraVertex - umbra[previousClosestUmbraIndex]).lengthSquared();
707 int currentClosestUmbraIndex = previousClosestUmbraIndex;
ztenghuid2dcd6f2014-10-29 16:04:29 -0700708 int indexDelta = 0;
709 for (int j = 1; j < umbraLength; j++) {
710 int newUmbraIndex = (previousClosestUmbraIndex + j) % umbraLength;
711 float newLengthSquared = (currentPenumbraVertex - umbra[newUmbraIndex]).lengthSquared();
712 if (newLengthSquared > currentLengthSquared) {
ztenghui39320632014-11-12 10:56:15 -0800713 // currentClosestUmbraIndex is the umbra vertex's index which has
714 // currently found smallest distance, so we can simply break here.
ztenghuid2dcd6f2014-10-29 16:04:29 -0700715 break;
716 } else {
717 currentLengthSquared = newLengthSquared;
718 indexDelta++;
ztenghui39320632014-11-12 10:56:15 -0800719 currentClosestUmbraIndex = newUmbraIndex;
ztenghui512e6432014-09-10 13:08:20 -0700720 }
ztenghuid2dcd6f2014-10-29 16:04:29 -0700721 }
ztenghuid2dcd6f2014-10-29 16:04:29 -0700722
723 if (indexDelta > 1) {
724 // For those umbra don't have penumbra, generate new penumbra vertices by interpolation.
725 //
726 // Assuming Pi for penumbra vertices, and Ui for umbra vertices.
727 // In the case like below P1 paired with U1 and P2 paired with U5.
728 // U2 to U4 are unpaired umbra vertices.
729 //
730 // P1 P2
731 // | |
732 // U1 U2 U3 U4 U5
733 //
734 // We will need to generate 3 more penumbra vertices P1.1, P1.2, P1.3
735 // to pair with U2 to U4.
736 //
737 // P1 P1.1 P1.2 P1.3 P2
738 // | | | | |
739 // U1 U2 U3 U4 U5
740 //
741 // That distance ratio b/t Ui to U1 and Ui to U5 decides its paired penumbra
742 // vertex's location.
743 int newPenumbraNumber = indexDelta - 1;
744
745 float accumulatedDeltaLength[newPenumbraNumber];
746 float totalDeltaLength = 0;
747
748 // To save time, cache the previous umbra vertex info outside the loop
749 // and update each loop.
750 Vector2 previousClosestUmbra = umbra[previousClosestUmbraIndex];
751 Vector2 skippedUmbra;
752 // Use umbra data to precompute the length b/t unpaired umbra vertices,
753 // and its ratio against the total length.
754 for (int k = 0; k < indexDelta; k++) {
755 int skippedUmbraIndex = (previousClosestUmbraIndex + k + 1) % umbraLength;
756 skippedUmbra = umbra[skippedUmbraIndex];
757 float currentDeltaLength = (skippedUmbra - previousClosestUmbra).length();
758
759 totalDeltaLength += currentDeltaLength;
760 accumulatedDeltaLength[k] = totalDeltaLength;
761
762 previousClosestUmbra = skippedUmbra;
763 }
764
765 const Vector2& previousPenumbra = penumbra[(i + penumbraLength - 1) % penumbraLength];
766 // Then for each unpaired umbra vertex, create a new penumbra by the ratio,
767 // and pair them togehter.
768 for (int k = 0; k < newPenumbraNumber; k++) {
769 float weightForCurrentPenumbra = 1.0f;
770 if (totalDeltaLength != 0.0f) {
771 weightForCurrentPenumbra = accumulatedDeltaLength[k] / totalDeltaLength;
772 }
773 float weightForPreviousPenumbra = 1.0f - weightForCurrentPenumbra;
774
775 Vector2 interpolatedPenumbra = currentPenumbraVertex * weightForCurrentPenumbra +
776 previousPenumbra * weightForPreviousPenumbra;
777
778 int skippedUmbraIndex = (previousClosestUmbraIndex + k + 1) % umbraLength;
Andreas Gampeedaecc12014-11-10 20:54:07 -0800779 verticesPair[verticesPairIndex].outerIndex = newPenumbraIndex;
780 verticesPair[verticesPairIndex].innerIndex = skippedUmbraIndex;
781 verticesPairIndex++;
ztenghuid2dcd6f2014-10-29 16:04:29 -0700782 newPenumbra[newPenumbraIndex++] = interpolatedPenumbra;
783 }
784 }
Andreas Gampeedaecc12014-11-10 20:54:07 -0800785 verticesPair[verticesPairIndex].outerIndex = newPenumbraIndex;
786 verticesPair[verticesPairIndex].innerIndex = currentClosestUmbraIndex;
787 verticesPairIndex++;
ztenghuid2dcd6f2014-10-29 16:04:29 -0700788 newPenumbra[newPenumbraIndex++] = currentPenumbraVertex;
789
790 previousClosestUmbraIndex = currentClosestUmbraIndex;
791 }
792}
793
794// Precompute all the polygon's vector, return true if the reference cross product is positive.
795inline bool genPolyToCentroid(const Vector2* poly2d, int polyLength,
796 const Vector2& centroid, Vector2* polyToCentroid) {
797 for (int j = 0; j < polyLength; j++) {
798 polyToCentroid[j] = poly2d[j] - centroid;
ztenghui39320632014-11-12 10:56:15 -0800799 // Normalize these vectors such that we can use epsilon comparison after
800 // computing their cross products with another normalized vector.
801 polyToCentroid[j].normalize();
ztenghuid2dcd6f2014-10-29 16:04:29 -0700802 }
803 float refCrossProduct = 0;
804 for (int j = 0; j < polyLength; j++) {
805 refCrossProduct = polyToCentroid[j].cross(polyToCentroid[(j + 1) % polyLength]);
806 if (refCrossProduct != 0) {
807 break;
ztenghui512e6432014-09-10 13:08:20 -0700808 }
809 }
810
ztenghuid2dcd6f2014-10-29 16:04:29 -0700811 return refCrossProduct > 0;
812}
ztenghui512e6432014-09-10 13:08:20 -0700813
ztenghuid2dcd6f2014-10-29 16:04:29 -0700814// For one umbra vertex, shoot an ray from centroid to it.
815// If the ray hit the polygon first, then return the intersection point as the
816// closer vertex.
817inline Vector2 getCloserVertex(const Vector2& umbraVertex, const Vector2& centroid,
818 const Vector2* poly2d, int polyLength, const Vector2* polyToCentroid,
819 bool isPositiveCross, int& previousPolyIndex) {
820 Vector2 umbraToCentroid = umbraVertex - centroid;
821 float distanceToUmbra = umbraToCentroid.length();
822 umbraToCentroid = umbraToCentroid / distanceToUmbra;
823
824 // previousPolyIndex is updated for each item such that we can minimize the
825 // looping inside findPolyIndex();
826 previousPolyIndex = findPolyIndex(isPositiveCross, previousPolyIndex,
827 umbraToCentroid, polyToCentroid, polyLength);
828
829 float dx = umbraToCentroid.x;
830 float dy = umbraToCentroid.y;
831 float distanceToIntersectPoly = rayIntersectPoints(centroid, dx, dy,
832 poly2d[previousPolyIndex], poly2d[(previousPolyIndex + 1) % polyLength]);
833 if (distanceToIntersectPoly < 0) {
834 distanceToIntersectPoly = 0;
835 }
836
837 // Pick the closer one as the occluded area vertex.
838 Vector2 closerVertex;
839 if (distanceToIntersectPoly < distanceToUmbra) {
840 closerVertex.x = centroid.x + dx * distanceToIntersectPoly;
841 closerVertex.y = centroid.y + dy * distanceToIntersectPoly;
842 } else {
843 closerVertex = umbraVertex;
844 }
845
846 return closerVertex;
ztenghui512e6432014-09-10 13:08:20 -0700847}
848
849/**
850 * Generate a triangle strip given two convex polygon
851**/
Andreas Gampe64bb4132014-11-22 00:35:09 +0000852void SpotShadow::generateTriangleStrip(bool isCasterOpaque, float shadowStrengthScale,
ztenghui512e6432014-09-10 13:08:20 -0700853 Vector2* penumbra, int penumbraLength, Vector2* umbra, int umbraLength,
854 const Vector3* poly, int polyLength, VertexBuffer& shadowTriangleStrip,
855 const Vector2& centroid) {
ztenghui512e6432014-09-10 13:08:20 -0700856 bool hasOccludedUmbraArea = false;
857 Vector2 poly2d[polyLength];
858
859 if (isCasterOpaque) {
860 for (int i = 0; i < polyLength; i++) {
861 poly2d[i].x = poly[i].x;
862 poly2d[i].y = poly[i].y;
863 }
864 // Make sure the centroid is inside the umbra, otherwise, fall back to the
865 // approach as if there is no occluded umbra area.
866 if (testPointInsidePolygon(centroid, poly2d, polyLength)) {
867 hasOccludedUmbraArea = true;
868 }
869 }
870
ztenghuid2dcd6f2014-10-29 16:04:29 -0700871 // For each penumbra vertex, find its corresponding closest umbra vertex index.
872 //
873 // Penumbra Vertices marked as Pi
874 // Umbra Vertices marked as Ui
875 // (P3)
876 // (P2) | ' (P4)
877 // (P1)' | | '
878 // ' | | '
879 // (P0) ------------------------------------------------(P5)
880 // | (U0) |(U1)
881 // | |
882 // | |(U2) (P5.1)
883 // | |
884 // | |
885 // | |
886 // | |
887 // | |
888 // | |
889 // (U4)-----------------------------------(U3) (P6)
890 //
891 // At least, like P0, P1, P2, they will find the matching umbra as U0.
892 // If we jump over some umbra vertex without matching penumbra vertex, then
893 // we will generate some new penumbra vertex by interpolation. Like P6 is
894 // matching U3, but U2 is not matched with any penumbra vertex.
895 // So interpolate P5.1 out and match U2.
896 // In this way, every umbra vertex will have a matching penumbra vertex.
897 //
898 // The total pair number can be as high as umbraLength + penumbraLength.
899 const int maxNewPenumbraLength = umbraLength + penumbraLength;
900 IndexPair verticesPair[maxNewPenumbraLength];
901 int verticesPairIndex = 0;
902
903 // Cache all the existing penumbra vertices and newly interpolated vertices into a
904 // a new array.
905 Vector2 newPenumbra[maxNewPenumbraLength];
906 int newPenumbraIndex = 0;
907
908 // For each penumbra vertex, find its closet umbra vertex by comparing the
909 // neighbor umbra vertices.
910 genNewPenumbraAndPairWithUmbra(penumbra, penumbraLength, umbra, umbraLength, newPenumbra,
911 newPenumbraIndex, verticesPair, verticesPairIndex);
912 ShadowTessellator::checkOverflow(verticesPairIndex, maxNewPenumbraLength, "Spot pair");
913 ShadowTessellator::checkOverflow(newPenumbraIndex, maxNewPenumbraLength, "Spot new penumbra");
914#if DEBUG_SHADOW
915 for (int i = 0; i < umbraLength; i++) {
916 ALOGD("umbra i %d, [%f, %f]", i, umbra[i].x, umbra[i].y);
ztenghui512e6432014-09-10 13:08:20 -0700917 }
ztenghuid2dcd6f2014-10-29 16:04:29 -0700918 for (int i = 0; i < newPenumbraIndex; i++) {
919 ALOGD("new penumbra i %d, [%f, %f]", i, newPenumbra[i].x, newPenumbra[i].y);
920 }
921 for (int i = 0; i < verticesPairIndex; i++) {
922 ALOGD("index i %d, [%d, %d]", i, verticesPair[i].outerIndex, verticesPair[i].innerIndex);
923 }
924#endif
ztenghui512e6432014-09-10 13:08:20 -0700925
ztenghuid2dcd6f2014-10-29 16:04:29 -0700926 // For the size of vertex buffer, we need 3 rings, one has newPenumbraSize,
927 // one has umbraLength, the last one has at most umbraLength.
928 //
929 // For the size of index buffer, the umbra area needs (2 * umbraLength + 2).
930 // The penumbra one can vary a bit, but it is bounded by (2 * verticesPairIndex + 2).
931 // And 2 more for jumping between penumbra to umbra.
932 const int newPenumbraLength = newPenumbraIndex;
933 const int totalVertexCount = newPenumbraLength + umbraLength * 2;
934 const int totalIndexCount = 2 * umbraLength + 2 * verticesPairIndex + 6;
ztenghui512e6432014-09-10 13:08:20 -0700935 AlphaVertex* shadowVertices =
936 shadowTriangleStrip.alloc<AlphaVertex>(totalVertexCount);
937 uint16_t* indexBuffer =
938 shadowTriangleStrip.allocIndices<uint16_t>(totalIndexCount);
ztenghui512e6432014-09-10 13:08:20 -0700939 int vertexBufferIndex = 0;
ztenghuid2dcd6f2014-10-29 16:04:29 -0700940 int indexBufferIndex = 0;
ztenghui512e6432014-09-10 13:08:20 -0700941
ztenghuid2dcd6f2014-10-29 16:04:29 -0700942 // Fill the IB and VB for the penumbra area.
943 for (int i = 0; i < newPenumbraLength; i++) {
944 AlphaVertex::set(&shadowVertices[vertexBufferIndex++], newPenumbra[i].x,
ztenghuiecf091e2015-02-17 13:26:10 -0800945 newPenumbra[i].y, TRANSFORMED_PENUMBRA_ALPHA);
ztenghuid2dcd6f2014-10-29 16:04:29 -0700946 }
947 for (int i = 0; i < umbraLength; i++) {
948 AlphaVertex::set(&shadowVertices[vertexBufferIndex++], umbra[i].x, umbra[i].y,
ztenghuiecf091e2015-02-17 13:26:10 -0800949 TRANSFORMED_UMBRA_ALPHA);
ztenghui512e6432014-09-10 13:08:20 -0700950 }
951
ztenghuid2dcd6f2014-10-29 16:04:29 -0700952 for (int i = 0; i < verticesPairIndex; i++) {
953 indexBuffer[indexBufferIndex++] = verticesPair[i].outerIndex;
954 // All umbra index need to be offseted by newPenumbraSize.
955 indexBuffer[indexBufferIndex++] = verticesPair[i].innerIndex + newPenumbraLength;
956 }
957 indexBuffer[indexBufferIndex++] = verticesPair[0].outerIndex;
958 indexBuffer[indexBufferIndex++] = verticesPair[0].innerIndex + newPenumbraLength;
ztenghui512e6432014-09-10 13:08:20 -0700959
ztenghuid2dcd6f2014-10-29 16:04:29 -0700960 // Now fill the IB and VB for the umbra area.
961 // First duplicated the index from previous strip and the first one for the
962 // degenerated triangles.
963 indexBuffer[indexBufferIndex] = indexBuffer[indexBufferIndex - 1];
964 indexBufferIndex++;
965 indexBuffer[indexBufferIndex++] = newPenumbraLength + 0;
966 // Save the first VB index for umbra area in order to close the loop.
967 int savedStartIndex = vertexBufferIndex;
968
ztenghui512e6432014-09-10 13:08:20 -0700969 if (hasOccludedUmbraArea) {
ztenghuid2dcd6f2014-10-29 16:04:29 -0700970 // Precompute all the polygon's vector, and the reference cross product,
971 // in order to find the right polygon edge for the ray to intersect.
972 Vector2 polyToCentroid[polyLength];
973 bool isPositiveCross = genPolyToCentroid(poly2d, polyLength, centroid, polyToCentroid);
ztenghui512e6432014-09-10 13:08:20 -0700974
ztenghuid2dcd6f2014-10-29 16:04:29 -0700975 // Because both the umbra and polygon are going in the same direction,
976 // we can save the previous polygon index to make sure we have less polygon
977 // vertex to compute for each ray.
978 int previousPolyIndex = 0;
979 for (int i = 0; i < umbraLength; i++) {
980 // Shoot a ray from centroid to each umbra vertices and pick the one with
981 // shorter distance to the centroid, b/t the umbra vertex or the intersection point.
982 Vector2 closerVertex = getCloserVertex(umbra[i], centroid, poly2d, polyLength,
983 polyToCentroid, isPositiveCross, previousPolyIndex);
984
985 // We already stored the umbra vertices, just need to add the occlued umbra's ones.
986 indexBuffer[indexBufferIndex++] = newPenumbraLength + i;
987 indexBuffer[indexBufferIndex++] = vertexBufferIndex;
988 AlphaVertex::set(&shadowVertices[vertexBufferIndex++],
ztenghuiecf091e2015-02-17 13:26:10 -0800989 closerVertex.x, closerVertex.y, TRANSFORMED_UMBRA_ALPHA);
ztenghui512e6432014-09-10 13:08:20 -0700990 }
ztenghui512e6432014-09-10 13:08:20 -0700991 } else {
ztenghuid2dcd6f2014-10-29 16:04:29 -0700992 // If there is no occluded umbra at all, then draw the triangle fan
993 // starting from the centroid to all umbra vertices.
ztenghui512e6432014-09-10 13:08:20 -0700994 int lastCentroidIndex = vertexBufferIndex;
995 AlphaVertex::set(&shadowVertices[vertexBufferIndex++], centroid.x,
ztenghuiecf091e2015-02-17 13:26:10 -0800996 centroid.y, TRANSFORMED_UMBRA_ALPHA);
ztenghuid2dcd6f2014-10-29 16:04:29 -0700997 for (int i = 0; i < umbraLength; i++) {
998 indexBuffer[indexBufferIndex++] = newPenumbraLength + i;
ztenghui512e6432014-09-10 13:08:20 -0700999 indexBuffer[indexBufferIndex++] = lastCentroidIndex;
1000 }
ztenghui512e6432014-09-10 13:08:20 -07001001 }
ztenghuid2dcd6f2014-10-29 16:04:29 -07001002 // Closing the umbra area triangle's loop here.
1003 indexBuffer[indexBufferIndex++] = newPenumbraLength;
1004 indexBuffer[indexBufferIndex++] = savedStartIndex;
ztenghui512e6432014-09-10 13:08:20 -07001005
1006 // At the end, update the real index and vertex buffer size.
1007 shadowTriangleStrip.updateVertexCount(vertexBufferIndex);
1008 shadowTriangleStrip.updateIndexCount(indexBufferIndex);
1009 ShadowTessellator::checkOverflow(vertexBufferIndex, totalVertexCount, "Spot Vertex Buffer");
1010 ShadowTessellator::checkOverflow(indexBufferIndex, totalIndexCount, "Spot Index Buffer");
1011
Chris Craik117bdbc2015-02-05 10:12:38 -08001012 shadowTriangleStrip.setMeshFeatureFlags(VertexBuffer::kAlpha | VertexBuffer::kIndices);
ztenghui512e6432014-09-10 13:08:20 -07001013 shadowTriangleStrip.computeBounds<AlphaVertex>();
1014}
1015
ztenghuif5ca8b42014-01-27 15:53:28 -08001016#if DEBUG_SHADOW
1017
1018#define TEST_POINT_NUMBER 128
ztenghuif5ca8b42014-01-27 15:53:28 -08001019/**
1020 * Calculate the bounds for generating random test points.
1021 */
1022void SpotShadow::updateBound(const Vector2 inVector, Vector2& lowerBound,
ztenghui512e6432014-09-10 13:08:20 -07001023 Vector2& upperBound) {
ztenghuif5ca8b42014-01-27 15:53:28 -08001024 if (inVector.x < lowerBound.x) {
1025 lowerBound.x = inVector.x;
1026 }
1027
1028 if (inVector.y < lowerBound.y) {
1029 lowerBound.y = inVector.y;
1030 }
1031
1032 if (inVector.x > upperBound.x) {
1033 upperBound.x = inVector.x;
1034 }
1035
1036 if (inVector.y > upperBound.y) {
1037 upperBound.y = inVector.y;
1038 }
1039}
1040
1041/**
1042 * For debug purpose, when things go wrong, dump the whole polygon data.
1043 */
ztenghuic50a03d2014-08-21 13:47:54 -07001044void SpotShadow::dumpPolygon(const Vector2* poly, int polyLength, const char* polyName) {
1045 for (int i = 0; i < polyLength; i++) {
1046 ALOGD("polygon %s i %d x %f y %f", polyName, i, poly[i].x, poly[i].y);
1047 }
1048}
1049
1050/**
1051 * For debug purpose, when things go wrong, dump the whole polygon data.
1052 */
1053void SpotShadow::dumpPolygon(const Vector3* poly, int polyLength, const char* polyName) {
ztenghuif5ca8b42014-01-27 15:53:28 -08001054 for (int i = 0; i < polyLength; i++) {
1055 ALOGD("polygon %s i %d x %f y %f", polyName, i, poly[i].x, poly[i].y);
1056 }
1057}
1058
1059/**
1060 * Test whether the polygon is convex.
1061 */
1062bool SpotShadow::testConvex(const Vector2* polygon, int polygonLength,
1063 const char* name) {
1064 bool isConvex = true;
1065 for (int i = 0; i < polygonLength; i++) {
1066 Vector2 start = polygon[i];
1067 Vector2 middle = polygon[(i + 1) % polygonLength];
1068 Vector2 end = polygon[(i + 2) % polygonLength];
1069
ztenghui9122b1b2014-10-03 11:21:11 -07001070 float delta = (float(middle.x) - start.x) * (float(end.y) - start.y) -
1071 (float(middle.y) - start.y) * (float(end.x) - start.x);
ztenghuif5ca8b42014-01-27 15:53:28 -08001072 bool isCCWOrCoLinear = (delta >= EPSILON);
1073
1074 if (isCCWOrCoLinear) {
ztenghui50ecf842014-03-11 16:52:30 -07001075 ALOGW("(Error Type 2): polygon (%s) is not a convex b/c start (x %f, y %f),"
ztenghuif5ca8b42014-01-27 15:53:28 -08001076 "middle (x %f, y %f) and end (x %f, y %f) , delta is %f !!!",
1077 name, start.x, start.y, middle.x, middle.y, end.x, end.y, delta);
1078 isConvex = false;
1079 break;
1080 }
1081 }
1082 return isConvex;
1083}
1084
1085/**
1086 * Test whether or not the polygon (intersection) is within the 2 input polygons.
1087 * Using Marte Carlo method, we generate a random point, and if it is inside the
1088 * intersection, then it must be inside both source polygons.
1089 */
1090void SpotShadow::testIntersection(const Vector2* poly1, int poly1Length,
1091 const Vector2* poly2, int poly2Length,
1092 const Vector2* intersection, int intersectionLength) {
1093 // Find the min and max of x and y.
ztenghuic50a03d2014-08-21 13:47:54 -07001094 Vector2 lowerBound = {FLT_MAX, FLT_MAX};
1095 Vector2 upperBound = {-FLT_MAX, -FLT_MAX};
ztenghuif5ca8b42014-01-27 15:53:28 -08001096 for (int i = 0; i < poly1Length; i++) {
1097 updateBound(poly1[i], lowerBound, upperBound);
1098 }
1099 for (int i = 0; i < poly2Length; i++) {
1100 updateBound(poly2[i], lowerBound, upperBound);
1101 }
1102
1103 bool dumpPoly = false;
1104 for (int k = 0; k < TEST_POINT_NUMBER; k++) {
1105 // Generate a random point between minX, minY and maxX, maxY.
ztenghui9122b1b2014-10-03 11:21:11 -07001106 float randomX = rand() / float(RAND_MAX);
1107 float randomY = rand() / float(RAND_MAX);
ztenghuif5ca8b42014-01-27 15:53:28 -08001108
1109 Vector2 testPoint;
1110 testPoint.x = lowerBound.x + randomX * (upperBound.x - lowerBound.x);
1111 testPoint.y = lowerBound.y + randomY * (upperBound.y - lowerBound.y);
1112
1113 // If the random point is in both poly 1 and 2, then it must be intersection.
1114 if (testPointInsidePolygon(testPoint, intersection, intersectionLength)) {
1115 if (!testPointInsidePolygon(testPoint, poly1, poly1Length)) {
1116 dumpPoly = true;
ztenghui50ecf842014-03-11 16:52:30 -07001117 ALOGW("(Error Type 1): one point (%f, %f) in the intersection is"
ztenghui512e6432014-09-10 13:08:20 -07001118 " not in the poly1",
ztenghuif5ca8b42014-01-27 15:53:28 -08001119 testPoint.x, testPoint.y);
1120 }
1121
1122 if (!testPointInsidePolygon(testPoint, poly2, poly2Length)) {
1123 dumpPoly = true;
ztenghui50ecf842014-03-11 16:52:30 -07001124 ALOGW("(Error Type 1): one point (%f, %f) in the intersection is"
ztenghui512e6432014-09-10 13:08:20 -07001125 " not in the poly2",
ztenghuif5ca8b42014-01-27 15:53:28 -08001126 testPoint.x, testPoint.y);
1127 }
1128 }
1129 }
1130
1131 if (dumpPoly) {
1132 dumpPolygon(intersection, intersectionLength, "intersection");
1133 for (int i = 1; i < intersectionLength; i++) {
1134 Vector2 delta = intersection[i] - intersection[i - 1];
1135 ALOGD("Intersetion i, %d Vs i-1 is delta %f", i, delta.lengthSquared());
1136 }
1137
1138 dumpPolygon(poly1, poly1Length, "poly 1");
1139 dumpPolygon(poly2, poly2Length, "poly 2");
1140 }
1141}
1142#endif
1143
ztenghui7b4516e2014-01-07 10:42:55 -08001144}; // namespace uirenderer
1145}; // namespace android