blob: 904ec8c37c186613e90426eeb03f5a2c5ad69da3 [file] [log] [blame]
ztenghui55bfb4e2013-12-03 10:38:55 -08001/*
2 * Copyright (C) 2013 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
19#include <math.h>
20#include <utils/Log.h>
Chris Craik564acf72014-01-02 16:46:18 -080021#include <utils/Vector.h>
ztenghui55bfb4e2013-12-03 10:38:55 -080022
23#include "AmbientShadow.h"
ztenghui63d41ab2014-02-14 13:13:41 -080024#include "ShadowTessellator.h"
ztenghui55bfb4e2013-12-03 10:38:55 -080025#include "Vertex.h"
26
27namespace android {
28namespace uirenderer {
29
30/**
31 * Calculate the shadows as a triangle strips while alpha value as the
32 * shadow values.
33 *
ztenghui50ecf842014-03-11 16:52:30 -070034 * @param isCasterOpaque Whether the caster is opaque.
ztenghui55bfb4e2013-12-03 10:38:55 -080035 * @param vertices The shadow caster's polygon, which is represented in a Vector3
36 * array.
37 * @param vertexCount The length of caster's polygon in terms of number of
38 * vertices.
ztenghui63d41ab2014-02-14 13:13:41 -080039 * @param centroid3d The centroid of the shadow caster.
ztenghui55bfb4e2013-12-03 10:38:55 -080040 * @param heightFactor The factor showing the higher the object, the lighter the
41 * shadow.
42 * @param geomFactor The factor scaling the geometry expansion along the normal.
43 *
44 * @param shadowVertexBuffer Return an floating point array of (x, y, a)
45 * triangle strips mode.
46 */
ztenghui50ecf842014-03-11 16:52:30 -070047VertexBufferMode AmbientShadow::createAmbientShadow(bool isCasterOpaque,
48 const Vector3* vertices, int vertexCount, const Vector3& centroid3d,
49 float heightFactor, float geomFactor, VertexBuffer& shadowVertexBuffer) {
ztenghui63d41ab2014-02-14 13:13:41 -080050 const int rays = SHADOW_RAY_COUNT;
ztenghui50ecf842014-03-11 16:52:30 -070051 VertexBufferMode mode = kVertexBufferMode_OnePolyRingShadow;
ztenghui55bfb4e2013-12-03 10:38:55 -080052 // Validate the inputs.
Chris Craik726118b2014-03-07 18:27:49 -080053 if (vertexCount < 3 || heightFactor <= 0 || rays <= 0
ztenghui55bfb4e2013-12-03 10:38:55 -080054 || geomFactor <= 0) {
55#if DEBUG_SHADOW
ztenghui50ecf842014-03-11 16:52:30 -070056 ALOGW("Invalid input for createAmbientShadow(), early return!");
ztenghui55bfb4e2013-12-03 10:38:55 -080057#endif
ztenghui50ecf842014-03-11 16:52:30 -070058 return mode; // vertex buffer is empty, so any mode doesn't matter.
ztenghui55bfb4e2013-12-03 10:38:55 -080059 }
ztenghui55bfb4e2013-12-03 10:38:55 -080060
Chris Craik564acf72014-01-02 16:46:18 -080061 Vector<Vector2> dir; // TODO: use C++11 unique_ptr
62 dir.setCapacity(rays);
ztenghui55bfb4e2013-12-03 10:38:55 -080063 float rayDist[rays];
64 float rayHeight[rays];
ztenghui7940dc52014-04-22 11:21:49 -070065 calculateRayDirections(rays, vertices, vertexCount, centroid3d, dir.editArray());
ztenghui55bfb4e2013-12-03 10:38:55 -080066
67 // Calculate the length and height of the points along the edge.
68 //
69 // The math here is:
70 // Intersect each ray (starting from the centroid) with the polygon.
71 for (int i = 0; i < rays; i++) {
72 int edgeIndex;
73 float edgeFraction;
74 float rayDistance;
ztenghui63d41ab2014-02-14 13:13:41 -080075 calculateIntersection(vertices, vertexCount, centroid3d, dir[i], edgeIndex,
ztenghui55bfb4e2013-12-03 10:38:55 -080076 edgeFraction, rayDistance);
77 rayDist[i] = rayDistance;
78 if (edgeIndex < 0 || edgeIndex >= vertexCount) {
79#if DEBUG_SHADOW
ztenghui50ecf842014-03-11 16:52:30 -070080 ALOGW("Invalid edgeIndex!");
ztenghui55bfb4e2013-12-03 10:38:55 -080081#endif
82 edgeIndex = 0;
83 }
84 float h1 = vertices[edgeIndex].z;
85 float h2 = vertices[((edgeIndex + 1) % vertexCount)].z;
86 rayHeight[i] = h1 + edgeFraction * (h2 - h1);
87 }
88
89 // The output buffer length basically is roughly rays * layers, but since we
90 // need triangle strips, so we need to duplicate vertices to accomplish that.
ztenghui50ecf842014-03-11 16:52:30 -070091 AlphaVertex* shadowVertices =
92 shadowVertexBuffer.alloc<AlphaVertex>(SHADOW_VERTEX_COUNT);
ztenghui55bfb4e2013-12-03 10:38:55 -080093
94 // Calculate the vertex of the shadows.
95 //
96 // The math here is:
97 // Along the edges of the polygon, for each intersection point P (generated above),
98 // calculate the normal N, which should be perpendicular to the edge of the
99 // polygon (represented by the neighbor intersection points) .
100 // Shadow's vertices will be generated as : P + N * scale.
ztenghui50ecf842014-03-11 16:52:30 -0700101 const Vector2 centroid2d = Vector2(centroid3d.x, centroid3d.y);
Chris Craik726118b2014-03-07 18:27:49 -0800102 for (int rayIndex = 0; rayIndex < rays; rayIndex++) {
103 Vector2 normal(1.0f, 0.0f);
104 calculateNormal(rays, rayIndex, dir.array(), rayDist, normal);
ztenghui55bfb4e2013-12-03 10:38:55 -0800105
Chris Craik726118b2014-03-07 18:27:49 -0800106 // The vertex should be start from rayDist[i] then scale the
107 // normalizeNormal!
108 Vector2 intersection = dir[rayIndex] * rayDist[rayIndex] +
ztenghui50ecf842014-03-11 16:52:30 -0700109 centroid2d;
ztenghui55bfb4e2013-12-03 10:38:55 -0800110
Chris Craik726118b2014-03-07 18:27:49 -0800111 // outer ring of points, expanded based upon height of each ray intersection
112 float expansionDist = rayHeight[rayIndex] * heightFactor *
113 geomFactor;
114 AlphaVertex::set(&shadowVertices[rayIndex],
115 intersection.x + normal.x * expansionDist,
116 intersection.y + normal.y * expansionDist,
117 0.0f);
ztenghui55bfb4e2013-12-03 10:38:55 -0800118
Chris Craik726118b2014-03-07 18:27:49 -0800119 // inner ring of points
120 float opacity = 1.0 / (1 + rayHeight[rayIndex] * heightFactor);
ztenghui50ecf842014-03-11 16:52:30 -0700121 AlphaVertex::set(&shadowVertices[rays + rayIndex],
Chris Craik726118b2014-03-07 18:27:49 -0800122 intersection.x,
123 intersection.y,
124 opacity);
ztenghui55bfb4e2013-12-03 10:38:55 -0800125 }
ztenghui50ecf842014-03-11 16:52:30 -0700126
127 // If caster isn't opaque, we need to to fill the umbra by storing the umbra's
128 // centroid in the innermost ring of vertices.
129 if (!isCasterOpaque) {
130 mode = kVertexBufferMode_TwoPolyRingShadow;
131 float centroidAlpha = 1.0 / (1 + centroid3d.z * heightFactor);
132 AlphaVertex centroidXYA;
133 AlphaVertex::set(&centroidXYA, centroid2d.x, centroid2d.y, centroidAlpha);
134 for (int rayIndex = 0; rayIndex < rays; rayIndex++) {
135 shadowVertices[2 * rays + rayIndex] = centroidXYA;
136 }
137 }
ztenghui55bfb4e2013-12-03 10:38:55 -0800138
ztenghui55bfb4e2013-12-03 10:38:55 -0800139#if DEBUG_SHADOW
ztenghui63d41ab2014-02-14 13:13:41 -0800140 for (int i = 0; i < SHADOW_VERTEX_COUNT; i++) {
141 ALOGD("ambient shadow value: i %d, (x:%f, y:%f, a:%f)", i, shadowVertices[i].x,
142 shadowVertices[i].y, shadowVertices[i].alpha);
143 }
144#endif
ztenghui50ecf842014-03-11 16:52:30 -0700145 return mode;
ztenghui55bfb4e2013-12-03 10:38:55 -0800146}
147
148/**
149 * Generate an array of rays' direction vectors.
150 *
151 * @param rays The number of rays shooting out from the centroid.
ztenghui7940dc52014-04-22 11:21:49 -0700152 * @param vertices Vertices of the polygon.
153 * @param vertexCount The number of vertices.
154 * @param centroid3d The centroid of the polygon.
ztenghui55bfb4e2013-12-03 10:38:55 -0800155 * @param dir Return the array of ray vectors.
156 */
ztenghui7940dc52014-04-22 11:21:49 -0700157void AmbientShadow::calculateRayDirections(const int rays, const Vector3* vertices,
158 const int vertexCount, const Vector3& centroid3d, Vector2* dir) {
159 // If we don't have enough rays, then fall back to the uniform distribution.
160 if (vertexCount * 2 > rays) {
161 float deltaAngle = 2 * M_PI / rays;
162 for (int i = 0; i < rays; i++) {
163 dir[i].x = sinf(deltaAngle * i);
164 dir[i].y = cosf(deltaAngle * i);
165 }
166 return;
167 }
168
169 // If we have enough rays, then we assign each vertices a ray, and distribute
170 // the rest uniformly.
171 float rayThetas[rays];
172
173 const int uniformRayCount = rays - vertexCount;
174 const float deltaAngle = 2 * M_PI / uniformRayCount;
175
176 // We have to generate all the vertices' theta anyway and we also need to
177 // find the minimal, so let's precompute it first.
178 // Since the incoming polygon is clockwise, we can find the dip to identify
179 // the minimal theta.
180 float polyThetas[vertexCount];
181 int minimalPolyThetaIndex = 0;
182 for (int i = 0; i < vertexCount; i++) {
183 polyThetas[i] = atan2(vertices[i].y - centroid3d.y,
184 vertices[i].x - centroid3d.x);
185 if (i > 0 && polyThetas[i] < polyThetas[i - 1]) {
186 minimalPolyThetaIndex = i;
187 }
188 }
189
190 int polyThetaIndex = minimalPolyThetaIndex;
191 float polyTheta = polyThetas[minimalPolyThetaIndex];
192 int uniformThetaIndex = 0;
193 float uniformTheta = - M_PI;
194 for (int i = 0; i < rays; i++) {
195 // Compare both thetas and pick the smaller one and move on.
196 bool hasThetaCollision = abs(polyTheta - uniformTheta) < MINIMAL_DELTA_THETA;
197 if (polyTheta < uniformTheta || hasThetaCollision) {
198 if (hasThetaCollision) {
199 // Shift the uniformTheta to middle way between current polyTheta
200 // and next uniform theta. The next uniform theta can wrap around
201 // to exactly PI safely here.
202 // Note that neither polyTheta nor uniformTheta can be FLT_MAX
203 // due to the hasThetaCollision is true.
204 uniformTheta = (polyTheta + deltaAngle * (uniformThetaIndex + 1) - M_PI) / 2;
205#if DEBUG_SHADOW
206 ALOGD("Shifted uniformTheta to %f", uniformTheta);
207#endif
208 }
209 rayThetas[i] = polyTheta;
210 polyThetaIndex = (polyThetaIndex + 1) % vertexCount;
211 if (polyThetaIndex != minimalPolyThetaIndex) {
212 polyTheta = polyThetas[polyThetaIndex];
213 } else {
214 // out of poly points.
215 polyTheta = FLT_MAX;
216 }
217 } else {
218 rayThetas[i] = uniformTheta;
219 uniformThetaIndex++;
220 if (uniformThetaIndex < uniformRayCount) {
221 uniformTheta = deltaAngle * uniformThetaIndex - M_PI;
222 } else {
223 // out of uniform points.
224 uniformTheta = FLT_MAX;
225 }
226 }
227 }
ztenghui55bfb4e2013-12-03 10:38:55 -0800228
229 for (int i = 0; i < rays; i++) {
ztenghui7940dc52014-04-22 11:21:49 -0700230#if DEBUG_SHADOW
231 ALOGD("No. %d : %f", i, rayThetas[i] * 180 / M_PI);
232#endif
233 // TODO: Fix the intersection precision problem and remvoe the delta added
234 // here.
235 dir[i].x = sinf(rayThetas[i] + MINIMAL_DELTA_THETA);
236 dir[i].y = cosf(rayThetas[i] + MINIMAL_DELTA_THETA);
ztenghui55bfb4e2013-12-03 10:38:55 -0800237 }
238}
239
240/**
241 * Calculate the intersection of a ray hitting the polygon.
242 *
243 * @param vertices The shadow caster's polygon, which is represented in a
244 * Vector3 array.
245 * @param vertexCount The length of caster's polygon in terms of number of vertices.
246 * @param start The starting point of the ray.
247 * @param dir The direction vector of the ray.
248 *
249 * @param outEdgeIndex Return the index of the segment (or index of the starting
250 * vertex) that ray intersect with.
251 * @param outEdgeFraction Return the fraction offset from the segment starting
252 * index.
253 * @param outRayDist Return the ray distance from centroid to the intersection.
254 */
255void AmbientShadow::calculateIntersection(const Vector3* vertices, int vertexCount,
ztenghui63d41ab2014-02-14 13:13:41 -0800256 const Vector3& start, const Vector2& dir, int& outEdgeIndex,
ztenghui55bfb4e2013-12-03 10:38:55 -0800257 float& outEdgeFraction, float& outRayDist) {
258 float startX = start.x;
259 float startY = start.y;
260 float dirX = dir.x;
261 float dirY = dir.y;
262 // Start the search from the last edge from poly[len-1] to poly[0].
263 int p1 = vertexCount - 1;
264
265 for (int p2 = 0; p2 < vertexCount; p2++) {
266 float p1x = vertices[p1].x;
267 float p1y = vertices[p1].y;
268 float p2x = vertices[p2].x;
269 float p2y = vertices[p2].y;
270
271 // The math here is derived from:
272 // f(t, v) = p1x * (1 - t) + p2x * t - (startX + dirX * v) = 0;
273 // g(t, v) = p1y * (1 - t) + p2y * t - (startY + dirY * v) = 0;
274 float div = (dirX * (p1y - p2y) + dirY * p2x - dirY * p1x);
275 if (div != 0) {
276 float t = (dirX * (p1y - startY) + dirY * startX - dirY * p1x) / (div);
277 if (t > 0 && t <= 1) {
278 float t2 = (p1x * (startY - p2y)
279 + p2x * (p1y - startY)
280 + startX * (p2y - p1y)) / div;
281 if (t2 > 0) {
282 outEdgeIndex = p1;
283 outRayDist = t2;
284 outEdgeFraction = t;
285 return;
286 }
287 }
288 }
289 p1 = p2;
290 }
291 return;
292};
293
294/**
295 * Calculate the normal at the intersection point between a ray and the polygon.
296 *
297 * @param rays The total number of rays.
298 * @param currentRayIndex The index of the ray which the normal is based on.
299 * @param dir The array of the all the rays directions.
300 * @param rayDist The pre-computed ray distances array.
301 *
302 * @param normal Return the normal.
303 */
304void AmbientShadow::calculateNormal(int rays, int currentRayIndex,
305 const Vector2* dir, const float* rayDist, Vector2& normal) {
306 int preIndex = (currentRayIndex - 1 + rays) % rays;
307 int postIndex = (currentRayIndex + 1) % rays;
308 Vector2 p1 = dir[preIndex] * rayDist[preIndex];
309 Vector2 p2 = dir[postIndex] * rayDist[postIndex];
310
311 // Now the V (deltaX, deltaY) is the vector going CW around the poly.
312 Vector2 delta = p2 - p1;
313 if (delta.length() != 0) {
314 delta.normalize();
315 // Calculate the normal , which is CCW 90 rotate to the V.
316 // 90 degrees CCW about z-axis: (x, y, z) -> (-y, x, z)
317 normal.x = -delta.y;
318 normal.y = delta.x;
319 }
320}
321
322}; // namespace uirenderer
323}; // namespace android