ztenghui | 7b4516e | 2014-01-07 10:42:55 -0800 | [diff] [blame] | 1 | /* |
| 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 | |
ztenghui | 512e643 | 2014-09-10 13:08:20 -0700 | [diff] [blame] | 19 | // The highest z value can't be higher than (CASTER_Z_CAP_RATIO * light.z) |
ztenghui | c50a03d | 2014-08-21 13:47:54 -0700 | [diff] [blame] | 20 | #define CASTER_Z_CAP_RATIO 0.95f |
ztenghui | 512e643 | 2014-09-10 13:08:20 -0700 | [diff] [blame] | 21 | |
| 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 | |
ztenghui | 7b4516e | 2014-01-07 10:42:55 -0800 | [diff] [blame] | 47 | |
| 48 | #include <math.h> |
ztenghui | f5ca8b4 | 2014-01-27 15:53:28 -0800 | [diff] [blame] | 49 | #include <stdlib.h> |
ztenghui | 7b4516e | 2014-01-07 10:42:55 -0800 | [diff] [blame] | 50 | #include <utils/Log.h> |
| 51 | |
ztenghui | 63d41ab | 2014-02-14 13:13:41 -0800 | [diff] [blame] | 52 | #include "ShadowTessellator.h" |
ztenghui | 7b4516e | 2014-01-07 10:42:55 -0800 | [diff] [blame] | 53 | #include "SpotShadow.h" |
| 54 | #include "Vertex.h" |
Tom Hudson | 2dc236b | 2014-10-15 15:46:42 -0400 | [diff] [blame^] | 55 | #include "VertexBuffer.h" |
ztenghui | c50a03d | 2014-08-21 13:47:54 -0700 | [diff] [blame] | 56 | #include "utils/MathUtils.h" |
ztenghui | 7b4516e | 2014-01-07 10:42:55 -0800 | [diff] [blame] | 57 | |
ztenghui | c50a03d | 2014-08-21 13:47:54 -0700 | [diff] [blame] | 58 | // TODO: After we settle down the new algorithm, we can remove the old one and |
| 59 | // its utility functions. |
| 60 | // Right now, we still need to keep it for comparison purpose and future expansion. |
ztenghui | 7b4516e | 2014-01-07 10:42:55 -0800 | [diff] [blame] | 61 | namespace android { |
| 62 | namespace uirenderer { |
| 63 | |
ztenghui | 9122b1b | 2014-10-03 11:21:11 -0700 | [diff] [blame] | 64 | static const float EPSILON = 1e-7; |
Chris Craik | 726118b | 2014-03-07 18:27:49 -0800 | [diff] [blame] | 65 | |
ztenghui | 7b4516e | 2014-01-07 10:42:55 -0800 | [diff] [blame] | 66 | /** |
ztenghui | c50a03d | 2014-08-21 13:47:54 -0700 | [diff] [blame] | 67 | * For each polygon's vertex, the light center will project it to the receiver |
| 68 | * as one of the outline vertex. |
| 69 | * For each outline vertex, we need to store the position and normal. |
| 70 | * Normal here is defined against the edge by the current vertex and the next vertex. |
| 71 | */ |
| 72 | struct OutlineData { |
| 73 | Vector2 position; |
| 74 | Vector2 normal; |
| 75 | float radius; |
| 76 | }; |
| 77 | |
| 78 | /** |
ztenghui | 512e643 | 2014-09-10 13:08:20 -0700 | [diff] [blame] | 79 | * For each vertex, we need to keep track of its angle, whether it is penumbra or |
| 80 | * umbra, and its corresponding vertex index. |
| 81 | */ |
| 82 | struct SpotShadow::VertexAngleData { |
| 83 | // The angle to the vertex from the centroid. |
| 84 | float mAngle; |
| 85 | // True is the vertex comes from penumbra, otherwise it comes from umbra. |
| 86 | bool mIsPenumbra; |
| 87 | // The index of the vertex described by this data. |
| 88 | int mVertexIndex; |
| 89 | void set(float angle, bool isPenumbra, int index) { |
| 90 | mAngle = angle; |
| 91 | mIsPenumbra = isPenumbra; |
| 92 | mVertexIndex = index; |
| 93 | } |
| 94 | }; |
| 95 | |
| 96 | /** |
Chris Craik | 726118b | 2014-03-07 18:27:49 -0800 | [diff] [blame] | 97 | * Calculate the angle between and x and a y coordinate. |
| 98 | * The atan2 range from -PI to PI. |
ztenghui | 7b4516e | 2014-01-07 10:42:55 -0800 | [diff] [blame] | 99 | */ |
Chris Craik | b79a3e3 | 2014-03-11 12:20:17 -0700 | [diff] [blame] | 100 | static float angle(const Vector2& point, const Vector2& center) { |
Chris Craik | 726118b | 2014-03-07 18:27:49 -0800 | [diff] [blame] | 101 | return atan2(point.y - center.y, point.x - center.x); |
| 102 | } |
| 103 | |
| 104 | /** |
| 105 | * Calculate the intersection of a ray with the line segment defined by two points. |
| 106 | * |
| 107 | * Returns a negative value in error conditions. |
| 108 | |
| 109 | * @param rayOrigin The start of the ray |
| 110 | * @param dx The x vector of the ray |
| 111 | * @param dy The y vector of the ray |
| 112 | * @param p1 The first point defining the line segment |
| 113 | * @param p2 The second point defining the line segment |
| 114 | * @return The distance along the ray if it intersects with the line segment, negative if otherwise |
| 115 | */ |
Chris Craik | b79a3e3 | 2014-03-11 12:20:17 -0700 | [diff] [blame] | 116 | static float rayIntersectPoints(const Vector2& rayOrigin, float dx, float dy, |
Chris Craik | 726118b | 2014-03-07 18:27:49 -0800 | [diff] [blame] | 117 | const Vector2& p1, const Vector2& p2) { |
| 118 | // The math below is derived from solving this formula, basically the |
| 119 | // intersection point should stay on both the ray and the edge of (p1, p2). |
| 120 | // solve([p1x+t*(p2x-p1x)=dx*t2+px,p1y+t*(p2y-p1y)=dy*t2+py],[t,t2]); |
| 121 | |
ztenghui | 9122b1b | 2014-10-03 11:21:11 -0700 | [diff] [blame] | 122 | float divisor = (dx * (p1.y - p2.y) + dy * p2.x - dy * p1.x); |
Chris Craik | 726118b | 2014-03-07 18:27:49 -0800 | [diff] [blame] | 123 | if (divisor == 0) return -1.0f; // error, invalid divisor |
| 124 | |
| 125 | #if DEBUG_SHADOW |
ztenghui | 9122b1b | 2014-10-03 11:21:11 -0700 | [diff] [blame] | 126 | float interpVal = (dx * (p1.y - rayOrigin.y) + dy * rayOrigin.x - dy * p1.x) / divisor; |
ztenghui | 99af942 | 2014-03-14 14:35:54 -0700 | [diff] [blame] | 127 | if (interpVal < 0 || interpVal > 1) { |
| 128 | ALOGW("rayIntersectPoints is hitting outside the segment %f", interpVal); |
| 129 | } |
Chris Craik | 726118b | 2014-03-07 18:27:49 -0800 | [diff] [blame] | 130 | #endif |
| 131 | |
ztenghui | 9122b1b | 2014-10-03 11:21:11 -0700 | [diff] [blame] | 132 | float distance = (p1.x * (rayOrigin.y - p2.y) + p2.x * (p1.y - rayOrigin.y) + |
Chris Craik | 726118b | 2014-03-07 18:27:49 -0800 | [diff] [blame] | 133 | rayOrigin.x * (p2.y - p1.y)) / divisor; |
| 134 | |
| 135 | return distance; // may be negative in error cases |
ztenghui | 7b4516e | 2014-01-07 10:42:55 -0800 | [diff] [blame] | 136 | } |
| 137 | |
| 138 | /** |
ztenghui | 7b4516e | 2014-01-07 10:42:55 -0800 | [diff] [blame] | 139 | * Sort points by their X coordinates |
| 140 | * |
| 141 | * @param points the points as a Vector2 array. |
| 142 | * @param pointsLength the number of vertices of the polygon. |
| 143 | */ |
| 144 | void SpotShadow::xsort(Vector2* points, int pointsLength) { |
| 145 | quicksortX(points, 0, pointsLength - 1); |
| 146 | } |
| 147 | |
| 148 | /** |
| 149 | * compute the convex hull of a collection of Points |
| 150 | * |
| 151 | * @param points the points as a Vector2 array. |
| 152 | * @param pointsLength the number of vertices of the polygon. |
| 153 | * @param retPoly pre allocated array of floats to put the vertices |
| 154 | * @return the number of points in the polygon 0 if no intersection |
| 155 | */ |
| 156 | int SpotShadow::hull(Vector2* points, int pointsLength, Vector2* retPoly) { |
| 157 | xsort(points, pointsLength); |
| 158 | int n = pointsLength; |
| 159 | Vector2 lUpper[n]; |
| 160 | lUpper[0] = points[0]; |
| 161 | lUpper[1] = points[1]; |
| 162 | |
| 163 | int lUpperSize = 2; |
| 164 | |
| 165 | for (int i = 2; i < n; i++) { |
| 166 | lUpper[lUpperSize] = points[i]; |
| 167 | lUpperSize++; |
| 168 | |
ztenghui | f5ca8b4 | 2014-01-27 15:53:28 -0800 | [diff] [blame] | 169 | while (lUpperSize > 2 && !ccw( |
| 170 | lUpper[lUpperSize - 3].x, lUpper[lUpperSize - 3].y, |
| 171 | lUpper[lUpperSize - 2].x, lUpper[lUpperSize - 2].y, |
| 172 | lUpper[lUpperSize - 1].x, lUpper[lUpperSize - 1].y)) { |
ztenghui | 7b4516e | 2014-01-07 10:42:55 -0800 | [diff] [blame] | 173 | // Remove the middle point of the three last |
| 174 | lUpper[lUpperSize - 2].x = lUpper[lUpperSize - 1].x; |
| 175 | lUpper[lUpperSize - 2].y = lUpper[lUpperSize - 1].y; |
| 176 | lUpperSize--; |
| 177 | } |
| 178 | } |
| 179 | |
| 180 | Vector2 lLower[n]; |
| 181 | lLower[0] = points[n - 1]; |
| 182 | lLower[1] = points[n - 2]; |
| 183 | |
| 184 | int lLowerSize = 2; |
| 185 | |
| 186 | for (int i = n - 3; i >= 0; i--) { |
| 187 | lLower[lLowerSize] = points[i]; |
| 188 | lLowerSize++; |
| 189 | |
ztenghui | f5ca8b4 | 2014-01-27 15:53:28 -0800 | [diff] [blame] | 190 | while (lLowerSize > 2 && !ccw( |
| 191 | lLower[lLowerSize - 3].x, lLower[lLowerSize - 3].y, |
| 192 | lLower[lLowerSize - 2].x, lLower[lLowerSize - 2].y, |
| 193 | lLower[lLowerSize - 1].x, lLower[lLowerSize - 1].y)) { |
ztenghui | 7b4516e | 2014-01-07 10:42:55 -0800 | [diff] [blame] | 194 | // Remove the middle point of the three last |
| 195 | lLower[lLowerSize - 2] = lLower[lLowerSize - 1]; |
| 196 | lLowerSize--; |
| 197 | } |
| 198 | } |
ztenghui | 7b4516e | 2014-01-07 10:42:55 -0800 | [diff] [blame] | 199 | |
Chris Craik | 726118b | 2014-03-07 18:27:49 -0800 | [diff] [blame] | 200 | // output points in CW ordering |
| 201 | const int total = lUpperSize + lLowerSize - 2; |
| 202 | int outIndex = total - 1; |
ztenghui | 7b4516e | 2014-01-07 10:42:55 -0800 | [diff] [blame] | 203 | for (int i = 0; i < lUpperSize; i++) { |
Chris Craik | 726118b | 2014-03-07 18:27:49 -0800 | [diff] [blame] | 204 | retPoly[outIndex] = lUpper[i]; |
| 205 | outIndex--; |
ztenghui | 7b4516e | 2014-01-07 10:42:55 -0800 | [diff] [blame] | 206 | } |
| 207 | |
| 208 | for (int i = 1; i < lLowerSize - 1; i++) { |
Chris Craik | 726118b | 2014-03-07 18:27:49 -0800 | [diff] [blame] | 209 | retPoly[outIndex] = lLower[i]; |
| 210 | outIndex--; |
ztenghui | 7b4516e | 2014-01-07 10:42:55 -0800 | [diff] [blame] | 211 | } |
| 212 | // TODO: Add test harness which verify that all the points are inside the hull. |
Chris Craik | 726118b | 2014-03-07 18:27:49 -0800 | [diff] [blame] | 213 | return total; |
ztenghui | 7b4516e | 2014-01-07 10:42:55 -0800 | [diff] [blame] | 214 | } |
| 215 | |
| 216 | /** |
ztenghui | f5ca8b4 | 2014-01-27 15:53:28 -0800 | [diff] [blame] | 217 | * Test whether the 3 points form a counter clockwise turn. |
ztenghui | 7b4516e | 2014-01-07 10:42:55 -0800 | [diff] [blame] | 218 | * |
ztenghui | 7b4516e | 2014-01-07 10:42:55 -0800 | [diff] [blame] | 219 | * @return true if a right hand turn |
| 220 | */ |
ztenghui | 9122b1b | 2014-10-03 11:21:11 -0700 | [diff] [blame] | 221 | bool SpotShadow::ccw(float ax, float ay, float bx, float by, |
| 222 | float cx, float cy) { |
ztenghui | 7b4516e | 2014-01-07 10:42:55 -0800 | [diff] [blame] | 223 | return (bx - ax) * (cy - ay) - (by - ay) * (cx - ax) > EPSILON; |
| 224 | } |
| 225 | |
| 226 | /** |
ztenghui | 7b4516e | 2014-01-07 10:42:55 -0800 | [diff] [blame] | 227 | * Sort points about a center point |
| 228 | * |
| 229 | * @param poly The in and out polyogon as a Vector2 array. |
| 230 | * @param polyLength The number of vertices of the polygon. |
| 231 | * @param center the center ctr[0] = x , ctr[1] = y to sort around. |
| 232 | */ |
| 233 | void SpotShadow::sort(Vector2* poly, int polyLength, const Vector2& center) { |
| 234 | quicksortCirc(poly, 0, polyLength - 1, center); |
| 235 | } |
| 236 | |
| 237 | /** |
ztenghui | 7b4516e | 2014-01-07 10:42:55 -0800 | [diff] [blame] | 238 | * Swap points pointed to by i and j |
| 239 | */ |
| 240 | void SpotShadow::swap(Vector2* points, int i, int j) { |
| 241 | Vector2 temp = points[i]; |
| 242 | points[i] = points[j]; |
| 243 | points[j] = temp; |
| 244 | } |
| 245 | |
| 246 | /** |
| 247 | * quick sort implementation about the center. |
| 248 | */ |
| 249 | void SpotShadow::quicksortCirc(Vector2* points, int low, int high, |
| 250 | const Vector2& center) { |
| 251 | int i = low, j = high; |
| 252 | int p = low + (high - low) / 2; |
| 253 | float pivot = angle(points[p], center); |
| 254 | while (i <= j) { |
Chris Craik | 726118b | 2014-03-07 18:27:49 -0800 | [diff] [blame] | 255 | while (angle(points[i], center) > pivot) { |
ztenghui | 7b4516e | 2014-01-07 10:42:55 -0800 | [diff] [blame] | 256 | i++; |
| 257 | } |
Chris Craik | 726118b | 2014-03-07 18:27:49 -0800 | [diff] [blame] | 258 | while (angle(points[j], center) < pivot) { |
ztenghui | 7b4516e | 2014-01-07 10:42:55 -0800 | [diff] [blame] | 259 | j--; |
| 260 | } |
| 261 | |
| 262 | if (i <= j) { |
| 263 | swap(points, i, j); |
| 264 | i++; |
| 265 | j--; |
| 266 | } |
| 267 | } |
| 268 | if (low < j) quicksortCirc(points, low, j, center); |
| 269 | if (i < high) quicksortCirc(points, i, high, center); |
| 270 | } |
| 271 | |
| 272 | /** |
| 273 | * Sort points by x axis |
| 274 | * |
| 275 | * @param points points to sort |
| 276 | * @param low start index |
| 277 | * @param high end index |
| 278 | */ |
| 279 | void SpotShadow::quicksortX(Vector2* points, int low, int high) { |
| 280 | int i = low, j = high; |
| 281 | int p = low + (high - low) / 2; |
| 282 | float pivot = points[p].x; |
| 283 | while (i <= j) { |
| 284 | while (points[i].x < pivot) { |
| 285 | i++; |
| 286 | } |
| 287 | while (points[j].x > pivot) { |
| 288 | j--; |
| 289 | } |
| 290 | |
| 291 | if (i <= j) { |
| 292 | swap(points, i, j); |
| 293 | i++; |
| 294 | j--; |
| 295 | } |
| 296 | } |
| 297 | if (low < j) quicksortX(points, low, j); |
| 298 | if (i < high) quicksortX(points, i, high); |
| 299 | } |
| 300 | |
| 301 | /** |
| 302 | * Test whether a point is inside the polygon. |
| 303 | * |
| 304 | * @param testPoint the point to test |
| 305 | * @param poly the polygon |
| 306 | * @return true if the testPoint is inside the poly. |
| 307 | */ |
| 308 | bool SpotShadow::testPointInsidePolygon(const Vector2 testPoint, |
| 309 | const Vector2* poly, int len) { |
| 310 | bool c = false; |
ztenghui | 9122b1b | 2014-10-03 11:21:11 -0700 | [diff] [blame] | 311 | float testx = testPoint.x; |
| 312 | float testy = testPoint.y; |
ztenghui | 7b4516e | 2014-01-07 10:42:55 -0800 | [diff] [blame] | 313 | for (int i = 0, j = len - 1; i < len; j = i++) { |
ztenghui | 9122b1b | 2014-10-03 11:21:11 -0700 | [diff] [blame] | 314 | float startX = poly[j].x; |
| 315 | float startY = poly[j].y; |
| 316 | float endX = poly[i].x; |
| 317 | float endY = poly[i].y; |
ztenghui | 7b4516e | 2014-01-07 10:42:55 -0800 | [diff] [blame] | 318 | |
ztenghui | 512e643 | 2014-09-10 13:08:20 -0700 | [diff] [blame] | 319 | if (((endY > testy) != (startY > testy)) |
| 320 | && (testx < (startX - endX) * (testy - endY) |
ztenghui | 7b4516e | 2014-01-07 10:42:55 -0800 | [diff] [blame] | 321 | / (startY - endY) + endX)) { |
| 322 | c = !c; |
| 323 | } |
| 324 | } |
| 325 | return c; |
| 326 | } |
| 327 | |
| 328 | /** |
| 329 | * Make the polygon turn clockwise. |
| 330 | * |
| 331 | * @param polygon the polygon as a Vector2 array. |
| 332 | * @param len the number of points of the polygon |
| 333 | */ |
| 334 | void SpotShadow::makeClockwise(Vector2* polygon, int len) { |
| 335 | if (polygon == 0 || len == 0) { |
| 336 | return; |
| 337 | } |
ztenghui | 2e023f3 | 2014-04-28 16:43:13 -0700 | [diff] [blame] | 338 | if (!ShadowTessellator::isClockwise(polygon, len)) { |
ztenghui | 7b4516e | 2014-01-07 10:42:55 -0800 | [diff] [blame] | 339 | reverse(polygon, len); |
| 340 | } |
| 341 | } |
| 342 | |
| 343 | /** |
ztenghui | 7b4516e | 2014-01-07 10:42:55 -0800 | [diff] [blame] | 344 | * Reverse the polygon |
| 345 | * |
| 346 | * @param polygon the polygon as a Vector2 array |
| 347 | * @param len the number of points of the polygon |
| 348 | */ |
| 349 | void SpotShadow::reverse(Vector2* polygon, int len) { |
| 350 | int n = len / 2; |
| 351 | for (int i = 0; i < n; i++) { |
| 352 | Vector2 tmp = polygon[i]; |
| 353 | int k = len - 1 - i; |
| 354 | polygon[i] = polygon[k]; |
| 355 | polygon[k] = tmp; |
| 356 | } |
| 357 | } |
| 358 | |
| 359 | /** |
ztenghui | 7b4516e | 2014-01-07 10:42:55 -0800 | [diff] [blame] | 360 | * Compute a horizontal circular polygon about point (x , y , height) of radius |
| 361 | * (size) |
| 362 | * |
| 363 | * @param points number of the points of the output polygon. |
| 364 | * @param lightCenter the center of the light. |
| 365 | * @param size the light size. |
| 366 | * @param ret result polygon. |
| 367 | */ |
| 368 | void SpotShadow::computeLightPolygon(int points, const Vector3& lightCenter, |
| 369 | float size, Vector3* ret) { |
| 370 | // TODO: Caching all the sin / cos values and store them in a look up table. |
| 371 | for (int i = 0; i < points; i++) { |
ztenghui | 9122b1b | 2014-10-03 11:21:11 -0700 | [diff] [blame] | 372 | float angle = 2 * i * M_PI / points; |
Chris Craik | 726118b | 2014-03-07 18:27:49 -0800 | [diff] [blame] | 373 | ret[i].x = cosf(angle) * size + lightCenter.x; |
| 374 | ret[i].y = sinf(angle) * size + lightCenter.y; |
ztenghui | 7b4516e | 2014-01-07 10:42:55 -0800 | [diff] [blame] | 375 | ret[i].z = lightCenter.z; |
| 376 | } |
| 377 | } |
| 378 | |
| 379 | /** |
ztenghui | 512e643 | 2014-09-10 13:08:20 -0700 | [diff] [blame] | 380 | * From light center, project one vertex to the z=0 surface and get the outline. |
ztenghui | 7b4516e | 2014-01-07 10:42:55 -0800 | [diff] [blame] | 381 | * |
ztenghui | 512e643 | 2014-09-10 13:08:20 -0700 | [diff] [blame] | 382 | * @param outline The result which is the outline position. |
| 383 | * @param lightCenter The center of light. |
| 384 | * @param polyVertex The input polygon's vertex. |
| 385 | * |
| 386 | * @return float The ratio of (polygon.z / light.z - polygon.z) |
ztenghui | 7b4516e | 2014-01-07 10:42:55 -0800 | [diff] [blame] | 387 | */ |
ztenghui | c50a03d | 2014-08-21 13:47:54 -0700 | [diff] [blame] | 388 | float SpotShadow::projectCasterToOutline(Vector2& outline, |
| 389 | const Vector3& lightCenter, const Vector3& polyVertex) { |
| 390 | float lightToPolyZ = lightCenter.z - polyVertex.z; |
| 391 | float ratioZ = CASTER_Z_CAP_RATIO; |
| 392 | if (lightToPolyZ != 0) { |
| 393 | // If any caster's vertex is almost above the light, we just keep it as 95% |
| 394 | // of the height of the light. |
ztenghui | 3bd3fa1 | 2014-08-25 14:42:27 -0700 | [diff] [blame] | 395 | ratioZ = MathUtils::clamp(polyVertex.z / lightToPolyZ, 0.0f, CASTER_Z_CAP_RATIO); |
ztenghui | c50a03d | 2014-08-21 13:47:54 -0700 | [diff] [blame] | 396 | } |
| 397 | |
| 398 | outline.x = polyVertex.x - ratioZ * (lightCenter.x - polyVertex.x); |
| 399 | outline.y = polyVertex.y - ratioZ * (lightCenter.y - polyVertex.y); |
| 400 | return ratioZ; |
| 401 | } |
| 402 | |
| 403 | /** |
| 404 | * Generate the shadow spot light of shape lightPoly and a object poly |
| 405 | * |
| 406 | * @param isCasterOpaque whether the caster is opaque |
| 407 | * @param lightCenter the center of the light |
| 408 | * @param lightSize the radius of the light |
| 409 | * @param poly x,y,z vertexes of a convex polygon that occludes the light source |
| 410 | * @param polyLength number of vertexes of the occluding polygon |
| 411 | * @param shadowTriangleStrip return an (x,y,alpha) triangle strip representing the shadow. Return |
| 412 | * empty strip if error. |
| 413 | */ |
| 414 | void SpotShadow::createSpotShadow(bool isCasterOpaque, const Vector3& lightCenter, |
| 415 | float lightSize, const Vector3* poly, int polyLength, const Vector3& polyCentroid, |
| 416 | VertexBuffer& shadowTriangleStrip) { |
ztenghui | 3bd3fa1 | 2014-08-25 14:42:27 -0700 | [diff] [blame] | 417 | if (CC_UNLIKELY(lightCenter.z <= 0)) { |
| 418 | ALOGW("Relative Light Z is not positive. No spot shadow!"); |
| 419 | return; |
| 420 | } |
ztenghui | 512e643 | 2014-09-10 13:08:20 -0700 | [diff] [blame] | 421 | if (CC_UNLIKELY(polyLength < 3)) { |
| 422 | #if DEBUG_SHADOW |
| 423 | ALOGW("Invalid polygon length. No spot shadow!"); |
| 424 | #endif |
| 425 | return; |
| 426 | } |
ztenghui | c50a03d | 2014-08-21 13:47:54 -0700 | [diff] [blame] | 427 | OutlineData outlineData[polyLength]; |
| 428 | Vector2 outlineCentroid; |
| 429 | // Calculate the projected outline for each polygon's vertices from the light center. |
| 430 | // |
| 431 | // O Light |
| 432 | // / |
| 433 | // / |
| 434 | // . Polygon vertex |
| 435 | // / |
| 436 | // / |
| 437 | // O Outline vertices |
| 438 | // |
| 439 | // Ratio = (Poly - Outline) / (Light - Poly) |
| 440 | // Outline.x = Poly.x - Ratio * (Light.x - Poly.x) |
| 441 | // Outline's radius / Light's radius = Ratio |
| 442 | |
| 443 | // Compute the last outline vertex to make sure we can get the normal and outline |
| 444 | // in one single loop. |
| 445 | projectCasterToOutline(outlineData[polyLength - 1].position, lightCenter, |
| 446 | poly[polyLength - 1]); |
| 447 | |
| 448 | // Take the outline's polygon, calculate the normal for each outline edge. |
| 449 | int currentNormalIndex = polyLength - 1; |
| 450 | int nextNormalIndex = 0; |
| 451 | |
| 452 | for (int i = 0; i < polyLength; i++) { |
| 453 | float ratioZ = projectCasterToOutline(outlineData[i].position, |
| 454 | lightCenter, poly[i]); |
| 455 | outlineData[i].radius = ratioZ * lightSize; |
| 456 | |
| 457 | outlineData[currentNormalIndex].normal = ShadowTessellator::calculateNormal( |
| 458 | outlineData[currentNormalIndex].position, |
| 459 | outlineData[nextNormalIndex].position); |
| 460 | currentNormalIndex = (currentNormalIndex + 1) % polyLength; |
| 461 | nextNormalIndex++; |
| 462 | } |
| 463 | |
| 464 | projectCasterToOutline(outlineCentroid, lightCenter, polyCentroid); |
| 465 | |
| 466 | int penumbraIndex = 0; |
ztenghui | 512e643 | 2014-09-10 13:08:20 -0700 | [diff] [blame] | 467 | // Then each polygon's vertex produce at minmal 2 penumbra vertices. |
| 468 | // Since the size can be dynamic here, we keep track of the size and update |
| 469 | // the real size at the end. |
| 470 | int allocatedPenumbraLength = 2 * polyLength + SPOT_MAX_EXTRA_CORNER_VERTEX_NUMBER; |
| 471 | Vector2 penumbra[allocatedPenumbraLength]; |
| 472 | int totalExtraCornerSliceNumber = 0; |
ztenghui | c50a03d | 2014-08-21 13:47:54 -0700 | [diff] [blame] | 473 | |
| 474 | Vector2 umbra[polyLength]; |
ztenghui | c50a03d | 2014-08-21 13:47:54 -0700 | [diff] [blame] | 475 | |
ztenghui | 512e643 | 2014-09-10 13:08:20 -0700 | [diff] [blame] | 476 | // When centroid is covered by all circles from outline, then we consider |
| 477 | // the umbra is invalid, and we will tune down the shadow strength. |
ztenghui | c50a03d | 2014-08-21 13:47:54 -0700 | [diff] [blame] | 478 | bool hasValidUmbra = true; |
ztenghui | 512e643 | 2014-09-10 13:08:20 -0700 | [diff] [blame] | 479 | // We need the minimal of RaitoVI to decrease the spot shadow strength accordingly. |
| 480 | float minRaitoVI = FLT_MAX; |
ztenghui | c50a03d | 2014-08-21 13:47:54 -0700 | [diff] [blame] | 481 | |
| 482 | for (int i = 0; i < polyLength; i++) { |
| 483 | // Generate all the penumbra's vertices only using the (outline vertex + normal * radius) |
| 484 | // There is no guarantee that the penumbra is still convex, but for |
| 485 | // each outline vertex, it will connect to all its corresponding penumbra vertices as |
| 486 | // triangle fans. And for neighber penumbra vertex, it will be a trapezoid. |
| 487 | // |
| 488 | // Penumbra Vertices marked as Pi |
| 489 | // Outline Vertices marked as Vi |
| 490 | // (P3) |
| 491 | // (P2) | ' (P4) |
| 492 | // (P1)' | | ' |
| 493 | // ' | | ' |
| 494 | // (P0) ------------------------------------------------(P5) |
| 495 | // | (V0) |(V1) |
| 496 | // | | |
| 497 | // | | |
| 498 | // | | |
| 499 | // | | |
| 500 | // | | |
| 501 | // | | |
| 502 | // | | |
| 503 | // | | |
| 504 | // (V3)-----------------------------------(V2) |
| 505 | int preNormalIndex = (i + polyLength - 1) % polyLength; |
ztenghui | c50a03d | 2014-08-21 13:47:54 -0700 | [diff] [blame] | 506 | |
ztenghui | 512e643 | 2014-09-10 13:08:20 -0700 | [diff] [blame] | 507 | const Vector2& previousNormal = outlineData[preNormalIndex].normal; |
| 508 | const Vector2& currentNormal = outlineData[i].normal; |
| 509 | |
| 510 | // Depending on how roundness we want for each corner, we can subdivide |
ztenghui | c50a03d | 2014-08-21 13:47:54 -0700 | [diff] [blame] | 511 | // further here and/or introduce some heuristic to decide how much the |
| 512 | // subdivision should be. |
ztenghui | 512e643 | 2014-09-10 13:08:20 -0700 | [diff] [blame] | 513 | int currentExtraSliceNumber = ShadowTessellator::getExtraVertexNumber( |
| 514 | previousNormal, currentNormal, SPOT_CORNER_RADIANS_DIVISOR); |
ztenghui | c50a03d | 2014-08-21 13:47:54 -0700 | [diff] [blame] | 515 | |
ztenghui | 512e643 | 2014-09-10 13:08:20 -0700 | [diff] [blame] | 516 | int currentCornerSliceNumber = 1 + currentExtraSliceNumber; |
| 517 | totalExtraCornerSliceNumber += currentExtraSliceNumber; |
| 518 | #if DEBUG_SHADOW |
| 519 | ALOGD("currentExtraSliceNumber should be %d", currentExtraSliceNumber); |
| 520 | ALOGD("currentCornerSliceNumber should be %d", currentCornerSliceNumber); |
| 521 | ALOGD("totalCornerSliceNumber is %d", totalExtraCornerSliceNumber); |
| 522 | #endif |
| 523 | if (CC_UNLIKELY(totalExtraCornerSliceNumber > SPOT_MAX_EXTRA_CORNER_VERTEX_NUMBER)) { |
| 524 | currentCornerSliceNumber = 1; |
| 525 | } |
| 526 | for (int k = 0; k <= currentCornerSliceNumber; k++) { |
| 527 | Vector2 avgNormal = |
| 528 | (previousNormal * (currentCornerSliceNumber - k) + currentNormal * k) / |
| 529 | currentCornerSliceNumber; |
| 530 | avgNormal.normalize(); |
| 531 | penumbra[penumbraIndex++] = outlineData[i].position + |
| 532 | avgNormal * outlineData[i].radius; |
| 533 | } |
ztenghui | c50a03d | 2014-08-21 13:47:54 -0700 | [diff] [blame] | 534 | |
ztenghui | c50a03d | 2014-08-21 13:47:54 -0700 | [diff] [blame] | 535 | |
| 536 | // Compute the umbra by the intersection from the outline's centroid! |
| 537 | // |
| 538 | // (V) ------------------------------------ |
| 539 | // | ' | |
| 540 | // | ' | |
| 541 | // | ' (I) | |
| 542 | // | ' | |
| 543 | // | ' (C) | |
| 544 | // | | |
| 545 | // | | |
| 546 | // | | |
| 547 | // | | |
| 548 | // ------------------------------------ |
| 549 | // |
| 550 | // Connect a line b/t the outline vertex (V) and the centroid (C), it will |
| 551 | // intersect with the outline vertex's circle at point (I). |
| 552 | // Now, ratioVI = VI / VC, ratioIC = IC / VC |
| 553 | // Then the intersetion point can be computed as Ixy = Vxy * ratioIC + Cxy * ratioVI; |
| 554 | // |
ztenghui | 512e643 | 2014-09-10 13:08:20 -0700 | [diff] [blame] | 555 | // When all of the outline circles cover the the outline centroid, (like I is |
ztenghui | c50a03d | 2014-08-21 13:47:54 -0700 | [diff] [blame] | 556 | // on the other side of C), there is no real umbra any more, so we just fake |
| 557 | // a small area around the centroid as the umbra, and tune down the spot |
| 558 | // shadow's umbra strength to simulate the effect the whole shadow will |
| 559 | // become lighter in this case. |
| 560 | // The ratio can be simulated by using the inverse of maximum of ratioVI for |
| 561 | // all (V). |
ztenghui | 512e643 | 2014-09-10 13:08:20 -0700 | [diff] [blame] | 562 | float distOutline = (outlineData[i].position - outlineCentroid).length(); |
ztenghui | 3bd3fa1 | 2014-08-25 14:42:27 -0700 | [diff] [blame] | 563 | if (CC_UNLIKELY(distOutline == 0)) { |
ztenghui | c50a03d | 2014-08-21 13:47:54 -0700 | [diff] [blame] | 564 | // If the outline has 0 area, then there is no spot shadow anyway. |
| 565 | ALOGW("Outline has 0 area, no spot shadow!"); |
| 566 | return; |
| 567 | } |
ztenghui | 512e643 | 2014-09-10 13:08:20 -0700 | [diff] [blame] | 568 | |
| 569 | float ratioVI = outlineData[i].radius / distOutline; |
| 570 | minRaitoVI = MathUtils::min(minRaitoVI, ratioVI); |
| 571 | if (ratioVI >= (1 - FAKE_UMBRA_SIZE_RATIO)) { |
| 572 | ratioVI = (1 - FAKE_UMBRA_SIZE_RATIO); |
ztenghui | c50a03d | 2014-08-21 13:47:54 -0700 | [diff] [blame] | 573 | } |
| 574 | // When we know we don't have valid umbra, don't bother to compute the |
| 575 | // values below. But we can't skip the loop yet since we want to know the |
| 576 | // maximum ratio. |
ztenghui | 512e643 | 2014-09-10 13:08:20 -0700 | [diff] [blame] | 577 | float ratioIC = 1 - ratioVI; |
| 578 | umbra[i] = outlineData[i].position * ratioIC + outlineCentroid * ratioVI; |
ztenghui | c50a03d | 2014-08-21 13:47:54 -0700 | [diff] [blame] | 579 | } |
| 580 | |
ztenghui | 512e643 | 2014-09-10 13:08:20 -0700 | [diff] [blame] | 581 | hasValidUmbra = (minRaitoVI <= 1.0); |
ztenghui | c50a03d | 2014-08-21 13:47:54 -0700 | [diff] [blame] | 582 | float shadowStrengthScale = 1.0; |
| 583 | if (!hasValidUmbra) { |
ztenghui | 512e643 | 2014-09-10 13:08:20 -0700 | [diff] [blame] | 584 | #if DEBUG_SHADOW |
ztenghui | c50a03d | 2014-08-21 13:47:54 -0700 | [diff] [blame] | 585 | ALOGW("The object is too close to the light or too small, no real umbra!"); |
ztenghui | 512e643 | 2014-09-10 13:08:20 -0700 | [diff] [blame] | 586 | #endif |
ztenghui | c50a03d | 2014-08-21 13:47:54 -0700 | [diff] [blame] | 587 | for (int i = 0; i < polyLength; i++) { |
| 588 | umbra[i] = outlineData[i].position * FAKE_UMBRA_SIZE_RATIO + |
ztenghui | 512e643 | 2014-09-10 13:08:20 -0700 | [diff] [blame] | 589 | outlineCentroid * (1 - FAKE_UMBRA_SIZE_RATIO); |
ztenghui | c50a03d | 2014-08-21 13:47:54 -0700 | [diff] [blame] | 590 | } |
ztenghui | 512e643 | 2014-09-10 13:08:20 -0700 | [diff] [blame] | 591 | shadowStrengthScale = 1.0 / minRaitoVI; |
ztenghui | c50a03d | 2014-08-21 13:47:54 -0700 | [diff] [blame] | 592 | } |
| 593 | |
ztenghui | 512e643 | 2014-09-10 13:08:20 -0700 | [diff] [blame] | 594 | int penumbraLength = penumbraIndex; |
| 595 | int umbraLength = polyLength; |
| 596 | |
ztenghui | c50a03d | 2014-08-21 13:47:54 -0700 | [diff] [blame] | 597 | #if DEBUG_SHADOW |
ztenghui | 512e643 | 2014-09-10 13:08:20 -0700 | [diff] [blame] | 598 | ALOGD("penumbraLength is %d , allocatedPenumbraLength %d", penumbraLength, allocatedPenumbraLength); |
ztenghui | c50a03d | 2014-08-21 13:47:54 -0700 | [diff] [blame] | 599 | dumpPolygon(poly, polyLength, "input poly"); |
ztenghui | c50a03d | 2014-08-21 13:47:54 -0700 | [diff] [blame] | 600 | dumpPolygon(penumbra, penumbraLength, "penumbra"); |
ztenghui | 512e643 | 2014-09-10 13:08:20 -0700 | [diff] [blame] | 601 | dumpPolygon(umbra, umbraLength, "umbra"); |
ztenghui | c50a03d | 2014-08-21 13:47:54 -0700 | [diff] [blame] | 602 | ALOGD("hasValidUmbra is %d and shadowStrengthScale is %f", hasValidUmbra, shadowStrengthScale); |
| 603 | #endif |
| 604 | |
ztenghui | 512e643 | 2014-09-10 13:08:20 -0700 | [diff] [blame] | 605 | // The penumbra and umbra needs to be in convex shape to keep consistency |
| 606 | // and quality. |
| 607 | // Since we are still shooting rays to penumbra, it needs to be convex. |
| 608 | // Umbra can be represented as a fan from the centroid, but visually umbra |
| 609 | // looks nicer when it is convex. |
| 610 | Vector2 finalUmbra[umbraLength]; |
| 611 | Vector2 finalPenumbra[penumbraLength]; |
| 612 | int finalUmbraLength = hull(umbra, umbraLength, finalUmbra); |
| 613 | int finalPenumbraLength = hull(penumbra, penumbraLength, finalPenumbra); |
| 614 | |
| 615 | generateTriangleStrip(isCasterOpaque, shadowStrengthScale, finalPenumbra, |
| 616 | finalPenumbraLength, finalUmbra, finalUmbraLength, poly, polyLength, |
| 617 | shadowTriangleStrip, outlineCentroid); |
| 618 | |
ztenghui | c50a03d | 2014-08-21 13:47:54 -0700 | [diff] [blame] | 619 | } |
| 620 | |
ztenghui | 7b4516e | 2014-01-07 10:42:55 -0800 | [diff] [blame] | 621 | /** |
Chris Craik | 726118b | 2014-03-07 18:27:49 -0800 | [diff] [blame] | 622 | * Converts a polygon specified with CW vertices into an array of distance-from-centroid values. |
| 623 | * |
| 624 | * Returns false in error conditions |
| 625 | * |
| 626 | * @param poly Array of vertices. Note that these *must* be CW. |
| 627 | * @param polyLength The number of vertices in the polygon. |
| 628 | * @param polyCentroid The centroid of the polygon, from which rays will be cast |
| 629 | * @param rayDist The output array for the calculated distances, must be SHADOW_RAY_COUNT in size |
| 630 | */ |
| 631 | bool convertPolyToRayDist(const Vector2* poly, int polyLength, const Vector2& polyCentroid, |
| 632 | float* rayDist) { |
| 633 | const int rays = SHADOW_RAY_COUNT; |
| 634 | const float step = M_PI * 2 / rays; |
| 635 | |
| 636 | const Vector2* lastVertex = &(poly[polyLength - 1]); |
| 637 | float startAngle = angle(*lastVertex, polyCentroid); |
| 638 | |
| 639 | // Start with the ray that's closest to and less than startAngle |
| 640 | int rayIndex = floor((startAngle - EPSILON) / step); |
| 641 | rayIndex = (rayIndex + rays) % rays; // ensure positive |
| 642 | |
| 643 | for (int polyIndex = 0; polyIndex < polyLength; polyIndex++) { |
| 644 | /* |
| 645 | * For a given pair of vertices on the polygon, poly[i-1] and poly[i], the rays that |
| 646 | * intersect these will be those that are between the two angles from the centroid that the |
| 647 | * vertices define. |
| 648 | * |
| 649 | * Because the polygon vertices are stored clockwise, the closest ray with an angle |
| 650 | * *smaller* than that defined by angle(poly[i], centroid) will be the first ray that does |
| 651 | * not intersect with poly[i-1], poly[i]. |
| 652 | */ |
| 653 | float currentAngle = angle(poly[polyIndex], polyCentroid); |
| 654 | |
| 655 | // find first ray that will not intersect the line segment poly[i-1] & poly[i] |
| 656 | int firstRayIndexOnNextSegment = floor((currentAngle - EPSILON) / step); |
| 657 | firstRayIndexOnNextSegment = (firstRayIndexOnNextSegment + rays) % rays; // ensure positive |
| 658 | |
| 659 | // Iterate through all rays that intersect with poly[i-1], poly[i] line segment. |
| 660 | // This may be 0 rays. |
| 661 | while (rayIndex != firstRayIndexOnNextSegment) { |
| 662 | float distanceToIntersect = rayIntersectPoints(polyCentroid, |
| 663 | cos(rayIndex * step), |
| 664 | sin(rayIndex * step), |
| 665 | *lastVertex, poly[polyIndex]); |
ztenghui | 50ecf84 | 2014-03-11 16:52:30 -0700 | [diff] [blame] | 666 | if (distanceToIntersect < 0) { |
| 667 | #if DEBUG_SHADOW |
| 668 | ALOGW("ERROR: convertPolyToRayDist failed"); |
| 669 | #endif |
| 670 | return false; // error case, abort |
| 671 | } |
Chris Craik | 726118b | 2014-03-07 18:27:49 -0800 | [diff] [blame] | 672 | |
| 673 | rayDist[rayIndex] = distanceToIntersect; |
| 674 | |
| 675 | rayIndex = (rayIndex - 1 + rays) % rays; |
| 676 | } |
| 677 | lastVertex = &poly[polyIndex]; |
| 678 | } |
| 679 | |
ztenghui | 512e643 | 2014-09-10 13:08:20 -0700 | [diff] [blame] | 680 | return true; |
Chris Craik | 726118b | 2014-03-07 18:27:49 -0800 | [diff] [blame] | 681 | } |
| 682 | |
| 683 | /** |
ztenghui | 7b4516e | 2014-01-07 10:42:55 -0800 | [diff] [blame] | 684 | * This is only for experimental purpose. |
| 685 | * After intersections are calculated, we could smooth the polygon if needed. |
| 686 | * So far, we don't think it is more appealing yet. |
| 687 | * |
| 688 | * @param level The level of smoothness. |
| 689 | * @param rays The total number of rays. |
| 690 | * @param rayDist (In and Out) The distance for each ray. |
| 691 | * |
| 692 | */ |
| 693 | void SpotShadow::smoothPolygon(int level, int rays, float* rayDist) { |
| 694 | for (int k = 0; k < level; k++) { |
| 695 | for (int i = 0; i < rays; i++) { |
| 696 | float p1 = rayDist[(rays - 1 + i) % rays]; |
| 697 | float p2 = rayDist[i]; |
| 698 | float p3 = rayDist[(i + 1) % rays]; |
| 699 | rayDist[i] = (p1 + p2 * 2 + p3) / 4; |
| 700 | } |
| 701 | } |
| 702 | } |
| 703 | |
ztenghui | 512e643 | 2014-09-10 13:08:20 -0700 | [diff] [blame] | 704 | /** |
| 705 | * Generate a array of the angleData for either umbra or penumbra vertices. |
| 706 | * |
| 707 | * This array will be merged and used to guide where to shoot the rays, in clockwise order. |
| 708 | * |
| 709 | * @param angleDataList The result array of angle data. |
| 710 | * |
| 711 | * @return int The maximum angle's index in the array. |
| 712 | */ |
| 713 | int SpotShadow::setupAngleList(VertexAngleData* angleDataList, |
| 714 | int polyLength, const Vector2* polygon, const Vector2& centroid, |
| 715 | bool isPenumbra, const char* name) { |
| 716 | float maxAngle = FLT_MIN; |
| 717 | int maxAngleIndex = 0; |
| 718 | for (int i = 0; i < polyLength; i++) { |
| 719 | float currentAngle = angle(polygon[i], centroid); |
| 720 | if (currentAngle > maxAngle) { |
| 721 | maxAngle = currentAngle; |
| 722 | maxAngleIndex = i; |
| 723 | } |
| 724 | angleDataList[i].set(currentAngle, isPenumbra, i); |
| 725 | #if DEBUG_SHADOW |
| 726 | ALOGD("%s AngleList i %d %f", name, i, currentAngle); |
| 727 | #endif |
| 728 | } |
| 729 | return maxAngleIndex; |
| 730 | } |
| 731 | |
| 732 | /** |
| 733 | * Make sure the polygons are indeed in clockwise order. |
| 734 | * |
| 735 | * Possible reasons to return false: 1. The input polygon is not setup properly. 2. The hull |
| 736 | * algorithm is not able to generate it properly. |
| 737 | * |
| 738 | * Anyway, since the algorithm depends on the clockwise, when these kind of unexpected error |
| 739 | * situation is found, we need to detect it and early return without corrupting the memory. |
| 740 | * |
| 741 | * @return bool True if the angle list is actually from big to small. |
| 742 | */ |
| 743 | bool SpotShadow::checkClockwise(int indexOfMaxAngle, int listLength, VertexAngleData* angleList, |
| 744 | const char* name) { |
| 745 | int currentIndex = indexOfMaxAngle; |
| 746 | #if DEBUG_SHADOW |
| 747 | ALOGD("max index %d", currentIndex); |
| 748 | #endif |
| 749 | for (int i = 0; i < listLength - 1; i++) { |
| 750 | // TODO: Cache the last angle. |
| 751 | float currentAngle = angleList[currentIndex].mAngle; |
| 752 | float nextAngle = angleList[(currentIndex + 1) % listLength].mAngle; |
| 753 | if (currentAngle < nextAngle) { |
| 754 | #if DEBUG_SHADOW |
| 755 | ALOGE("%s, is not CW, at index %d", name, currentIndex); |
| 756 | #endif |
| 757 | return false; |
| 758 | } |
| 759 | currentIndex = (currentIndex + 1) % listLength; |
| 760 | } |
| 761 | return true; |
| 762 | } |
| 763 | |
| 764 | /** |
| 765 | * Check the polygon is clockwise. |
| 766 | * |
| 767 | * @return bool True is the polygon is clockwise. |
| 768 | */ |
| 769 | bool SpotShadow::checkPolyClockwise(int polyAngleLength, int maxPolyAngleIndex, |
| 770 | const float* polyAngleList) { |
| 771 | bool isPolyCW = true; |
| 772 | // Starting from maxPolyAngleIndex , check around to make sure angle decrease. |
| 773 | for (int i = 0; i < polyAngleLength - 1; i++) { |
| 774 | float currentAngle = polyAngleList[(i + maxPolyAngleIndex) % polyAngleLength]; |
| 775 | float nextAngle = polyAngleList[(i + maxPolyAngleIndex + 1) % polyAngleLength]; |
| 776 | if (currentAngle < nextAngle) { |
| 777 | isPolyCW = false; |
| 778 | } |
| 779 | } |
| 780 | return isPolyCW; |
| 781 | } |
| 782 | |
| 783 | /** |
| 784 | * Given the sorted array of all the vertices angle data, calculate for each |
| 785 | * vertices, the offset value to array element which represent the start edge |
| 786 | * of the polygon we need to shoot the ray at. |
| 787 | * |
| 788 | * TODO: Calculate this for umbra and penumbra in one loop using one single array. |
| 789 | * |
| 790 | * @param distances The result of the array distance counter. |
| 791 | */ |
| 792 | void SpotShadow::calculateDistanceCounter(bool needsOffsetToUmbra, int angleLength, |
| 793 | const VertexAngleData* allVerticesAngleData, int* distances) { |
| 794 | |
| 795 | bool firstVertexIsPenumbra = allVerticesAngleData[0].mIsPenumbra; |
| 796 | // If we want distance to inner, then we just set to 0 when we see inner. |
| 797 | bool needsSearch = needsOffsetToUmbra ? firstVertexIsPenumbra : !firstVertexIsPenumbra; |
| 798 | int distanceCounter = 0; |
| 799 | if (needsSearch) { |
| 800 | int foundIndex = -1; |
| 801 | for (int i = (angleLength - 1); i >= 0; i--) { |
| 802 | bool currentIsOuter = allVerticesAngleData[i].mIsPenumbra; |
| 803 | // If we need distance to inner, then we need to find a inner vertex. |
| 804 | if (currentIsOuter != firstVertexIsPenumbra) { |
| 805 | foundIndex = i; |
| 806 | break; |
| 807 | } |
| 808 | } |
| 809 | LOG_ALWAYS_FATAL_IF(foundIndex == -1, "Wrong index found, means either" |
| 810 | " umbra or penumbra's length is 0"); |
| 811 | distanceCounter = angleLength - foundIndex; |
| 812 | } |
| 813 | #if DEBUG_SHADOW |
| 814 | ALOGD("distances[0] is %d", distanceCounter); |
| 815 | #endif |
| 816 | |
| 817 | distances[0] = distanceCounter; // means never see a target poly |
| 818 | |
| 819 | for (int i = 1; i < angleLength; i++) { |
| 820 | bool firstVertexIsPenumbra = allVerticesAngleData[i].mIsPenumbra; |
| 821 | // When we needs for distance for each outer vertex to inner, then we |
| 822 | // increase the distance when seeing outer vertices. Otherwise, we clear |
| 823 | // to 0. |
| 824 | bool needsIncrement = needsOffsetToUmbra ? firstVertexIsPenumbra : !firstVertexIsPenumbra; |
| 825 | // If counter is not -1, that means we have seen an other polygon's vertex. |
| 826 | if (needsIncrement && distanceCounter != -1) { |
| 827 | distanceCounter++; |
| 828 | } else { |
| 829 | distanceCounter = 0; |
| 830 | } |
| 831 | distances[i] = distanceCounter; |
| 832 | } |
| 833 | } |
| 834 | |
| 835 | /** |
| 836 | * Given umbra and penumbra angle data list, merge them by sorting the angle |
| 837 | * from the biggest to smallest. |
| 838 | * |
| 839 | * @param allVerticesAngleData The result array of merged angle data. |
| 840 | */ |
| 841 | void SpotShadow::mergeAngleList(int maxUmbraAngleIndex, int maxPenumbraAngleIndex, |
| 842 | const VertexAngleData* umbraAngleList, int umbraLength, |
| 843 | const VertexAngleData* penumbraAngleList, int penumbraLength, |
| 844 | VertexAngleData* allVerticesAngleData) { |
| 845 | |
| 846 | int totalRayNumber = umbraLength + penumbraLength; |
| 847 | int umbraIndex = maxUmbraAngleIndex; |
| 848 | int penumbraIndex = maxPenumbraAngleIndex; |
| 849 | |
| 850 | float currentUmbraAngle = umbraAngleList[umbraIndex].mAngle; |
| 851 | float currentPenumbraAngle = penumbraAngleList[penumbraIndex].mAngle; |
| 852 | |
| 853 | // TODO: Clean this up using a while loop with 2 iterators. |
| 854 | for (int i = 0; i < totalRayNumber; i++) { |
| 855 | if (currentUmbraAngle > currentPenumbraAngle) { |
| 856 | allVerticesAngleData[i] = umbraAngleList[umbraIndex]; |
| 857 | umbraIndex = (umbraIndex + 1) % umbraLength; |
| 858 | |
| 859 | // If umbraIndex round back, that means we are running out of |
| 860 | // umbra vertices to merge, so just copy all the penumbra leftover. |
| 861 | // Otherwise, we update the currentUmbraAngle. |
| 862 | if (umbraIndex != maxUmbraAngleIndex) { |
| 863 | currentUmbraAngle = umbraAngleList[umbraIndex].mAngle; |
| 864 | } else { |
| 865 | for (int j = i + 1; j < totalRayNumber; j++) { |
| 866 | allVerticesAngleData[j] = penumbraAngleList[penumbraIndex]; |
| 867 | penumbraIndex = (penumbraIndex + 1) % penumbraLength; |
| 868 | } |
| 869 | break; |
| 870 | } |
| 871 | } else { |
| 872 | allVerticesAngleData[i] = penumbraAngleList[penumbraIndex]; |
| 873 | penumbraIndex = (penumbraIndex + 1) % penumbraLength; |
| 874 | // If penumbraIndex round back, that means we are running out of |
| 875 | // penumbra vertices to merge, so just copy all the umbra leftover. |
| 876 | // Otherwise, we update the currentPenumbraAngle. |
| 877 | if (penumbraIndex != maxPenumbraAngleIndex) { |
| 878 | currentPenumbraAngle = penumbraAngleList[penumbraIndex].mAngle; |
| 879 | } else { |
| 880 | for (int j = i + 1; j < totalRayNumber; j++) { |
| 881 | allVerticesAngleData[j] = umbraAngleList[umbraIndex]; |
| 882 | umbraIndex = (umbraIndex + 1) % umbraLength; |
| 883 | } |
| 884 | break; |
| 885 | } |
| 886 | } |
| 887 | } |
| 888 | } |
| 889 | |
| 890 | #if DEBUG_SHADOW |
| 891 | /** |
| 892 | * DEBUG ONLY: Verify all the offset compuation is correctly done by examining |
| 893 | * each vertex and its neighbor. |
| 894 | */ |
| 895 | static void verifyDistanceCounter(const VertexAngleData* allVerticesAngleData, |
| 896 | const int* distances, int angleLength, const char* name) { |
| 897 | int currentDistance = distances[0]; |
| 898 | for (int i = 1; i < angleLength; i++) { |
| 899 | if (distances[i] != INT_MIN) { |
| 900 | if (!((currentDistance + 1) == distances[i] |
| 901 | || distances[i] == 0)) { |
| 902 | ALOGE("Wrong distance found at i %d name %s", i, name); |
| 903 | } |
| 904 | currentDistance = distances[i]; |
| 905 | if (currentDistance != 0) { |
| 906 | bool currentOuter = allVerticesAngleData[i].mIsPenumbra; |
| 907 | for (int j = 1; j <= (currentDistance - 1); j++) { |
| 908 | bool neigborOuter = |
| 909 | allVerticesAngleData[(i + angleLength - j) % angleLength].mIsPenumbra; |
| 910 | if (neigborOuter != currentOuter) { |
| 911 | ALOGE("Wrong distance found at i %d name %s", i, name); |
| 912 | } |
| 913 | } |
| 914 | bool oppositeOuter = |
| 915 | allVerticesAngleData[(i + angleLength - currentDistance) % angleLength].mIsPenumbra; |
| 916 | if (oppositeOuter == currentOuter) { |
| 917 | ALOGE("Wrong distance found at i %d name %s", i, name); |
| 918 | } |
| 919 | } |
| 920 | } |
| 921 | } |
| 922 | } |
| 923 | |
| 924 | /** |
| 925 | * DEBUG ONLY: Verify all the angle data compuated are is correctly done |
| 926 | */ |
| 927 | static void verifyAngleData(int totalRayNumber, const VertexAngleData* allVerticesAngleData, |
| 928 | const int* distancesToInner, const int* distancesToOuter, |
| 929 | const VertexAngleData* umbraAngleList, int maxUmbraAngleIndex, int umbraLength, |
| 930 | const VertexAngleData* penumbraAngleList, int maxPenumbraAngleIndex, |
| 931 | int penumbraLength) { |
| 932 | for (int i = 0; i < totalRayNumber; i++) { |
| 933 | ALOGD("currentAngleList i %d, angle %f, isInner %d, index %d distancesToInner" |
| 934 | " %d distancesToOuter %d", i, allVerticesAngleData[i].mAngle, |
| 935 | !allVerticesAngleData[i].mIsPenumbra, |
| 936 | allVerticesAngleData[i].mVertexIndex, distancesToInner[i], distancesToOuter[i]); |
| 937 | } |
| 938 | |
| 939 | verifyDistanceCounter(allVerticesAngleData, distancesToInner, totalRayNumber, "distancesToInner"); |
| 940 | verifyDistanceCounter(allVerticesAngleData, distancesToOuter, totalRayNumber, "distancesToOuter"); |
| 941 | |
| 942 | for (int i = 0; i < totalRayNumber; i++) { |
| 943 | if ((distancesToInner[i] * distancesToOuter[i]) != 0) { |
| 944 | ALOGE("distancesToInner wrong at index %d distancesToInner[i] %d," |
| 945 | " distancesToOuter[i] %d", i, distancesToInner[i], distancesToOuter[i]); |
| 946 | } |
| 947 | } |
| 948 | int currentUmbraVertexIndex = |
| 949 | umbraAngleList[maxUmbraAngleIndex].mVertexIndex; |
| 950 | int currentPenumbraVertexIndex = |
| 951 | penumbraAngleList[maxPenumbraAngleIndex].mVertexIndex; |
| 952 | for (int i = 0; i < totalRayNumber; i++) { |
| 953 | if (allVerticesAngleData[i].mIsPenumbra == true) { |
| 954 | if (allVerticesAngleData[i].mVertexIndex != currentPenumbraVertexIndex) { |
| 955 | ALOGW("wrong penumbra indexing i %d allVerticesAngleData[i].mVertexIndex %d " |
| 956 | "currentpenumbraVertexIndex %d", i, |
| 957 | allVerticesAngleData[i].mVertexIndex, currentPenumbraVertexIndex); |
| 958 | } |
| 959 | currentPenumbraVertexIndex = (currentPenumbraVertexIndex + 1) % penumbraLength; |
| 960 | } else { |
| 961 | if (allVerticesAngleData[i].mVertexIndex != currentUmbraVertexIndex) { |
| 962 | ALOGW("wrong umbra indexing i %d allVerticesAngleData[i].mVertexIndex %d " |
| 963 | "currentUmbraVertexIndex %d", i, |
| 964 | allVerticesAngleData[i].mVertexIndex, currentUmbraVertexIndex); |
| 965 | } |
| 966 | currentUmbraVertexIndex = (currentUmbraVertexIndex + 1) % umbraLength; |
| 967 | } |
| 968 | } |
| 969 | for (int i = 0; i < totalRayNumber - 1; i++) { |
| 970 | float currentAngle = allVerticesAngleData[i].mAngle; |
| 971 | float nextAngle = allVerticesAngleData[(i + 1) % totalRayNumber].mAngle; |
| 972 | if (currentAngle < nextAngle) { |
| 973 | ALOGE("Unexpected angle values!, currentAngle nextAngle %f %f", currentAngle, nextAngle); |
| 974 | } |
| 975 | } |
| 976 | } |
| 977 | #endif |
| 978 | |
| 979 | /** |
| 980 | * In order to compute the occluded umbra, we need to setup the angle data list |
| 981 | * for the polygon data. Since we only store one poly vertex per polygon vertex, |
| 982 | * this array only needs to be a float array which are the angles for each vertex. |
| 983 | * |
| 984 | * @param polyAngleList The result list |
| 985 | * |
| 986 | * @return int The index for the maximum angle in this array. |
| 987 | */ |
| 988 | int SpotShadow::setupPolyAngleList(float* polyAngleList, int polyAngleLength, |
| 989 | const Vector2* poly2d, const Vector2& centroid) { |
| 990 | int maxPolyAngleIndex = -1; |
| 991 | float maxPolyAngle = -FLT_MAX; |
| 992 | for (int i = 0; i < polyAngleLength; i++) { |
| 993 | polyAngleList[i] = angle(poly2d[i], centroid); |
| 994 | if (polyAngleList[i] > maxPolyAngle) { |
| 995 | maxPolyAngle = polyAngleList[i]; |
| 996 | maxPolyAngleIndex = i; |
| 997 | } |
| 998 | } |
| 999 | return maxPolyAngleIndex; |
| 1000 | } |
| 1001 | |
| 1002 | /** |
| 1003 | * For umbra and penumbra, given the offset info and the current ray number, |
| 1004 | * find the right edge index (the (starting vertex) for the ray to shoot at. |
| 1005 | * |
| 1006 | * @return int The index of the starting vertex of the edge. |
| 1007 | */ |
| 1008 | inline int SpotShadow::getEdgeStartIndex(const int* offsets, int rayIndex, int totalRayNumber, |
| 1009 | const VertexAngleData* allVerticesAngleData) { |
| 1010 | int tempOffset = offsets[rayIndex]; |
| 1011 | int targetRayIndex = (rayIndex - tempOffset + totalRayNumber) % totalRayNumber; |
| 1012 | return allVerticesAngleData[targetRayIndex].mVertexIndex; |
| 1013 | } |
| 1014 | |
| 1015 | /** |
| 1016 | * For the occluded umbra, given the array of angles, find the index of the |
| 1017 | * starting vertex of the edge, for the ray to shoo at. |
| 1018 | * |
| 1019 | * TODO: Save the last result to shorten the search distance. |
| 1020 | * |
| 1021 | * @return int The index of the starting vertex of the edge. |
| 1022 | */ |
| 1023 | inline int SpotShadow::getPolyEdgeStartIndex(int maxPolyAngleIndex, int polyLength, |
| 1024 | const float* polyAngleList, float rayAngle) { |
| 1025 | int minPolyAngleIndex = (maxPolyAngleIndex + polyLength - 1) % polyLength; |
| 1026 | int resultIndex = -1; |
| 1027 | if (rayAngle > polyAngleList[maxPolyAngleIndex] |
| 1028 | || rayAngle <= polyAngleList[minPolyAngleIndex]) { |
| 1029 | resultIndex = minPolyAngleIndex; |
| 1030 | } else { |
| 1031 | for (int i = 0; i < polyLength - 1; i++) { |
| 1032 | int currentIndex = (maxPolyAngleIndex + i) % polyLength; |
| 1033 | int nextIndex = (maxPolyAngleIndex + i + 1) % polyLength; |
| 1034 | if (rayAngle <= polyAngleList[currentIndex] |
| 1035 | && rayAngle > polyAngleList[nextIndex]) { |
| 1036 | resultIndex = currentIndex; |
| 1037 | } |
| 1038 | } |
| 1039 | } |
| 1040 | if (CC_UNLIKELY(resultIndex == -1)) { |
| 1041 | // TODO: Add more error handling here. |
| 1042 | ALOGE("Wrong index found, means no edge can't be found for rayAngle %f", rayAngle); |
| 1043 | } |
| 1044 | return resultIndex; |
| 1045 | } |
| 1046 | |
| 1047 | /** |
| 1048 | * Convert the incoming polygons into arrays of vertices, for each ray. |
| 1049 | * Ray only shoots when there is one vertex either on penumbra on umbra. |
| 1050 | * |
| 1051 | * Finally, it will generate vertices per ray for umbra, penumbra and optionally |
| 1052 | * occludedUmbra. |
| 1053 | * |
| 1054 | * Return true (success) when all vertices are generated |
| 1055 | */ |
| 1056 | int SpotShadow::convertPolysToVerticesPerRay( |
| 1057 | bool hasOccludedUmbraArea, const Vector2* poly2d, int polyLength, |
| 1058 | const Vector2* umbra, int umbraLength, const Vector2* penumbra, |
| 1059 | int penumbraLength, const Vector2& centroid, |
| 1060 | Vector2* umbraVerticesPerRay, Vector2* penumbraVerticesPerRay, |
| 1061 | Vector2* occludedUmbraVerticesPerRay) { |
| 1062 | int totalRayNumber = umbraLength + penumbraLength; |
| 1063 | |
| 1064 | // For incoming umbra / penumbra polygons, we will build an intermediate data |
| 1065 | // structure to help us sort all the vertices according to the vertices. |
| 1066 | // Using this data structure, we can tell where (the angle) to shoot the ray, |
| 1067 | // whether we shoot at penumbra edge or umbra edge, and which edge to shoot at. |
| 1068 | // |
| 1069 | // We first parse each vertices and generate a table of VertexAngleData. |
| 1070 | // Based on that, we create 2 arrays telling us which edge to shoot at. |
| 1071 | VertexAngleData allVerticesAngleData[totalRayNumber]; |
| 1072 | VertexAngleData umbraAngleList[umbraLength]; |
| 1073 | VertexAngleData penumbraAngleList[penumbraLength]; |
| 1074 | |
| 1075 | int polyAngleLength = hasOccludedUmbraArea ? polyLength : 0; |
| 1076 | float polyAngleList[polyAngleLength]; |
| 1077 | |
| 1078 | const int maxUmbraAngleIndex = |
| 1079 | setupAngleList(umbraAngleList, umbraLength, umbra, centroid, false, "umbra"); |
| 1080 | const int maxPenumbraAngleIndex = |
| 1081 | setupAngleList(penumbraAngleList, penumbraLength, penumbra, centroid, true, "penumbra"); |
| 1082 | const int maxPolyAngleIndex = setupPolyAngleList(polyAngleList, polyAngleLength, poly2d, centroid); |
| 1083 | |
| 1084 | // Check all the polygons here are CW. |
| 1085 | bool isPolyCW = checkPolyClockwise(polyAngleLength, maxPolyAngleIndex, polyAngleList); |
| 1086 | bool isUmbraCW = checkClockwise(maxUmbraAngleIndex, umbraLength, |
| 1087 | umbraAngleList, "umbra"); |
| 1088 | bool isPenumbraCW = checkClockwise(maxPenumbraAngleIndex, penumbraLength, |
| 1089 | penumbraAngleList, "penumbra"); |
| 1090 | |
| 1091 | if (!isUmbraCW || !isPenumbraCW || !isPolyCW) { |
| 1092 | #if DEBUG_SHADOW |
| 1093 | ALOGE("One polygon is not CW isUmbraCW %d isPenumbraCW %d isPolyCW %d", |
| 1094 | isUmbraCW, isPenumbraCW, isPolyCW); |
| 1095 | #endif |
| 1096 | return false; |
| 1097 | } |
| 1098 | |
| 1099 | mergeAngleList(maxUmbraAngleIndex, maxPenumbraAngleIndex, |
| 1100 | umbraAngleList, umbraLength, penumbraAngleList, penumbraLength, |
| 1101 | allVerticesAngleData); |
| 1102 | |
| 1103 | // Calculate the offset to the left most Inner vertex for each outerVertex. |
| 1104 | // Then the offset to the left most Outer vertex for each innerVertex. |
| 1105 | int offsetToInner[totalRayNumber]; |
| 1106 | int offsetToOuter[totalRayNumber]; |
| 1107 | calculateDistanceCounter(true, totalRayNumber, allVerticesAngleData, offsetToInner); |
| 1108 | calculateDistanceCounter(false, totalRayNumber, allVerticesAngleData, offsetToOuter); |
| 1109 | |
| 1110 | // Generate both umbraVerticesPerRay and penumbraVerticesPerRay |
| 1111 | for (int i = 0; i < totalRayNumber; i++) { |
| 1112 | float rayAngle = allVerticesAngleData[i].mAngle; |
| 1113 | bool isUmbraVertex = !allVerticesAngleData[i].mIsPenumbra; |
| 1114 | |
| 1115 | float dx = cosf(rayAngle); |
| 1116 | float dy = sinf(rayAngle); |
| 1117 | float distanceToIntersectUmbra = -1; |
| 1118 | |
| 1119 | if (isUmbraVertex) { |
| 1120 | // We can just copy umbra easily, and calculate the distance for the |
| 1121 | // occluded umbra computation. |
| 1122 | int startUmbraIndex = allVerticesAngleData[i].mVertexIndex; |
| 1123 | umbraVerticesPerRay[i] = umbra[startUmbraIndex]; |
| 1124 | if (hasOccludedUmbraArea) { |
| 1125 | distanceToIntersectUmbra = (umbraVerticesPerRay[i] - centroid).length(); |
| 1126 | } |
| 1127 | |
| 1128 | //shoot ray to penumbra only |
| 1129 | int startPenumbraIndex = getEdgeStartIndex(offsetToOuter, i, totalRayNumber, |
| 1130 | allVerticesAngleData); |
| 1131 | float distanceToIntersectPenumbra = rayIntersectPoints(centroid, dx, dy, |
| 1132 | penumbra[startPenumbraIndex], |
| 1133 | penumbra[(startPenumbraIndex + 1) % penumbraLength]); |
| 1134 | if (distanceToIntersectPenumbra < 0) { |
| 1135 | #if DEBUG_SHADOW |
| 1136 | ALOGW("convertPolyToRayDist for penumbra failed rayAngle %f dx %f dy %f", |
| 1137 | rayAngle, dx, dy); |
| 1138 | #endif |
| 1139 | distanceToIntersectPenumbra = 0; |
| 1140 | } |
| 1141 | penumbraVerticesPerRay[i].x = centroid.x + dx * distanceToIntersectPenumbra; |
| 1142 | penumbraVerticesPerRay[i].y = centroid.y + dy * distanceToIntersectPenumbra; |
| 1143 | } else { |
| 1144 | // We can just copy the penumbra |
| 1145 | int startPenumbraIndex = allVerticesAngleData[i].mVertexIndex; |
| 1146 | penumbraVerticesPerRay[i] = penumbra[startPenumbraIndex]; |
| 1147 | |
| 1148 | // And shoot ray to umbra only |
| 1149 | int startUmbraIndex = getEdgeStartIndex(offsetToInner, i, totalRayNumber, |
| 1150 | allVerticesAngleData); |
| 1151 | |
| 1152 | distanceToIntersectUmbra = rayIntersectPoints(centroid, dx, dy, |
| 1153 | umbra[startUmbraIndex], umbra[(startUmbraIndex + 1) % umbraLength]); |
| 1154 | if (distanceToIntersectUmbra < 0) { |
| 1155 | #if DEBUG_SHADOW |
| 1156 | ALOGW("convertPolyToRayDist for umbra failed rayAngle %f dx %f dy %f", |
| 1157 | rayAngle, dx, dy); |
| 1158 | #endif |
| 1159 | distanceToIntersectUmbra = 0; |
| 1160 | } |
| 1161 | umbraVerticesPerRay[i].x = centroid.x + dx * distanceToIntersectUmbra; |
| 1162 | umbraVerticesPerRay[i].y = centroid.y + dy * distanceToIntersectUmbra; |
| 1163 | } |
| 1164 | |
| 1165 | if (hasOccludedUmbraArea) { |
| 1166 | // Shoot the same ray to the poly2d, and get the distance. |
| 1167 | int startPolyIndex = getPolyEdgeStartIndex(maxPolyAngleIndex, polyLength, |
| 1168 | polyAngleList, rayAngle); |
| 1169 | |
| 1170 | float distanceToIntersectPoly = rayIntersectPoints(centroid, dx, dy, |
| 1171 | poly2d[startPolyIndex], poly2d[(startPolyIndex + 1) % polyLength]); |
| 1172 | if (distanceToIntersectPoly < 0) { |
| 1173 | distanceToIntersectPoly = 0; |
| 1174 | } |
| 1175 | distanceToIntersectPoly = MathUtils::min(distanceToIntersectUmbra, distanceToIntersectPoly); |
| 1176 | occludedUmbraVerticesPerRay[i].x = centroid.x + dx * distanceToIntersectPoly; |
| 1177 | occludedUmbraVerticesPerRay[i].y = centroid.y + dy * distanceToIntersectPoly; |
| 1178 | } |
| 1179 | } |
| 1180 | |
| 1181 | #if DEBUG_SHADOW |
| 1182 | verifyAngleData(totalRayNumber, allVerticesAngleData, offsetToInner, |
| 1183 | offsetToOuter, umbraAngleList, maxUmbraAngleIndex, umbraLength, |
| 1184 | penumbraAngleList, maxPenumbraAngleIndex, penumbraLength); |
| 1185 | #endif |
| 1186 | return true; // success |
| 1187 | |
| 1188 | } |
| 1189 | |
| 1190 | /** |
| 1191 | * Generate a triangle strip given two convex polygon |
| 1192 | **/ |
| 1193 | void SpotShadow::generateTriangleStrip(bool isCasterOpaque, float shadowStrengthScale, |
| 1194 | Vector2* penumbra, int penumbraLength, Vector2* umbra, int umbraLength, |
| 1195 | const Vector3* poly, int polyLength, VertexBuffer& shadowTriangleStrip, |
| 1196 | const Vector2& centroid) { |
| 1197 | |
| 1198 | bool hasOccludedUmbraArea = false; |
| 1199 | Vector2 poly2d[polyLength]; |
| 1200 | |
| 1201 | if (isCasterOpaque) { |
| 1202 | for (int i = 0; i < polyLength; i++) { |
| 1203 | poly2d[i].x = poly[i].x; |
| 1204 | poly2d[i].y = poly[i].y; |
| 1205 | } |
| 1206 | // Make sure the centroid is inside the umbra, otherwise, fall back to the |
| 1207 | // approach as if there is no occluded umbra area. |
| 1208 | if (testPointInsidePolygon(centroid, poly2d, polyLength)) { |
| 1209 | hasOccludedUmbraArea = true; |
| 1210 | } |
| 1211 | } |
| 1212 | |
| 1213 | int totalRayNum = umbraLength + penumbraLength; |
| 1214 | Vector2 umbraVertices[totalRayNum]; |
| 1215 | Vector2 penumbraVertices[totalRayNum]; |
| 1216 | Vector2 occludedUmbraVertices[totalRayNum]; |
| 1217 | bool convertSuccess = convertPolysToVerticesPerRay(hasOccludedUmbraArea, poly2d, |
| 1218 | polyLength, umbra, umbraLength, penumbra, penumbraLength, |
| 1219 | centroid, umbraVertices, penumbraVertices, occludedUmbraVertices); |
| 1220 | if (!convertSuccess) { |
| 1221 | return; |
| 1222 | } |
| 1223 | |
| 1224 | // Minimal value is 1, for each vertex show up once. |
| 1225 | // The bigger this value is , the smoother the look is, but more memory |
| 1226 | // is consumed. |
| 1227 | // When the ray number is high, that means the polygon has been fine |
| 1228 | // tessellated, we don't need this extra slice, just keep it as 1. |
| 1229 | int sliceNumberPerEdge = (totalRayNum > FINE_TESSELLATED_POLYGON_RAY_NUMBER) ? 1 : 2; |
| 1230 | |
| 1231 | // For each polygon, we at most add (totalRayNum * sliceNumberPerEdge) vertices. |
| 1232 | int slicedVertexCountPerPolygon = totalRayNum * sliceNumberPerEdge; |
| 1233 | int totalVertexCount = slicedVertexCountPerPolygon * 2 + totalRayNum; |
| 1234 | int totalIndexCount = 2 * (slicedVertexCountPerPolygon * 2 + 2); |
| 1235 | AlphaVertex* shadowVertices = |
| 1236 | shadowTriangleStrip.alloc<AlphaVertex>(totalVertexCount); |
| 1237 | uint16_t* indexBuffer = |
| 1238 | shadowTriangleStrip.allocIndices<uint16_t>(totalIndexCount); |
| 1239 | |
| 1240 | int indexBufferIndex = 0; |
| 1241 | int vertexBufferIndex = 0; |
| 1242 | |
| 1243 | uint16_t slicedUmbraVertexIndex[totalRayNum * sliceNumberPerEdge]; |
| 1244 | // Should be something like 0 0 0 1 1 1 2 3 3 3... |
| 1245 | int rayNumberPerSlicedUmbra[totalRayNum * sliceNumberPerEdge]; |
| 1246 | int realUmbraVertexCount = 0; |
| 1247 | for (int i = 0; i < totalRayNum; i++) { |
| 1248 | Vector2 currentPenumbra = penumbraVertices[i]; |
| 1249 | Vector2 currentUmbra = umbraVertices[i]; |
| 1250 | |
| 1251 | Vector2 nextPenumbra = penumbraVertices[(i + 1) % totalRayNum]; |
| 1252 | Vector2 nextUmbra = umbraVertices[(i + 1) % totalRayNum]; |
| 1253 | // NextUmbra/Penumbra will be done in the next loop!! |
| 1254 | for (int weight = 0; weight < sliceNumberPerEdge; weight++) { |
| 1255 | const Vector2& slicedPenumbra = (currentPenumbra * (sliceNumberPerEdge - weight) |
| 1256 | + nextPenumbra * weight) / sliceNumberPerEdge; |
| 1257 | |
| 1258 | const Vector2& slicedUmbra = (currentUmbra * (sliceNumberPerEdge - weight) |
| 1259 | + nextUmbra * weight) / sliceNumberPerEdge; |
| 1260 | |
| 1261 | // In the vertex buffer, we fill the Penumbra first, then umbra. |
| 1262 | indexBuffer[indexBufferIndex++] = vertexBufferIndex; |
| 1263 | AlphaVertex::set(&shadowVertices[vertexBufferIndex++], slicedPenumbra.x, |
| 1264 | slicedPenumbra.y, 0.0f); |
| 1265 | |
| 1266 | // When we add umbra vertex, we need to remember its current ray number. |
| 1267 | // And its own vertexBufferIndex. This is for occluded umbra usage. |
| 1268 | indexBuffer[indexBufferIndex++] = vertexBufferIndex; |
| 1269 | rayNumberPerSlicedUmbra[realUmbraVertexCount] = i; |
| 1270 | slicedUmbraVertexIndex[realUmbraVertexCount] = vertexBufferIndex; |
| 1271 | realUmbraVertexCount++; |
| 1272 | AlphaVertex::set(&shadowVertices[vertexBufferIndex++], slicedUmbra.x, |
| 1273 | slicedUmbra.y, M_PI); |
| 1274 | } |
| 1275 | } |
| 1276 | |
| 1277 | indexBuffer[indexBufferIndex++] = 0; |
| 1278 | //RealUmbraVertexIndex[0] must be 1, so we connect back well at the |
| 1279 | //beginning of occluded area. |
| 1280 | indexBuffer[indexBufferIndex++] = 1; |
| 1281 | |
| 1282 | float occludedUmbraAlpha = M_PI; |
| 1283 | if (hasOccludedUmbraArea) { |
| 1284 | // Now the occludedUmbra area; |
| 1285 | int currentRayNumber = -1; |
| 1286 | int firstOccludedUmbraIndex = -1; |
| 1287 | for (int i = 0; i < realUmbraVertexCount; i++) { |
| 1288 | indexBuffer[indexBufferIndex++] = slicedUmbraVertexIndex[i]; |
| 1289 | |
| 1290 | // If the occludedUmbra vertex has not been added yet, then add it. |
| 1291 | // Otherwise, just use the previously added occludedUmbra vertices. |
| 1292 | if (rayNumberPerSlicedUmbra[i] != currentRayNumber) { |
| 1293 | currentRayNumber++; |
| 1294 | indexBuffer[indexBufferIndex++] = vertexBufferIndex; |
| 1295 | // We need to remember the begining of the occludedUmbra vertices |
| 1296 | // to close this loop. |
| 1297 | if (currentRayNumber == 0) { |
| 1298 | firstOccludedUmbraIndex = vertexBufferIndex; |
| 1299 | } |
| 1300 | AlphaVertex::set(&shadowVertices[vertexBufferIndex++], |
| 1301 | occludedUmbraVertices[currentRayNumber].x, |
| 1302 | occludedUmbraVertices[currentRayNumber].y, |
| 1303 | occludedUmbraAlpha); |
| 1304 | } else { |
| 1305 | indexBuffer[indexBufferIndex++] = (vertexBufferIndex - 1); |
| 1306 | } |
| 1307 | } |
| 1308 | // Close the loop here! |
| 1309 | indexBuffer[indexBufferIndex++] = slicedUmbraVertexIndex[0]; |
| 1310 | indexBuffer[indexBufferIndex++] = firstOccludedUmbraIndex; |
| 1311 | } else { |
| 1312 | int lastCentroidIndex = vertexBufferIndex; |
| 1313 | AlphaVertex::set(&shadowVertices[vertexBufferIndex++], centroid.x, |
| 1314 | centroid.y, occludedUmbraAlpha); |
| 1315 | for (int i = 0; i < realUmbraVertexCount; i++) { |
| 1316 | indexBuffer[indexBufferIndex++] = slicedUmbraVertexIndex[i]; |
| 1317 | indexBuffer[indexBufferIndex++] = lastCentroidIndex; |
| 1318 | } |
| 1319 | // Close the loop here! |
| 1320 | indexBuffer[indexBufferIndex++] = slicedUmbraVertexIndex[0]; |
| 1321 | indexBuffer[indexBufferIndex++] = lastCentroidIndex; |
| 1322 | } |
| 1323 | |
| 1324 | #if DEBUG_SHADOW |
| 1325 | ALOGD("allocated IB %d allocated VB is %d", totalIndexCount, totalVertexCount); |
| 1326 | ALOGD("IB index %d VB index is %d", indexBufferIndex, vertexBufferIndex); |
| 1327 | for (int i = 0; i < vertexBufferIndex; i++) { |
| 1328 | ALOGD("vertexBuffer i %d, (%f, %f %f)", i, shadowVertices[i].x, shadowVertices[i].y, |
| 1329 | shadowVertices[i].alpha); |
| 1330 | } |
| 1331 | for (int i = 0; i < indexBufferIndex; i++) { |
| 1332 | ALOGD("indexBuffer i %d, indexBuffer[i] %d", i, indexBuffer[i]); |
| 1333 | } |
| 1334 | #endif |
| 1335 | |
| 1336 | // At the end, update the real index and vertex buffer size. |
| 1337 | shadowTriangleStrip.updateVertexCount(vertexBufferIndex); |
| 1338 | shadowTriangleStrip.updateIndexCount(indexBufferIndex); |
| 1339 | ShadowTessellator::checkOverflow(vertexBufferIndex, totalVertexCount, "Spot Vertex Buffer"); |
| 1340 | ShadowTessellator::checkOverflow(indexBufferIndex, totalIndexCount, "Spot Index Buffer"); |
| 1341 | |
| 1342 | shadowTriangleStrip.setMode(VertexBuffer::kIndices); |
| 1343 | shadowTriangleStrip.computeBounds<AlphaVertex>(); |
| 1344 | } |
| 1345 | |
ztenghui | f5ca8b4 | 2014-01-27 15:53:28 -0800 | [diff] [blame] | 1346 | #if DEBUG_SHADOW |
| 1347 | |
| 1348 | #define TEST_POINT_NUMBER 128 |
ztenghui | f5ca8b4 | 2014-01-27 15:53:28 -0800 | [diff] [blame] | 1349 | /** |
| 1350 | * Calculate the bounds for generating random test points. |
| 1351 | */ |
| 1352 | void SpotShadow::updateBound(const Vector2 inVector, Vector2& lowerBound, |
ztenghui | 512e643 | 2014-09-10 13:08:20 -0700 | [diff] [blame] | 1353 | Vector2& upperBound) { |
ztenghui | f5ca8b4 | 2014-01-27 15:53:28 -0800 | [diff] [blame] | 1354 | if (inVector.x < lowerBound.x) { |
| 1355 | lowerBound.x = inVector.x; |
| 1356 | } |
| 1357 | |
| 1358 | if (inVector.y < lowerBound.y) { |
| 1359 | lowerBound.y = inVector.y; |
| 1360 | } |
| 1361 | |
| 1362 | if (inVector.x > upperBound.x) { |
| 1363 | upperBound.x = inVector.x; |
| 1364 | } |
| 1365 | |
| 1366 | if (inVector.y > upperBound.y) { |
| 1367 | upperBound.y = inVector.y; |
| 1368 | } |
| 1369 | } |
| 1370 | |
| 1371 | /** |
| 1372 | * For debug purpose, when things go wrong, dump the whole polygon data. |
| 1373 | */ |
ztenghui | c50a03d | 2014-08-21 13:47:54 -0700 | [diff] [blame] | 1374 | void SpotShadow::dumpPolygon(const Vector2* poly, int polyLength, const char* polyName) { |
| 1375 | for (int i = 0; i < polyLength; i++) { |
| 1376 | ALOGD("polygon %s i %d x %f y %f", polyName, i, poly[i].x, poly[i].y); |
| 1377 | } |
| 1378 | } |
| 1379 | |
| 1380 | /** |
| 1381 | * For debug purpose, when things go wrong, dump the whole polygon data. |
| 1382 | */ |
| 1383 | void SpotShadow::dumpPolygon(const Vector3* poly, int polyLength, const char* polyName) { |
ztenghui | f5ca8b4 | 2014-01-27 15:53:28 -0800 | [diff] [blame] | 1384 | for (int i = 0; i < polyLength; i++) { |
| 1385 | ALOGD("polygon %s i %d x %f y %f", polyName, i, poly[i].x, poly[i].y); |
| 1386 | } |
| 1387 | } |
| 1388 | |
| 1389 | /** |
| 1390 | * Test whether the polygon is convex. |
| 1391 | */ |
| 1392 | bool SpotShadow::testConvex(const Vector2* polygon, int polygonLength, |
| 1393 | const char* name) { |
| 1394 | bool isConvex = true; |
| 1395 | for (int i = 0; i < polygonLength; i++) { |
| 1396 | Vector2 start = polygon[i]; |
| 1397 | Vector2 middle = polygon[(i + 1) % polygonLength]; |
| 1398 | Vector2 end = polygon[(i + 2) % polygonLength]; |
| 1399 | |
ztenghui | 9122b1b | 2014-10-03 11:21:11 -0700 | [diff] [blame] | 1400 | float delta = (float(middle.x) - start.x) * (float(end.y) - start.y) - |
| 1401 | (float(middle.y) - start.y) * (float(end.x) - start.x); |
ztenghui | f5ca8b4 | 2014-01-27 15:53:28 -0800 | [diff] [blame] | 1402 | bool isCCWOrCoLinear = (delta >= EPSILON); |
| 1403 | |
| 1404 | if (isCCWOrCoLinear) { |
ztenghui | 50ecf84 | 2014-03-11 16:52:30 -0700 | [diff] [blame] | 1405 | ALOGW("(Error Type 2): polygon (%s) is not a convex b/c start (x %f, y %f)," |
ztenghui | f5ca8b4 | 2014-01-27 15:53:28 -0800 | [diff] [blame] | 1406 | "middle (x %f, y %f) and end (x %f, y %f) , delta is %f !!!", |
| 1407 | name, start.x, start.y, middle.x, middle.y, end.x, end.y, delta); |
| 1408 | isConvex = false; |
| 1409 | break; |
| 1410 | } |
| 1411 | } |
| 1412 | return isConvex; |
| 1413 | } |
| 1414 | |
| 1415 | /** |
| 1416 | * Test whether or not the polygon (intersection) is within the 2 input polygons. |
| 1417 | * Using Marte Carlo method, we generate a random point, and if it is inside the |
| 1418 | * intersection, then it must be inside both source polygons. |
| 1419 | */ |
| 1420 | void SpotShadow::testIntersection(const Vector2* poly1, int poly1Length, |
| 1421 | const Vector2* poly2, int poly2Length, |
| 1422 | const Vector2* intersection, int intersectionLength) { |
| 1423 | // Find the min and max of x and y. |
ztenghui | c50a03d | 2014-08-21 13:47:54 -0700 | [diff] [blame] | 1424 | Vector2 lowerBound = {FLT_MAX, FLT_MAX}; |
| 1425 | Vector2 upperBound = {-FLT_MAX, -FLT_MAX}; |
ztenghui | f5ca8b4 | 2014-01-27 15:53:28 -0800 | [diff] [blame] | 1426 | for (int i = 0; i < poly1Length; i++) { |
| 1427 | updateBound(poly1[i], lowerBound, upperBound); |
| 1428 | } |
| 1429 | for (int i = 0; i < poly2Length; i++) { |
| 1430 | updateBound(poly2[i], lowerBound, upperBound); |
| 1431 | } |
| 1432 | |
| 1433 | bool dumpPoly = false; |
| 1434 | for (int k = 0; k < TEST_POINT_NUMBER; k++) { |
| 1435 | // Generate a random point between minX, minY and maxX, maxY. |
ztenghui | 9122b1b | 2014-10-03 11:21:11 -0700 | [diff] [blame] | 1436 | float randomX = rand() / float(RAND_MAX); |
| 1437 | float randomY = rand() / float(RAND_MAX); |
ztenghui | f5ca8b4 | 2014-01-27 15:53:28 -0800 | [diff] [blame] | 1438 | |
| 1439 | Vector2 testPoint; |
| 1440 | testPoint.x = lowerBound.x + randomX * (upperBound.x - lowerBound.x); |
| 1441 | testPoint.y = lowerBound.y + randomY * (upperBound.y - lowerBound.y); |
| 1442 | |
| 1443 | // If the random point is in both poly 1 and 2, then it must be intersection. |
| 1444 | if (testPointInsidePolygon(testPoint, intersection, intersectionLength)) { |
| 1445 | if (!testPointInsidePolygon(testPoint, poly1, poly1Length)) { |
| 1446 | dumpPoly = true; |
ztenghui | 50ecf84 | 2014-03-11 16:52:30 -0700 | [diff] [blame] | 1447 | ALOGW("(Error Type 1): one point (%f, %f) in the intersection is" |
ztenghui | 512e643 | 2014-09-10 13:08:20 -0700 | [diff] [blame] | 1448 | " not in the poly1", |
ztenghui | f5ca8b4 | 2014-01-27 15:53:28 -0800 | [diff] [blame] | 1449 | testPoint.x, testPoint.y); |
| 1450 | } |
| 1451 | |
| 1452 | if (!testPointInsidePolygon(testPoint, poly2, poly2Length)) { |
| 1453 | dumpPoly = true; |
ztenghui | 50ecf84 | 2014-03-11 16:52:30 -0700 | [diff] [blame] | 1454 | ALOGW("(Error Type 1): one point (%f, %f) in the intersection is" |
ztenghui | 512e643 | 2014-09-10 13:08:20 -0700 | [diff] [blame] | 1455 | " not in the poly2", |
ztenghui | f5ca8b4 | 2014-01-27 15:53:28 -0800 | [diff] [blame] | 1456 | testPoint.x, testPoint.y); |
| 1457 | } |
| 1458 | } |
| 1459 | } |
| 1460 | |
| 1461 | if (dumpPoly) { |
| 1462 | dumpPolygon(intersection, intersectionLength, "intersection"); |
| 1463 | for (int i = 1; i < intersectionLength; i++) { |
| 1464 | Vector2 delta = intersection[i] - intersection[i - 1]; |
| 1465 | ALOGD("Intersetion i, %d Vs i-1 is delta %f", i, delta.lengthSquared()); |
| 1466 | } |
| 1467 | |
| 1468 | dumpPolygon(poly1, poly1Length, "poly 1"); |
| 1469 | dumpPolygon(poly2, poly2Length, "poly 2"); |
| 1470 | } |
| 1471 | } |
| 1472 | #endif |
| 1473 | |
ztenghui | 7b4516e | 2014-01-07 10:42:55 -0800 | [diff] [blame] | 1474 | }; // namespace uirenderer |
| 1475 | }; // namespace android |