ShadowTessellator.cpp revision 272a685f17cc4828257e521a6f62b7b17870f75e
1/*
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#include <math.h>
18#include <utils/Log.h>
19#include <utils/Trace.h>
20#include <utils/MathUtils.h>
21
22#include "AmbientShadow.h"
23#include "Properties.h"
24#include "ShadowTessellator.h"
25#include "SpotShadow.h"
26#include "Vector.h"
27
28namespace android {
29namespace uirenderer {
30
31void ShadowTessellator::tessellateAmbientShadow(bool isCasterOpaque,
32        const Vector3* casterPolygon, int casterVertexCount,
33        const Vector3& centroid3d, const Rect& casterBounds,
34        const Rect& localClip, float maxZ, VertexBuffer& shadowVertexBuffer) {
35    ATRACE_CALL();
36
37    // A bunch of parameters to tweak the shadow.
38    // TODO: Allow some of these changable by debug settings or APIs.
39    float heightFactor = 1.0f / 128;
40    const float geomFactor = 64;
41
42    if (CC_UNLIKELY(Properties::overrideAmbientRatio > 0.0f)) {
43        heightFactor *= Properties::overrideAmbientRatio;
44    }
45
46    Rect ambientShadowBounds(casterBounds);
47    ambientShadowBounds.outset(maxZ * geomFactor * heightFactor);
48
49    if (!localClip.intersects(ambientShadowBounds)) {
50#if DEBUG_SHADOW
51        ALOGD("Ambient shadow is out of clip rect!");
52#endif
53        return;
54    }
55
56    AmbientShadow::createAmbientShadow(isCasterOpaque, casterPolygon,
57            casterVertexCount, centroid3d, heightFactor, geomFactor,
58            shadowVertexBuffer);
59}
60
61void ShadowTessellator::tessellateSpotShadow(bool isCasterOpaque,
62        const Vector3* casterPolygon, int casterVertexCount, const Vector3& casterCentroid,
63        const mat4& receiverTransform, const Vector3& lightCenter, int lightRadius,
64        const Rect& casterBounds, const Rect& localClip, VertexBuffer& shadowVertexBuffer) {
65    ATRACE_CALL();
66
67    Vector3 adjustedLightCenter(lightCenter);
68    if (CC_UNLIKELY(Properties::overrideLightPosY > 0)) {
69        adjustedLightCenter.y = - Properties::overrideLightPosY; // negated since this shifts up
70    }
71    if (CC_UNLIKELY(Properties::overrideLightPosZ > 0)) {
72        adjustedLightCenter.z = Properties::overrideLightPosZ;
73    }
74
75#if DEBUG_SHADOW
76    ALOGD("light center %f %f %f",
77            adjustedLightCenter.x, adjustedLightCenter.y, adjustedLightCenter.z);
78#endif
79
80    // light position (because it's in local space) needs to compensate for receiver transform
81    // TODO: should apply to light orientation, not just position
82    Matrix4 reverseReceiverTransform;
83    reverseReceiverTransform.loadInverse(receiverTransform);
84    reverseReceiverTransform.mapPoint3d(adjustedLightCenter);
85
86    if (CC_UNLIKELY(Properties::overrideLightRadius > 0)) {
87        lightRadius = Properties::overrideLightRadius;
88    }
89
90    // Now light and caster are both in local space, we will check whether
91    // the shadow is within the clip area.
92    Rect lightRect = Rect(adjustedLightCenter.x - lightRadius, adjustedLightCenter.y - lightRadius,
93            adjustedLightCenter.x + lightRadius, adjustedLightCenter.y + lightRadius);
94    lightRect.unionWith(localClip);
95    if (!lightRect.intersects(casterBounds)) {
96#if DEBUG_SHADOW
97        ALOGD("Spot shadow is out of clip rect!");
98#endif
99        return;
100    }
101
102    SpotShadow::createSpotShadow(isCasterOpaque, adjustedLightCenter, lightRadius,
103            casterPolygon, casterVertexCount, casterCentroid, shadowVertexBuffer);
104
105#if DEBUG_SHADOW
106     if(shadowVertexBuffer.getVertexCount() <= 0) {
107        ALOGD("Spot shadow generation failed %d", shadowVertexBuffer.getVertexCount());
108     }
109#endif
110}
111
112/**
113 * Calculate the centroid of a 2d polygon.
114 *
115 * @param poly The polygon, which is represented in a Vector2 array.
116 * @param polyLength The length of the polygon in terms of number of vertices.
117 * @return the centroid of the polygon.
118 */
119Vector2 ShadowTessellator::centroid2d(const Vector2* poly, int polyLength) {
120    double sumx = 0;
121    double sumy = 0;
122    int p1 = polyLength - 1;
123    double area = 0;
124    for (int p2 = 0; p2 < polyLength; p2++) {
125        double x1 = poly[p1].x;
126        double y1 = poly[p1].y;
127        double x2 = poly[p2].x;
128        double y2 = poly[p2].y;
129        double a = (x1 * y2 - x2 * y1);
130        sumx += (x1 + x2) * a;
131        sumy += (y1 + y2) * a;
132        area += a;
133        p1 = p2;
134    }
135
136    Vector2 centroid = poly[0];
137    if (area != 0) {
138        centroid = (Vector2){static_cast<float>(sumx / (3 * area)),
139            static_cast<float>(sumy / (3 * area))};
140    } else {
141        ALOGW("Area is 0 while computing centroid!");
142    }
143    return centroid;
144}
145
146// Make sure p1 -> p2 is going CW around the poly.
147Vector2 ShadowTessellator::calculateNormal(const Vector2& p1, const Vector2& p2) {
148    Vector2 result = p2 - p1;
149    if (result.x != 0 || result.y != 0) {
150        result.normalize();
151        // Calculate the normal , which is CCW 90 rotate to the delta.
152        float tempy = result.y;
153        result.y = result.x;
154        result.x = -tempy;
155    }
156    return result;
157}
158
159int ShadowTessellator::getExtraVertexNumber(const Vector2& vector1,
160        const Vector2& vector2, float divisor) {
161    // When there is no distance difference, there is no need for extra vertices.
162    if (vector1.lengthSquared() == 0 || vector2.lengthSquared() == 0) {
163        return 0;
164    }
165    // The formula is :
166    // extraNumber = floor(acos(dot(n1, n2)) / (M_PI / EXTRA_VERTEX_PER_PI))
167    // The value ranges for each step are:
168    // dot( ) --- [-1, 1]
169    // acos( )     --- [0, M_PI]
170    // floor(...)  --- [0, EXTRA_VERTEX_PER_PI]
171    float dotProduct = vector1.dot(vector2);
172    // make sure that dotProduct value is in acsof input range [-1, 1]
173    dotProduct = MathUtils::clamp(dotProduct, -1.0f, 1.0f);
174    // TODO: Use look up table for the dotProduct to extraVerticesNumber
175    // computation, if needed.
176    float angle = acosf(dotProduct);
177    return (int) floor(angle / divisor);
178}
179
180void ShadowTessellator::checkOverflow(int used, int total, const char* bufferName) {
181    LOG_ALWAYS_FATAL_IF(used > total, "Error: %s overflow!!! used %d, total %d",
182            bufferName, used, total);
183}
184
185}; // namespace uirenderer
186}; // namespace android
187