aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/core
diff options
context:
space:
mode:
Diffstat (limited to 'src/core')
-rw-r--r--src/core/SkLight.h56
-rw-r--r--src/core/SkLightingShader.cpp738
-rw-r--r--src/core/SkLightingShader.h101
-rw-r--r--src/core/SkPoint3.cpp80
-rw-r--r--src/core/SkPoint3.h124
5 files changed, 1099 insertions, 0 deletions
diff --git a/src/core/SkLight.h b/src/core/SkLight.h
new file mode 100644
index 0000000000..4a6e149c76
--- /dev/null
+++ b/src/core/SkLight.h
@@ -0,0 +1,56 @@
+
+/*
+ * Copyright 2015 Google Inc.
+ *
+ * Use of this source code is governed by a BSD-style license that can be
+ * found in the LICENSE file.
+ */
+
+#ifndef SkLight_DEFINED
+#define SkLight_DEFINED
+
+#include "SkPoint3.h"
+
+class SK_API SkLight {
+public:
+ enum LightType {
+ kAmbient_LightType, // only 'fColor' is used
+ kDirectional_LightType
+ };
+
+ SkLight() : fType(kAmbient_LightType) {
+ fColor.set(0.0f, 0.0f, 0.0f);
+ fDirection.set(0.0f, 0.0f, 1.0f);
+ }
+
+ SkLight(const SkColor3f& color)
+ : fType(kAmbient_LightType)
+ , fColor(color) {
+ fDirection.set(0.0f, 0.0f, 1.0f);
+ }
+
+ SkLight(const SkColor3f& color, const SkVector3& dir)
+ : fType(kDirectional_LightType)
+ , fColor(color)
+ , fDirection(dir) {
+ if (!fDirection.normalize()) {
+ fDirection.set(0.0f, 0.0f, 1.0f);
+ }
+ }
+
+ LightType type() const { return fType; }
+ const SkColor3f& color() const { return fColor; }
+ const SkVector3& dir() const {
+ SkASSERT(kAmbient_LightType != fType);
+ return fDirection;
+ }
+
+private:
+ LightType fType;
+ SkColor3f fColor; // linear (unpremul) color. Range is 0..1 in each channel.
+ SkVector3 fDirection; // direction towards the light (+Z is out of the screen).
+ // If degenerate, it will be replaced with (0, 0, 1).
+};
+
+
+#endif
diff --git a/src/core/SkLightingShader.cpp b/src/core/SkLightingShader.cpp
new file mode 100644
index 0000000000..ce5c0ddb25
--- /dev/null
+++ b/src/core/SkLightingShader.cpp
@@ -0,0 +1,738 @@
+
+/*
+ * Copyright 2015 Google Inc.
+ *
+ * Use of this source code is governed by a BSD-style license that can be
+ * found in the LICENSE file.
+ */
+
+#include "SkBitmapProcState.h"
+#include "SkColor.h"
+#include "SkEmptyShader.h"
+#include "SkErrorInternals.h"
+#include "SkLightingShader.h"
+#include "SkMathPriv.h"
+#include "SkPoint3.h"
+#include "SkReadBuffer.h"
+#include "SkWriteBuffer.h"
+
+////////////////////////////////////////////////////////////////////////////
+
+/*
+ SkLightingShader TODOs:
+ support other than clamp mode
+ allow 'diffuse' & 'normal' to be of different dimensions?
+ support different light types
+ support multiple lights
+ enforce normal map is 4 channel
+ use SkImages instead if SkBitmaps
+
+ To Test:
+ non-opaque diffuse textures
+ A8 diffuse textures
+ down & upsampled draws
+*/
+
+
+
+/** \class SkLightingShaderImpl
+ This subclass of shader applies lighting.
+*/
+class SK_API SkLightingShaderImpl : public SkShader {
+public:
+
+ /** Create a new lighting shader that uses the provided normal map and
+ lights to light the diffuse bitmap.
+ @param diffuse the diffuse bitmap
+ @param normal the normal map
+ @param lights the lights applied to the normal map
+ @param invNormRotation rotation applied to the normal map's normals
+ @param diffLocalM the local matrix for the diffuse coordinates
+ @param normLocalM the local matrix for the normal coordinates
+ */
+ SkLightingShaderImpl(const SkBitmap& diffuse, const SkBitmap& normal,
+ const SkLightingShader::Lights* lights,
+ const SkVector& invNormRotation,
+ const SkMatrix* diffLocalM, const SkMatrix* normLocalM)
+ : INHERITED(diffLocalM)
+ , fDiffuseMap(diffuse)
+ , fNormalMap(normal)
+ , fLights(SkRef(lights))
+ , fInvNormRotation(invNormRotation) {
+
+ if (normLocalM) {
+ fNormLocalMatrix = *normLocalM;
+ } else {
+ fNormLocalMatrix.reset();
+ }
+ // Pre-cache so future calls to fNormLocalMatrix.getType() are threadsafe.
+ (void)fNormLocalMatrix.getType();
+
+ }
+
+ bool isOpaque() const override;
+
+ bool asFragmentProcessor(GrContext*, const SkPaint& paint, const SkMatrix& viewM,
+ const SkMatrix* localMatrix, GrColor* color,
+ GrProcessorDataManager*, GrFragmentProcessor** fp) const override;
+
+ size_t contextSize() const override;
+
+ class LightingShaderContext : public SkShader::Context {
+ public:
+ // The context takes ownership of the states. It will call their destructors
+ // but will NOT free the memory.
+ LightingShaderContext(const SkLightingShaderImpl&, const ContextRec&,
+ SkBitmapProcState* diffuseState, SkBitmapProcState* normalState);
+ ~LightingShaderContext() override;
+
+ void shadeSpan(int x, int y, SkPMColor[], int count) override;
+
+ uint32_t getFlags() const override { return fFlags; }
+
+ private:
+ SkBitmapProcState* fDiffuseState;
+ SkBitmapProcState* fNormalState;
+ uint32_t fFlags;
+
+ typedef SkShader::Context INHERITED;
+ };
+
+ SK_TO_STRING_OVERRIDE()
+ SK_DECLARE_PUBLIC_FLATTENABLE_DESERIALIZATION_PROCS(SkLightingShaderImpl)
+
+protected:
+ void flatten(SkWriteBuffer&) const override;
+ Context* onCreateContext(const ContextRec&, void*) const override;
+ bool computeNormTotalInverse(const ContextRec& rec, SkMatrix* normTotalInverse) const;
+
+private:
+ SkBitmap fDiffuseMap;
+ SkBitmap fNormalMap;
+
+ SkAutoTUnref<const SkLightingShader::Lights> fLights;
+
+ SkMatrix fNormLocalMatrix;
+ SkVector fInvNormRotation;
+
+ friend class SkLightingShader;
+
+ typedef SkShader INHERITED;
+};
+
+////////////////////////////////////////////////////////////////////////////
+
+#if SK_SUPPORT_GPU
+
+#include "GrCoordTransform.h"
+#include "GrFragmentProcessor.h"
+#include "GrTextureAccess.h"
+#include "gl/GrGLProcessor.h"
+#include "gl/builders/GrGLProgramBuilder.h"
+#include "SkGr.h"
+
+class LightingFP : public GrFragmentProcessor {
+public:
+ LightingFP(GrProcessorDataManager* pdm, GrTexture* diffuse, GrTexture* normal,
+ const SkMatrix& diffMatrix, const SkMatrix& normMatrix,
+ const GrTextureParams& diffParams, const GrTextureParams& normParams,
+ const SkLightingShader::Lights* lights, const SkVector& invNormRotation)
+ : fDiffDeviceTransform(kLocal_GrCoordSet, diffMatrix, diffuse, diffParams.filterMode())
+ , fNormDeviceTransform(kLocal_GrCoordSet, normMatrix, normal, normParams.filterMode())
+ , fDiffuseTextureAccess(diffuse, diffParams)
+ , fNormalTextureAccess(normal, normParams)
+ , fInvNormRotation(invNormRotation) {
+ this->addCoordTransform(&fDiffDeviceTransform);
+ this->addCoordTransform(&fNormDeviceTransform);
+ this->addTextureAccess(&fDiffuseTextureAccess);
+ this->addTextureAccess(&fNormalTextureAccess);
+
+ // fuse all ambient lights into a single one
+ fAmbientColor.set(0.0f, 0.0f, 0.0f);
+ for (int i = 0; i < lights->numLights(); ++i) {
+ if (SkLight::kAmbient_LightType == lights->light(i).type()) {
+ fAmbientColor += lights->light(i).color();
+ } else {
+ // TODO: handle more than one of these
+ fLightColor = lights->light(i).color();
+ fLightDir = lights->light(i).dir();
+ }
+ }
+
+ this->initClassID<LightingFP>();
+ }
+
+ class LightingGLFP : public GrGLFragmentProcessor {
+ public:
+ LightingGLFP() {
+ fLightDir.fX = 10000.0f;
+ fLightColor.fX = 0.0f;
+ fAmbientColor.fX = 0.0f;
+ fInvNormRotation.fX = 0.0f;
+ }
+
+ void emitCode(EmitArgs& args) override {
+
+ GrGLFragmentBuilder* fpb = args.fBuilder->getFragmentShaderBuilder();
+
+ // add uniforms
+ const char* lightDirUniName = NULL;
+ fLightDirUni = args.fBuilder->addUniform(GrGLProgramBuilder::kFragment_Visibility,
+ kVec3f_GrSLType, kDefault_GrSLPrecision,
+ "LightDir", &lightDirUniName);
+
+ const char* lightColorUniName = NULL;
+ fLightColorUni = args.fBuilder->addUniform(GrGLProgramBuilder::kFragment_Visibility,
+ kVec3f_GrSLType, kDefault_GrSLPrecision,
+ "LightColor", &lightColorUniName);
+
+ const char* ambientColorUniName = NULL;
+ fAmbientColorUni = args.fBuilder->addUniform(GrGLProgramBuilder::kFragment_Visibility,
+ kVec3f_GrSLType, kDefault_GrSLPrecision,
+ "AmbientColor", &ambientColorUniName);
+
+ const char* xformUniName = NULL;
+ fXformUni = args.fBuilder->addUniform(GrGLProgramBuilder::kFragment_Visibility,
+ kVec2f_GrSLType, kDefault_GrSLPrecision,
+ "Xform", &xformUniName);
+
+ fpb->codeAppend("vec4 diffuseColor = ");
+ fpb->appendTextureLookupAndModulate(args.fInputColor, args.fSamplers[0],
+ args.fCoords[0].c_str(),
+ args.fCoords[0].getType());
+ fpb->codeAppend(";");
+
+ fpb->codeAppend("vec4 normalColor = ");
+ fpb->appendTextureLookup(args.fSamplers[1],
+ args.fCoords[1].c_str(),
+ args.fCoords[1].getType());
+ fpb->codeAppend(";");
+
+ fpb->codeAppend("vec3 normal = normalColor.rgb - vec3(0.5);");
+
+ fpb->codeAppendf("mat3 m = mat3(%s.x, -%s.y, 0.0, %s.y, %s.x, 0.0, 0.0, 0.0, 1.0);",
+ xformUniName, xformUniName, xformUniName, xformUniName);
+
+ // TODO: inverse map the light direction vectors in the vertex shader rather than
+ // transforming all the normals here!
+ fpb->codeAppend("normal = normalize(m*normal);");
+
+ fpb->codeAppendf("float NdotL = clamp(dot(normal, %s), 0.0, 1.0);", lightDirUniName);
+ // diffuse light
+ fpb->codeAppendf("vec3 result = %s*diffuseColor.rgb*NdotL;", lightColorUniName);
+ // ambient light
+ fpb->codeAppendf("result += %s;", ambientColorUniName);
+ fpb->codeAppendf("%s = vec4(result.rgb, diffuseColor.a);", args.fOutputColor);
+ }
+
+ static void GenKey(const GrProcessor& proc, const GrGLSLCaps&,
+ GrProcessorKeyBuilder* b) {
+// const LightingFP& lightingFP = proc.cast<LightingFP>();
+ // only one shader generated currently
+ b->add32(0x0);
+ }
+
+ protected:
+ void onSetData(const GrGLProgramDataManager& pdman, const GrProcessor& proc) override {
+ const LightingFP& lightingFP = proc.cast<LightingFP>();
+
+ const SkVector3& lightDir = lightingFP.lightDir();
+ if (lightDir != fLightDir) {
+ pdman.set3fv(fLightDirUni, 1, &lightDir.fX);
+ fLightDir = lightDir;
+ }
+
+ const SkColor3f& lightColor = lightingFP.lightColor();
+ if (lightColor != fLightColor) {
+ pdman.set3fv(fLightColorUni, 1, &lightColor.fX);
+ fLightColor = lightColor;
+ }
+
+ const SkColor3f& ambientColor = lightingFP.ambientColor();
+ if (ambientColor != fAmbientColor) {
+ pdman.set3fv(fAmbientColorUni, 1, &ambientColor.fX);
+ fAmbientColor = ambientColor;
+ }
+
+ const SkVector& invNormRotation = lightingFP.invNormRotation();
+ if (invNormRotation != fInvNormRotation) {
+ pdman.set2fv(fXformUni, 1, &invNormRotation.fX);
+ fInvNormRotation = invNormRotation;
+ }
+ }
+
+ private:
+ SkVector3 fLightDir;
+ GrGLProgramDataManager::UniformHandle fLightDirUni;
+
+ SkColor3f fLightColor;
+ GrGLProgramDataManager::UniformHandle fLightColorUni;
+
+ SkColor3f fAmbientColor;
+ GrGLProgramDataManager::UniformHandle fAmbientColorUni;
+
+ SkVector fInvNormRotation;
+ GrGLProgramDataManager::UniformHandle fXformUni;
+ };
+
+ void onGetGLProcessorKey(const GrGLSLCaps& caps, GrProcessorKeyBuilder* b) const override {
+ LightingGLFP::GenKey(*this, caps, b);
+ }
+
+ const char* name() const override { return "LightingFP"; }
+
+ void onComputeInvariantOutput(GrInvariantOutput* inout) const override {
+ inout->mulByUnknownFourComponents();
+ }
+
+ const SkVector3& lightDir() const { return fLightDir; }
+ const SkColor3f& lightColor() const { return fLightColor; }
+ const SkColor3f& ambientColor() const { return fAmbientColor; }
+ const SkVector& invNormRotation() const { return fInvNormRotation; }
+
+private:
+ GrGLFragmentProcessor* onCreateGLInstance() const override { return SkNEW(LightingGLFP); }
+
+ bool onIsEqual(const GrFragmentProcessor& proc) const override {
+ const LightingFP& lightingFP = proc.cast<LightingFP>();
+ return fDiffDeviceTransform == lightingFP.fDiffDeviceTransform &&
+ fNormDeviceTransform == lightingFP.fNormDeviceTransform &&
+ fDiffuseTextureAccess == lightingFP.fDiffuseTextureAccess &&
+ fNormalTextureAccess == lightingFP.fNormalTextureAccess &&
+ fLightDir == lightingFP.fLightDir &&
+ fLightColor == lightingFP.fLightColor &&
+ fAmbientColor == lightingFP.fAmbientColor &&
+ fInvNormRotation == lightingFP.fInvNormRotation;
+ }
+
+ GrCoordTransform fDiffDeviceTransform;
+ GrCoordTransform fNormDeviceTransform;
+ GrTextureAccess fDiffuseTextureAccess;
+ GrTextureAccess fNormalTextureAccess;
+ SkVector3 fLightDir;
+ SkColor3f fLightColor;
+ SkColor3f fAmbientColor;
+
+ SkVector fInvNormRotation;
+};
+
+////////////////////////////////////////////////////////////////////////////
+
+static bool make_mat(const SkBitmap& bm,
+ const SkMatrix& localMatrix1,
+ const SkMatrix* localMatrix2,
+ SkMatrix* result) {
+
+ result->setIDiv(bm.width(), bm.height());
+
+ SkMatrix lmInverse;
+ if (!localMatrix1.invert(&lmInverse)) {
+ return false;
+ }
+ if (localMatrix2) {
+ SkMatrix inv;
+ if (!localMatrix2->invert(&inv)) {
+ return false;
+ }
+ lmInverse.postConcat(inv);
+ }
+ result->preConcat(lmInverse);
+
+ return true;
+}
+
+bool SkLightingShaderImpl::asFragmentProcessor(GrContext* context, const SkPaint& paint,
+ const SkMatrix& viewM, const SkMatrix* localMatrix,
+ GrColor* color, GrProcessorDataManager* pdm,
+ GrFragmentProcessor** fp) const {
+ // we assume diffuse and normal maps have same width and height
+ // TODO: support different sizes
+ SkASSERT(fDiffuseMap.width() == fNormalMap.width() &&
+ fDiffuseMap.height() == fNormalMap.height());
+ SkMatrix diffM, normM;
+
+ if (!make_mat(fDiffuseMap, this->getLocalMatrix(), localMatrix, &diffM)) {
+ return false;
+ }
+
+ if (!make_mat(fNormalMap, fNormLocalMatrix, localMatrix, &normM)) {
+ return false;
+ }
+
+ bool doBicubic;
+ GrTextureParams::FilterMode diffFilterMode = GrSkFilterQualityToGrFilterMode(
+ SkTMin(paint.getFilterQuality(), kMedium_SkFilterQuality),
+ viewM,
+ this->getLocalMatrix(),
+ &doBicubic);
+ SkASSERT(!doBicubic);
+
+ GrTextureParams::FilterMode normFilterMode = GrSkFilterQualityToGrFilterMode(
+ SkTMin(paint.getFilterQuality(), kMedium_SkFilterQuality),
+ viewM,
+ fNormLocalMatrix,
+ &doBicubic);
+ SkASSERT(!doBicubic);
+
+ // TODO: support other tile modes
+ GrTextureParams diffParams(kClamp_TileMode, diffFilterMode);
+ SkAutoTUnref<GrTexture> diffuseTexture(GrRefCachedBitmapTexture(context,
+ fDiffuseMap, &diffParams));
+ if (!diffuseTexture) {
+ SkErrorInternals::SetError(kInternalError_SkError,
+ "Couldn't convert bitmap to texture.");
+ return false;
+ }
+
+ GrTextureParams normParams(kClamp_TileMode, normFilterMode);
+ SkAutoTUnref<GrTexture> normalTexture(GrRefCachedBitmapTexture(context,
+ fNormalMap, &normParams));
+ if (!normalTexture) {
+ SkErrorInternals::SetError(kInternalError_SkError,
+ "Couldn't convert bitmap to texture.");
+ return false;
+ }
+
+
+ *fp = SkNEW_ARGS(LightingFP, (pdm, diffuseTexture, normalTexture,
+ diffM, normM, diffParams, normParams, fLights,
+ fInvNormRotation));
+
+ *color = GrColorPackA4(paint.getAlpha());
+ return true;
+}
+#else
+
+bool SkLightingShaderImpl::asFragmentProcessor(GrContext* context, const SkPaint& paint,
+ const SkMatrix& viewM, const SkMatrix* localMatrix,
+ GrColor* color, GrProcessorDataManager*,
+ GrFragmentProcessor** fp) const {
+ SkDEBUGFAIL("Should not call in GPU-less build");
+ return false;
+}
+
+#endif
+
+////////////////////////////////////////////////////////////////////////////
+
+bool SkLightingShaderImpl::isOpaque() const {
+ return fDiffuseMap.isOpaque();
+}
+
+size_t SkLightingShaderImpl::contextSize() const {
+ return 2 * sizeof(SkBitmapProcState) + sizeof(LightingShaderContext);
+}
+
+SkLightingShaderImpl::LightingShaderContext::LightingShaderContext(const SkLightingShaderImpl& shader,
+ const ContextRec& rec,
+ SkBitmapProcState* diffuseState,
+ SkBitmapProcState* normalState)
+ : INHERITED(shader, rec)
+ , fDiffuseState(diffuseState)
+ , fNormalState(normalState)
+{
+ const SkPixmap& pixmap = fDiffuseState->fPixmap;
+ bool isOpaque = pixmap.isOpaque();
+
+ // update fFlags
+ uint32_t flags = 0;
+ if (isOpaque && (255 == this->getPaintAlpha())) {
+ flags |= kOpaqueAlpha_Flag;
+ }
+
+ fFlags = flags;
+}
+
+SkLightingShaderImpl::LightingShaderContext::~LightingShaderContext() {
+ // The bitmap proc states have been created outside of the context on memory that will be freed
+ // elsewhere. Call the destructors but leave the freeing of the memory to the caller.
+ fDiffuseState->~SkBitmapProcState();
+ fNormalState->~SkBitmapProcState();
+}
+
+static inline SkPMColor convert(SkColor3f color, U8CPU a) {
+ if (color.fX <= 0.0f) {
+ color.fX = 0.0f;
+ } else if (color.fX >= 255.0f) {
+ color.fX = 255.0f;
+ }
+
+ if (color.fY <= 0.0f) {
+ color.fY = 0.0f;
+ } else if (color.fY >= 255.0f) {
+ color.fY = 255.0f;
+ }
+
+ if (color.fZ <= 0.0f) {
+ color.fZ = 0.0f;
+ } else if (color.fZ >= 255.0f) {
+ color.fZ = 255.0f;
+ }
+
+ return SkPreMultiplyARGB(a, (int) color.fX, (int) color.fY, (int) color.fZ);
+}
+
+// larger is better (fewer times we have to loop), but we shouldn't
+// take up too much stack-space (each one here costs 16 bytes)
+#define TMP_COUNT 16
+
+void SkLightingShaderImpl::LightingShaderContext::shadeSpan(int x, int y,
+ SkPMColor result[], int count) {
+ const SkLightingShaderImpl& lightShader = static_cast<const SkLightingShaderImpl&>(fShader);
+
+ uint32_t tmpColor[TMP_COUNT], tmpNormal[TMP_COUNT];
+ SkPMColor tmpColor2[2*TMP_COUNT], tmpNormal2[2*TMP_COUNT];
+
+ SkBitmapProcState::MatrixProc diffMProc = fDiffuseState->getMatrixProc();
+ SkBitmapProcState::SampleProc32 diffSProc = fDiffuseState->getSampleProc32();
+
+ SkBitmapProcState::MatrixProc normalMProc = fNormalState->getMatrixProc();
+ SkBitmapProcState::SampleProc32 normalSProc = fNormalState->getSampleProc32();
+
+ int diffMax = fDiffuseState->maxCountForBufferSize(sizeof(tmpColor[0]) * TMP_COUNT);
+ int normMax = fNormalState->maxCountForBufferSize(sizeof(tmpNormal[0]) * TMP_COUNT);
+ int max = SkTMin(diffMax, normMax);
+
+ SkASSERT(fDiffuseState->fPixmap.addr());
+ SkASSERT(fNormalState->fPixmap.addr());
+
+ SkPoint3 norm, xformedNorm;
+
+ do {
+ int n = count;
+ if (n > max) {
+ n = max;
+ }
+
+ diffMProc(*fDiffuseState, tmpColor, n, x, y);
+ diffSProc(*fDiffuseState, tmpColor, n, tmpColor2);
+
+ normalMProc(*fNormalState, tmpNormal, n, x, y);
+ normalSProc(*fNormalState, tmpNormal, n, tmpNormal2);
+
+ for (int i = 0; i < n; ++i) {
+ SkASSERT(0xFF == SkColorGetA(tmpNormal2[i])); // opaque -> unpremul
+ norm.set(SkIntToScalar(SkGetPackedR32(tmpNormal2[i]))-127.0f,
+ SkIntToScalar(SkGetPackedG32(tmpNormal2[i]))-127.0f,
+ SkIntToScalar(SkGetPackedB32(tmpNormal2[i]))-127.0f);
+ norm.normalize();
+
+ xformedNorm.fX = lightShader.fInvNormRotation.fX * norm.fX +
+ lightShader.fInvNormRotation.fY * norm.fY;
+ xformedNorm.fY = lightShader.fInvNormRotation.fX * norm.fX -
+ lightShader.fInvNormRotation.fY * norm.fY;
+ xformedNorm.fZ = norm.fZ;
+
+ SkColor diffColor = SkUnPreMultiply::PMColorToColor(tmpColor2[i]);
+
+ SkColor3f accum = SkColor3f::Make(0.0f, 0.0f, 0.0f);
+ // This is all done in linear unpremul color space (each component 0..255.0f though)
+ for (int l = 0; l < lightShader.fLights->numLights(); ++l) {
+ const SkLight& light = lightShader.fLights->light(l);
+
+ if (SkLight::kAmbient_LightType == light.type()) {
+ accum += light.color().makeScale(255.0f);
+ } else {
+ SkScalar NdotL = xformedNorm.dot(light.dir());
+ if (NdotL < 0.0f) {
+ NdotL = 0.0f;
+ }
+
+ accum.fX += light.color().fX * SkColorGetR(diffColor) * NdotL;
+ accum.fY += light.color().fY * SkColorGetG(diffColor) * NdotL;
+ accum.fZ += light.color().fZ * SkColorGetB(diffColor) * NdotL;
+ }
+ }
+
+ result[i] = convert(accum, SkColorGetA(diffColor));
+ }
+
+ result += n;
+ x += n;
+ count -= n;
+ } while (count > 0);
+}
+
+////////////////////////////////////////////////////////////////////////////
+
+#ifndef SK_IGNORE_TO_STRING
+void SkLightingShaderImpl::toString(SkString* str) const {
+ str->appendf("LightingShader: ()");
+}
+#endif
+
+SkFlattenable* SkLightingShaderImpl::CreateProc(SkReadBuffer& buf) {
+ SkMatrix diffLocalM;
+ bool hasDiffLocalM = buf.readBool();
+ if (hasDiffLocalM) {
+ buf.readMatrix(&diffLocalM);
+ } else {
+ diffLocalM.reset();
+ }
+
+ SkMatrix normLocalM;
+ bool hasNormLocalM = buf.readBool();
+ if (hasNormLocalM) {
+ buf.readMatrix(&normLocalM);
+ } else {
+ normLocalM.reset();
+ }
+
+ SkBitmap diffuse;
+ if (!buf.readBitmap(&diffuse)) {
+ return NULL;
+ }
+ diffuse.setImmutable();
+
+ SkBitmap normal;
+ if (!buf.readBitmap(&normal)) {
+ return NULL;
+ }
+ normal.setImmutable();
+
+ int numLights = buf.readInt();
+
+ SkLightingShader::Lights::Builder builder;
+
+ for (int l = 0; l < numLights; ++l) {
+ bool isAmbient = buf.readBool();
+
+ SkColor3f color;
+ if (!buf.readScalarArray(&color.fX, 3)) {
+ return NULL;
+ }
+
+ if (isAmbient) {
+ builder.add(SkLight(color));
+ } else {
+ SkVector3 dir;
+ if (!buf.readScalarArray(&dir.fX, 3)) {
+ return NULL;
+ }
+ builder.add(SkLight(color, dir));
+ }
+ }
+
+ SkAutoTUnref<const SkLightingShader::Lights> lights(builder.finish());
+
+ return SkNEW_ARGS(SkLightingShaderImpl, (diffuse, normal, lights,
+ SkVector::Make(1.0f, 0.0f),
+ &diffLocalM, &normLocalM));
+}
+
+void SkLightingShaderImpl::flatten(SkWriteBuffer& buf) const {
+ this->INHERITED::flatten(buf);
+
+ bool hasNormLocalM = !fNormLocalMatrix.isIdentity();
+ buf.writeBool(hasNormLocalM);
+ if (hasNormLocalM) {
+ buf.writeMatrix(fNormLocalMatrix);
+ }
+
+ buf.writeBitmap(fDiffuseMap);
+ buf.writeBitmap(fNormalMap);
+
+ buf.writeInt(fLights->numLights());
+ for (int l = 0; l < fLights->numLights(); ++l) {
+ const SkLight& light = fLights->light(l);
+
+ bool isAmbient = SkLight::kAmbient_LightType == light.type();
+
+ buf.writeBool(isAmbient);
+ buf.writeScalarArray(&light.color().fX, 3);
+ if (!isAmbient) {
+ buf.writeScalarArray(&light.dir().fX, 3);
+ }
+ }
+}
+
+bool SkLightingShaderImpl::computeNormTotalInverse(const ContextRec& rec,
+ SkMatrix* normTotalInverse) const {
+ SkMatrix total;
+ total.setConcat(*rec.fMatrix, fNormLocalMatrix);
+
+ const SkMatrix* m = &total;
+ if (rec.fLocalMatrix) {
+ total.setConcat(*m, *rec.fLocalMatrix);
+ m = &total;
+ }
+ return m->invert(normTotalInverse);
+}
+
+SkShader::Context* SkLightingShaderImpl::onCreateContext(const ContextRec& rec,
+ void* storage) const {
+
+ SkMatrix diffTotalInv;
+ // computeTotalInverse was called in SkShader::createContext so we know it will succeed
+ SkAssertResult(this->computeTotalInverse(rec, &diffTotalInv));
+
+ SkMatrix normTotalInv;
+ if (!this->computeNormTotalInverse(rec, &normTotalInv)) {
+ return NULL;
+ }
+
+ void* diffuseStateStorage = (char*)storage + sizeof(LightingShaderContext);
+ SkBitmapProcState* diffuseState = SkNEW_PLACEMENT(diffuseStateStorage, SkBitmapProcState);
+ SkASSERT(diffuseState);
+
+ diffuseState->fTileModeX = SkShader::kClamp_TileMode;
+ diffuseState->fTileModeY = SkShader::kClamp_TileMode;
+ diffuseState->fOrigBitmap = fDiffuseMap;
+ if (!diffuseState->chooseProcs(diffTotalInv, *rec.fPaint)) {
+ diffuseState->~SkBitmapProcState();
+ return NULL;
+ }
+
+ void* normalStateStorage = (char*)storage + sizeof(LightingShaderContext) + sizeof(SkBitmapProcState);
+ SkBitmapProcState* normalState = SkNEW_PLACEMENT(normalStateStorage, SkBitmapProcState);
+ SkASSERT(normalState);
+
+ normalState->fTileModeX = SkShader::kClamp_TileMode;
+ normalState->fTileModeY = SkShader::kClamp_TileMode;
+ normalState->fOrigBitmap = fNormalMap;
+ if (!normalState->chooseProcs(normTotalInv, *rec.fPaint)) {
+ diffuseState->~SkBitmapProcState();
+ normalState->~SkBitmapProcState();
+ return NULL;
+ }
+
+ return SkNEW_PLACEMENT_ARGS(storage, LightingShaderContext, (*this, rec,
+ diffuseState, normalState));
+}
+
+///////////////////////////////////////////////////////////////////////////////
+
+static bool bitmap_is_too_big(const SkBitmap& bm) {
+ // SkBitmapProcShader stores bitmap coordinates in a 16bit buffer, as it
+ // communicates between its matrix-proc and its sampler-proc. Until we can
+ // widen that, we have to reject bitmaps that are larger.
+ //
+ static const int kMaxSize = 65535;
+
+ return bm.width() > kMaxSize || bm.height() > kMaxSize;
+}
+
+SkShader* SkLightingShader::Create(const SkBitmap& diffuse, const SkBitmap& normal,
+ const Lights* lights,
+ const SkVector& invNormRotation,
+ const SkMatrix* diffLocalM, const SkMatrix* normLocalM) {
+ if (diffuse.isNull() || bitmap_is_too_big(diffuse) ||
+ normal.isNull() || bitmap_is_too_big(normal) ||
+ diffuse.width() != normal.width() ||
+ diffuse.height() != normal.height()) {
+ return nullptr;
+ }
+
+ SkASSERT(SkScalarNearlyEqual(invNormRotation.lengthSqd(), SK_Scalar1));
+
+ return SkNEW_ARGS(SkLightingShaderImpl, (diffuse, normal, lights,
+ invNormRotation, diffLocalM, normLocalM));
+}
+
+///////////////////////////////////////////////////////////////////////////////
+
+SK_DEFINE_FLATTENABLE_REGISTRAR_GROUP_START(SkLightingShader)
+ SK_DEFINE_FLATTENABLE_REGISTRAR_ENTRY(SkLightingShaderImpl)
+SK_DEFINE_FLATTENABLE_REGISTRAR_GROUP_END
+
+///////////////////////////////////////////////////////////////////////////////
diff --git a/src/core/SkLightingShader.h b/src/core/SkLightingShader.h
new file mode 100644
index 0000000000..499e358238
--- /dev/null
+++ b/src/core/SkLightingShader.h
@@ -0,0 +1,101 @@
+
+/*
+ * Copyright 2015 Google Inc.
+ *
+ * Use of this source code is governed by a BSD-style license that can be
+ * found in the LICENSE file.
+ */
+
+
+#ifndef SkLightingShader_DEFINED
+#define SkLightingShader_DEFINED
+
+#include "SkFlattenable.h"
+#include "SkLight.h"
+#include "SkShader.h"
+#include "SkTDArray.h"
+
+class SkBitmap;
+class SkMatrix;
+
+class SK_API SkLightingShader {
+public:
+ class Lights : public SkRefCnt {
+ public:
+ class Builder {
+ public:
+ Builder(const SkLight lights[], int numLights)
+ : fLights(SkNEW_ARGS(Lights, (lights, numLights))) {
+ }
+
+ Builder() : fLights(SkNEW(Lights)) { }
+
+ // TODO: limit the number of lights here or just ignore those
+ // above some maximum?
+ void add(const SkLight& light) {
+ if (fLights) {
+ *fLights->fLights.push() = light;
+ }
+ }
+
+ const Lights* finish() {
+ return fLights.detach();
+ }
+
+ private:
+ SkAutoTUnref<Lights> fLights;
+ };
+
+ int numLights() const {
+ return fLights.count();
+ }
+
+ const SkLight& light(int index) const {
+ return fLights[index];
+ }
+
+ private:
+ Lights() {}
+ Lights(const SkLight lights[], int numLights) : fLights(lights, numLights) {}
+
+ SkTDArray<SkLight> fLights;
+
+ typedef SkRefCnt INHERITED;
+ };
+
+ /** Returns a shader that lights the diffuse and normal maps with a single light.
+
+ It returns a shader with a reference count of 1.
+ The caller should decrement the shader's reference count when done with the shader.
+ It is an error for count to be < 2.
+ @param diffuse the diffuse bitmap
+ @param normal the normal map
+ @param light the light applied to the normal map
+ @param ambient the linear (unpremul) ambient light color. Range is 0..1/channel.
+ @param localMatrix the matrix mapping the textures to the dest rect
+
+ NULL will be returned if:
+ either 'diffuse' or 'normal' are empty
+ either 'diffuse' or 'normal' are too big (> 65535 on a side)
+ 'diffuse' and 'normal' aren't the same size
+
+ The lighting equation is currently:
+ result = LightColor * DiffuseColor * (Normal * LightDir) + AmbientColor
+
+ The normal map is currently assumed to be an 8888 image where the normal at a texel
+ is retrieved by:
+ N.x = R-127;
+ N.y = G-127;
+ N.z = B-127;
+ N.normalize();
+ The +Z axis is thus encoded in RGB as (127, 127, 255) while the -Z axis is
+ (127, 127, 0).
+ */
+ static SkShader* Create(const SkBitmap& diffuse, const SkBitmap& normal,
+ const Lights* lights, const SkVector& invNormRotation,
+ const SkMatrix* diffLocalMatrix, const SkMatrix* normLocalMatrix);
+
+ SK_DECLARE_FLATTENABLE_REGISTRAR_GROUP()
+};
+
+#endif
diff --git a/src/core/SkPoint3.cpp b/src/core/SkPoint3.cpp
new file mode 100644
index 0000000000..3b5586b067
--- /dev/null
+++ b/src/core/SkPoint3.cpp
@@ -0,0 +1,80 @@
+/*
+ * Copyright 2015 Google Inc.
+ *
+ * Use of this source code is governed by a BSD-style license that can be
+ * found in the LICENSE file.
+ */
+
+#include "SkPoint3.h"
+
+// Returns the square of the Euclidian distance to (x,y,z).
+static inline float get_length_squared(float x, float y, float z) {
+ return x * x + y * y + z * z;
+}
+
+// Calculates the square of the Euclidian distance to (x,y,z) and stores it in
+// *lengthSquared. Returns true if the distance is judged to be "nearly zero".
+//
+// This logic is encapsulated in a helper method to make it explicit that we
+// always perform this check in the same manner, to avoid inconsistencies
+// (see http://code.google.com/p/skia/issues/detail?id=560 ).
+static inline bool is_length_nearly_zero(float x, float y, float z, float *lengthSquared) {
+ *lengthSquared = get_length_squared(x, y, z);
+ return *lengthSquared <= (SK_ScalarNearlyZero * SK_ScalarNearlyZero);
+}
+
+SkScalar SkPoint3::Length(SkScalar x, SkScalar y, SkScalar z) {
+ float magSq = get_length_squared(x, y, z);
+ if (SkScalarIsFinite(magSq)) {
+ return sk_float_sqrt(magSq);
+ } else {
+ double xx = x;
+ double yy = y;
+ double zz = z;
+ return (float)sqrt(xx * xx + yy * yy + zz * zz);
+ }
+}
+
+/*
+ * We have to worry about 2 tricky conditions:
+ * 1. underflow of magSq (compared against nearlyzero^2)
+ * 2. overflow of magSq (compared w/ isfinite)
+ *
+ * If we underflow, we return false. If we overflow, we compute again using
+ * doubles, which is much slower (3x in a desktop test) but will not overflow.
+ */
+bool SkPoint3::normalize() {
+ float magSq;
+ if (is_length_nearly_zero(fX, fY, fZ, &magSq)) {
+ this->set(0, 0, 0);
+ return false;
+ }
+
+ float scale;
+ if (SkScalarIsFinite(magSq)) {
+ scale = 1.0f / sk_float_sqrt(magSq);
+ } else {
+ // our magSq step overflowed to infinity, so use doubles instead.
+ // much slower, but needed when x, y or z is very large, otherwise we
+ // divide by inf. and return (0,0,0) vector.
+ double xx = fX;
+ double yy = fY;
+ double zz = fZ;
+#ifdef SK_CPU_FLUSH_TO_ZERO
+ // The iOS ARM processor discards small denormalized numbers to go faster.
+ // Casting this to a float would cause the scale to go to zero. Keeping it
+ // as a double for the multiply keeps the scale non-zero.
+ double dscale = 1.0f / sqrt(xx * xx + yy * yy + zz * zz);
+ fX = x * dscale;
+ fY = y * dscale;
+ fZ = z * dscale;
+ return true;
+#else
+ scale = (float)(1.0f / sqrt(xx * xx + yy * yy + zz * zz));
+#endif
+ }
+ fX *= scale;
+ fY *= scale;
+ fZ *= scale;
+ return true;
+}
diff --git a/src/core/SkPoint3.h b/src/core/SkPoint3.h
new file mode 100644
index 0000000000..af24a8df58
--- /dev/null
+++ b/src/core/SkPoint3.h
@@ -0,0 +1,124 @@
+/*
+ * Copyright 2015 Google Inc.
+ *
+ * Use of this source code is governed by a BSD-style license that can be
+ * found in the LICENSE file.
+ */
+
+#ifndef SkPoint3_DEFINED
+#define SkPoint3_DEFINED
+
+#include "SkScalar.h"
+
+struct SK_API SkPoint3 {
+ SkScalar fX, fY, fZ;
+
+ static SkPoint3 Make(SkScalar x, SkScalar y, SkScalar z) {
+ SkPoint3 pt;
+ pt.set(x, y, z);
+ return pt;
+ }
+
+ SkScalar x() const { return fX; }
+ SkScalar y() const { return fY; }
+ SkScalar z() const { return fZ; }
+
+ void set(SkScalar x, SkScalar y, SkScalar z) { fX = x; fY = y; fZ = z; }
+
+ friend bool operator==(const SkPoint3& a, const SkPoint3& b) {
+ return a.fX == b.fX && a.fY == b.fY && a.fZ == b.fZ;
+ }
+
+ friend bool operator!=(const SkPoint3& a, const SkPoint3& b) {
+ return !(a == b);
+ }
+
+ /** Returns the Euclidian distance from (0,0,0) to (x,y,z)
+ */
+ static SkScalar Length(SkScalar x, SkScalar y, SkScalar z);
+
+ /** Return the Euclidian distance from (0,0,0) to the point
+ */
+ SkScalar length() const { return SkPoint3::Length(fX, fY, fZ); }
+
+ /** Set the point (vector) to be unit-length in the same direction as it
+ already points. If the point has a degenerate length (i.e., nearly 0)
+ then set it to (0,0,0) and return false; otherwise return true.
+ */
+ bool normalize();
+
+ /** Return a new point whose X, Y and Z coordinates are scaled.
+ */
+ SkPoint3 makeScale(SkScalar scale) const {
+ SkPoint3 p;
+ p.set(scale * fX, scale * fY, scale * fZ);
+ return p;
+ }
+
+ /** Scale the point's coordinates by scale.
+ */
+ void scale(SkScalar value) {
+ fX *= value;
+ fY *= value;
+ fZ *= value;
+ }
+
+ /** Return a new point whose X, Y and Z coordinates are the negative of the
+ original point's
+ */
+ SkPoint3 operator-() const {
+ SkPoint3 neg;
+ neg.fX = -fX;
+ neg.fY = -fY;
+ neg.fZ = -fZ;
+ return neg;
+ }
+
+ /** Returns a new point whose coordinates are the difference between
+ a and b (i.e., a - b)
+ */
+ friend SkPoint3 operator-(const SkPoint3& a, const SkPoint3& b) {
+ SkPoint3 v;
+ v.set(a.fX - b.fX, a.fY - b.fY, a.fZ - b.fZ);
+ return v;
+ }
+
+ /** Returns a new point whose coordinates are the sum of a and b (a + b)
+ */
+ friend SkPoint3 operator+(const SkPoint3& a, const SkPoint3& b) {
+ SkPoint3 v;
+ v.set(a.fX + b.fX, a.fY + b.fY, a.fZ + b.fZ);
+ return v;
+ }
+
+ /** Add v's coordinates to the point's
+ */
+ void operator+=(const SkPoint3& v) {
+ fX += v.fX;
+ fY += v.fY;
+ fZ += v.fZ;
+ }
+
+ /** Subtract v's coordinates from the point's
+ */
+ void operator-=(const SkPoint3& v) {
+ fX -= v.fX;
+ fY -= v.fY;
+ fZ -= v.fZ;
+ }
+
+ /** Returns the dot product of a and b, treating them as 3D vectors
+ */
+ static SkScalar DotProduct(const SkPoint3& a, const SkPoint3& b) {
+ return a.fX * b.fX + a.fY * b.fY + a.fZ * b.fZ;
+ }
+
+ SkScalar dot(const SkPoint3& vec) const {
+ return DotProduct(*this, vec);
+ }
+};
+
+typedef SkPoint3 SkVector3;
+typedef SkPoint3 SkColor3f;
+
+#endif