Merge pull request #8162 from super626/light

3D Light
This commit is contained in:
minggo 2014-09-30 11:13:59 +08:00
commit d1e41c771b
40 changed files with 1895 additions and 60 deletions

View File

@ -1279,6 +1279,10 @@
3E6176771960F89B00DE83F5 /* CCEventListenerController.h in Headers */ = {isa = PBXBuildFile; fileRef = 3E6176641960F89B00DE83F5 /* CCEventListenerController.h */; };
3E6176781960F89B00DE83F5 /* CCGameController.h in Headers */ = {isa = PBXBuildFile; fileRef = 3E6176651960F89B00DE83F5 /* CCGameController.h */; };
3E61781D1966A5A300DE83F5 /* CCController.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 3E61781C1966A5A300DE83F5 /* CCController.cpp */; };
3EA1072F19D7F37700CAB794 /* CCLight.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 3EA1072D19D7F37700CAB794 /* CCLight.cpp */; };
3EA1073019D7F37700CAB794 /* CCLight.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 3EA1072D19D7F37700CAB794 /* CCLight.cpp */; };
3EA1073119D7F37700CAB794 /* CCLight.h in Headers */ = {isa = PBXBuildFile; fileRef = 3EA1072E19D7F37700CAB794 /* CCLight.h */; };
3EA1073219D7F37700CAB794 /* CCLight.h in Headers */ = {isa = PBXBuildFile; fileRef = 3EA1072E19D7F37700CAB794 /* CCLight.h */; };
3EA3EDBC1991CDFA00645534 /* CCCamera.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 3EA3EDBA1991CDFA00645534 /* CCCamera.cpp */; };
3EA3EDBD1991CDFA00645534 /* CCCamera.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 3EA3EDBA1991CDFA00645534 /* CCCamera.cpp */; };
3EA3EDBE1991CDFA00645534 /* CCCamera.h in Headers */ = {isa = PBXBuildFile; fileRef = 3EA3EDBB1991CDFA00645534 /* CCCamera.h */; };
@ -2310,6 +2314,8 @@
3E61781C1966A5A300DE83F5 /* CCController.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = CCController.cpp; path = ../base/CCController.cpp; sourceTree = "<group>"; };
3EA0FB69191C841D00B170C8 /* UIVideoPlayer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = UIVideoPlayer.h; sourceTree = "<group>"; };
3EA0FB6A191C841D00B170C8 /* UIVideoPlayer-ios.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = "UIVideoPlayer-ios.mm"; sourceTree = "<group>"; };
3EA1072D19D7F37700CAB794 /* CCLight.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = CCLight.cpp; path = ../base/CCLight.cpp; sourceTree = "<group>"; };
3EA1072E19D7F37700CAB794 /* CCLight.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = CCLight.h; path = ../base/CCLight.h; sourceTree = "<group>"; };
3EA3EDBA1991CDFA00645534 /* CCCamera.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = CCCamera.cpp; path = ../base/CCCamera.cpp; sourceTree = "<group>"; };
3EA3EDBB1991CDFA00645534 /* CCCamera.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = CCCamera.h; path = ../base/CCCamera.h; sourceTree = "<group>"; };
464AD6E3197EBB1400E502D8 /* pvr.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = pvr.cpp; path = ../base/pvr.cpp; sourceTree = "<group>"; };
@ -2796,6 +2802,9 @@
B3AF019F1842FBA400A98B85 /* b2MotorJoint.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2MotorJoint.h; sourceTree = "<group>"; };
B60C5BD219AC68B10056FBDE /* CCBillBoard.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = CCBillBoard.cpp; sourceTree = "<group>"; };
B60C5BD319AC68B10056FBDE /* CCBillBoard.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCBillBoard.h; sourceTree = "<group>"; };
B67C624319D4186F00F11FC6 /* ccShader_3D_ColorNormal.frag */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.glsl; path = ccShader_3D_ColorNormal.frag; sourceTree = "<group>"; };
B67C624419D4186F00F11FC6 /* ccShader_3D_ColorNormalTex.frag */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.glsl; path = ccShader_3D_ColorNormalTex.frag; sourceTree = "<group>"; };
B67C624519D4186F00F11FC6 /* ccShader_3D_PositionNormalTex.vert */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.glsl; path = ccShader_3D_PositionNormalTex.vert; sourceTree = "<group>"; };
ED9C6A9218599AD8000A5232 /* CCNodeGrid.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; lineEnding = 0; path = CCNodeGrid.cpp; sourceTree = "<group>"; xcLanguageSpecificationIdentifier = xcode.lang.cpp; };
ED9C6A9318599AD8000A5232 /* CCNodeGrid.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCNodeGrid.h; sourceTree = "<group>"; };
/* End PBXFileReference section */
@ -3000,6 +3009,8 @@
1A5700A2180BC5E60088DEC7 /* base */ = {
isa = PBXGroup;
children = (
3EA1072D19D7F37700CAB794 /* CCLight.cpp */,
3EA1072E19D7F37700CAB794 /* CCLight.h */,
299CF1F919A434BC00C378C1 /* ccRandom.cpp */,
299CF1FA19A434BC00C378C1 /* ccRandom.h */,
3EA3EDBA1991CDFA00645534 /* CCCamera.cpp */,
@ -4473,6 +4484,9 @@
5034CA5D191D591900CE6051 /* shaders */ = {
isa = PBXGroup;
children = (
B67C624319D4186F00F11FC6 /* ccShader_3D_ColorNormal.frag */,
B67C624419D4186F00F11FC6 /* ccShader_3D_ColorNormalTex.frag */,
B67C624519D4186F00F11FC6 /* ccShader_3D_PositionNormalTex.vert */,
B29594AF1926D5D9003EEF37 /* ccShader_3D_Color.frag */,
B29594B01926D5D9003EEF37 /* ccShader_3D_ColorTex.frag */,
B29594B11926D5D9003EEF37 /* ccShader_3D_PositionTex.vert */,
@ -4803,6 +4817,7 @@
15AE1A5319AAD40300C27E9E /* b2Draw.h in Headers */,
5034CA39191D591100CE6051 /* ccShader_PositionColorLengthTexture.frag in Headers */,
292DB14B19B4574100A80320 /* UIEditBoxImpl-mac.h in Headers */,
3EA1073119D7F37700CAB794 /* CCLight.h in Headers */,
50ABBE891925AB6F00A911A9 /* CCMap.h in Headers */,
50ABBE8D1925AB6F00A911A9 /* CCNS.h in Headers */,
50ABBEA51925AB6F00A911A9 /* CCScriptSupport.h in Headers */,
@ -5721,6 +5736,7 @@
1A01C6A718F58F7500EFE3A6 /* CCNotificationCenter.h in Headers */,
50ABBEDA1925AB6F00A911A9 /* ZipUtils.h in Headers */,
50ABBDC01925AB4100A911A9 /* CCTextureCache.h in Headers */,
3EA1073219D7F37700CAB794 /* CCLight.h in Headers */,
B276EF641988D1D500CD400F /* CCVertexIndexBuffer.h in Headers */,
15AE1A0619AAD3A700C27E9E /* Bone.h in Headers */,
ED9C6A9718599AD8000A5232 /* CCNodeGrid.h in Headers */,
@ -6159,6 +6175,7 @@
15AE199819AAD39600C27E9E /* LoadingBarReader.cpp in Sources */,
503DD8F71926B0DB00CD74DD /* CCIMEDispatcher.cpp in Sources */,
50ABBE751925AB6F00A911A9 /* CCEventListenerTouch.cpp in Sources */,
3EA1072F19D7F37700CAB794 /* CCLight.cpp in Sources */,
15AE18F019AAD35000C27E9E /* CCArmatureAnimation.cpp in Sources */,
50ABBE511925AB6F00A911A9 /* CCEventDispatcher.cpp in Sources */,
50ABC0051926664800A911A9 /* CCThread-apple.mm in Sources */,
@ -6627,6 +6644,7 @@
50ABBE201925AB6F00A911A9 /* atitc.cpp in Sources */,
50CB248019D9C5A100687767 /* AudioPlayer.mm in Sources */,
50ABBE9A1925AB6F00A911A9 /* CCRef.cpp in Sources */,
3EA1073019D7F37700CAB794 /* CCLight.cpp in Sources */,
15AE18BF19AAD33D00C27E9E /* CCLabelTTFLoader.cpp in Sources */,
15AE1B9519AADA9A00C27E9E /* CocosGUI.cpp in Sources */,
15AE1A0D19AAD3A700C27E9E /* extension.cpp in Sources */,

View File

@ -945,6 +945,8 @@
B2507B6C192589AF00FA4972 /* Shaders3D in Resources */ = {isa = PBXBuildFile; fileRef = B2507B6A192589AF00FA4972 /* Shaders3D */; };
B609E67319C18DAD003D0074 /* BillBoardTest.cpp in Sources */ = {isa = PBXBuildFile; fileRef = B609E67119C18DAD003D0074 /* BillBoardTest.cpp */; };
B609E67419C18DAD003D0074 /* BillBoardTest.cpp in Sources */ = {isa = PBXBuildFile; fileRef = B609E67119C18DAD003D0074 /* BillBoardTest.cpp */; };
B6C039D919C95D83007207DC /* LightTest.cpp in Sources */ = {isa = PBXBuildFile; fileRef = B6C039D719C95D83007207DC /* LightTest.cpp */; };
B6C039DA19C95D83007207DC /* LightTest.cpp in Sources */ = {isa = PBXBuildFile; fileRef = B6C039D719C95D83007207DC /* LightTest.cpp */; };
C04F935A1941B05400E9FEAB /* TileMapTest2.cpp in Sources */ = {isa = PBXBuildFile; fileRef = C04F93581941B05400E9FEAB /* TileMapTest2.cpp */; };
C04F935B1941B05400E9FEAB /* TileMapTest2.cpp in Sources */ = {isa = PBXBuildFile; fileRef = C04F93581941B05400E9FEAB /* TileMapTest2.cpp */; };
C08689C118D370C90093E810 /* background.caf in Resources */ = {isa = PBXBuildFile; fileRef = C08689C018D370C90093E810 /* background.caf */; };
@ -2970,6 +2972,8 @@
B2507B6A192589AF00FA4972 /* Shaders3D */ = {isa = PBXFileReference; lastKnownFileType = folder; name = Shaders3D; path = "../tests/cpp-tests/Resources/Shaders3D"; sourceTree = "<group>"; };
B609E67119C18DAD003D0074 /* BillBoardTest.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = BillBoardTest.cpp; path = BillBoardTest/BillBoardTest.cpp; sourceTree = "<group>"; };
B609E67219C18DAD003D0074 /* BillBoardTest.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = BillBoardTest.h; path = BillBoardTest/BillBoardTest.h; sourceTree = "<group>"; };
B6C039D719C95D83007207DC /* LightTest.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = LightTest.cpp; path = LightTest/LightTest.cpp; sourceTree = "<group>"; };
B6C039D819C95D83007207DC /* LightTest.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = LightTest.h; path = LightTest/LightTest.h; sourceTree = "<group>"; };
C04F93581941B05400E9FEAB /* TileMapTest2.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = TileMapTest2.cpp; sourceTree = "<group>"; };
C04F93591941B05400E9FEAB /* TileMapTest2.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = TileMapTest2.h; sourceTree = "<group>"; };
C08689C018D370C90093E810 /* background.caf */ = {isa = PBXFileReference; lastKnownFileType = file; name = background.caf; path = "../tests/cpp-tests/Resources/background.caf"; sourceTree = "<group>"; };
@ -5444,6 +5448,7 @@
1AC3592418CECF0A00F37B72 /* Classes */ = {
isa = PBXGroup;
children = (
B6C039D619C95D28007207DC /* LightTest */,
B609E67019C18D90003D0074 /* BillBoardTest */,
3E2BDACD19BEA3410055CDCD /* NewAudioEngineTest */,
3E9E75CB199324A8005B7047 /* Camera3DTest */,
@ -7179,6 +7184,15 @@
name = BillBoardTest;
sourceTree = "<group>";
};
B6C039D619C95D28007207DC /* LightTest */ = {
isa = PBXGroup;
children = (
B6C039D719C95D83007207DC /* LightTest.cpp */,
B6C039D819C95D83007207DC /* LightTest.h */,
);
name = LightTest;
sourceTree = "<group>";
};
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
@ -8083,6 +8097,7 @@
1AC35C4F18CECF0C00F37B72 /* SpriteTest.cpp in Sources */,
29080D9D191B595E0066F8DF /* CustomParticleWidgetReader.cpp in Sources */,
1AC35C0318CECF0C00F37B72 /* FileUtilsTest.cpp in Sources */,
B6C039D919C95D83007207DC /* LightTest.cpp in Sources */,
1AC35B5B18CECF0C00F37B72 /* CurlTest.cpp in Sources */,
29080DD5191B595E0066F8DF /* UITextAtlasTest_Editor.cpp in Sources */,
1AC35BFF18CECF0C00F37B72 /* CustomTableViewCell.cpp in Sources */,
@ -8388,6 +8403,7 @@
1AC35BFC18CECF0C00F37B72 /* NotificationCenterTest.cpp in Sources */,
29FBBBFF196A9ECD00E65826 /* CocostudioParserJsonTest.cpp in Sources */,
1AC35C3618CECF0C00F37B72 /* PerformanceSpriteTest.cpp in Sources */,
B6C039DA19C95D83007207DC /* LightTest.cpp in Sources */,
1AC35C3C18CECF0C00F37B72 /* PerformanceTouchesTest.cpp in Sources */,
29080DA2191B595E0066F8DF /* GUIEditorTest.cpp in Sources */,
29080D94191B595E0066F8DF /* CustomImageTest.cpp in Sources */,

View File

@ -34,6 +34,7 @@ THE SOFTWARE.
NS_CC_BEGIN
class Camera;
class BaseLight;
class Renderer;
class EventListenerCustom;
class EventCustom;
@ -73,6 +74,8 @@ public:
/** get all cameras */
const std::vector<Camera*>& getCameras() const { return _cameras; }
const std::vector<BaseLight*>& getLights() const { return _lights; }
/** render the scene */
void render(Renderer* renderer);
@ -90,12 +93,15 @@ protected:
friend class ProtectedNode;
friend class SpriteBatchNode;
friend class Camera;
friend class BaseLight;
friend class Renderer;
std::vector<Camera*> _cameras; //weak ref to Camera
Camera* _defaultCamera; //weak ref, default camera created by scene, _cameras[0], Caution that the default camera can not be added to _cameras before onEnter is called
EventListenerCustom* _event;
std::vector<BaseLight *> _lights;
private:
CC_DISALLOW_COPY_AND_ASSIGN(Scene);

View File

@ -246,6 +246,7 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\chipmunk\prebuilt\win32\release-lib\*.*
<ClCompile Include="..\base\CCEventTouch.cpp" />
<ClCompile Include="..\base\ccFPSImages.c" />
<ClCompile Include="..\base\CCIMEDispatcher.cpp" />
<ClCompile Include="..\base\CCLight.cpp" />
<ClCompile Include="..\base\CCNS.cpp" />
<ClCompile Include="..\base\CCProfiling.cpp" />
<ClCompile Include="..\base\ccRandom.cpp" />
@ -589,6 +590,7 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\chipmunk\prebuilt\win32\release-lib\*.*
<ClInclude Include="..\base\ccFPSImages.h" />
<ClInclude Include="..\base\CCIMEDelegate.h" />
<ClInclude Include="..\base\CCIMEDispatcher.h" />
<ClInclude Include="..\base\CCLight.h" />
<ClInclude Include="..\base\ccMacros.h" />
<ClInclude Include="..\base\CCMap.h" />
<ClInclude Include="..\base\CCNS.h" />

View File

@ -1171,6 +1171,9 @@
<ClCompile Include="..\ui\UIWebView.cpp">
<Filter>ui\UIWidgets</Filter>
</ClCompile>
<ClCompile Include="..\base\CCLight.cpp">
<Filter>base</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="..\physics\CCPhysicsBody.h">
@ -2305,6 +2308,9 @@
<ClInclude Include="..\ui\UIWebView.h">
<Filter>ui\UIWidgets</Filter>
</ClInclude>
<ClInclude Include="..\base\CCLight.h">
<Filter>base</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<None Include="..\math\Mat4.inl">

View File

@ -31,8 +31,9 @@
#include "3d/CCMesh.h"
#include "base/CCDirector.h"
#include "platform/CCPlatformMacros.h"
#include "base/CCLight.h"
#include "base/ccMacros.h"
#include "platform/CCPlatformMacros.h"
#include "platform/CCFileUtils.h"
#include "renderer/CCTextureCache.h"
#include "renderer/CCRenderer.h"
@ -166,6 +167,8 @@ Sprite3D::Sprite3D()
: _skeleton(nullptr)
, _blend(BlendFunc::ALPHA_NON_PREMULTIPLIED)
, _aabbDirty(true)
, _lightMask(-1)
, _shaderUsingLight(false)
{
}
@ -299,25 +302,46 @@ void Sprite3D::createAttachSprite3DNode(NodeData* nodedata,const MaterialDatas&
}
void Sprite3D::genGLProgramState()
{
const auto& lights = Director::getInstance()->getRunningScene()->getLights();
_shaderUsingLight = false;
for (const auto light : lights) {
_shaderUsingLight = ((unsigned int)light->getLightFlag() & _lightMask) > 0;
if (_shaderUsingLight)
break;
}
std::unordered_map<const MeshVertexData*, GLProgramState*> glProgramestates;
for(auto& mesh : _meshVertexDatas)
{
bool textured = mesh->hasVertexAttrib(GLProgram::VERTEX_ATTRIB_TEX_COORD);
bool hasSkin = mesh->hasVertexAttrib(GLProgram::VERTEX_ATTRIB_BLEND_INDEX)
&& mesh->hasVertexAttrib(GLProgram::VERTEX_ATTRIB_BLEND_WEIGHT);
bool hasNormal = mesh->hasVertexAttrib(GLProgram::VERTEX_ATTRIB_NORMAL);
GLProgram* glProgram = nullptr;
const char* shader = nullptr;
if(textured)
{
if (hasSkin)
glProgram = GLProgramCache::getInstance()->getGLProgram(GLProgram::SHADER_3D_SKINPOSITION_TEXTURE);
{
if (hasNormal && _shaderUsingLight)
shader = GLProgram::SHADER_3D_SKINPOSITION_NORMAL_TEXTURE;
else
shader = GLProgram::SHADER_3D_SKINPOSITION_TEXTURE;
}
else
glProgram = GLProgramCache::getInstance()->getGLProgram(GLProgram::SHADER_3D_POSITION_TEXTURE);
{
if (hasNormal && _shaderUsingLight)
shader = GLProgram::SHADER_3D_POSITION_NORMAL_TEXTURE;
else
shader = GLProgram::SHADER_3D_POSITION_TEXTURE;
}
}
else
{
glProgram = GLProgramCache::getInstance()->getGLProgram(GLProgram::SHADER_3D_POSITION);
shader = GLProgram::SHADER_3D_POSITION;
}
if (shader)
glProgram = GLProgramCache::getInstance()->getGLProgram(shader);
auto programstate = GLProgramState::create(glProgram);
long offset = 0;
@ -499,6 +523,17 @@ void Sprite3D::draw(Renderer *renderer, const Mat4 &transform, uint32_t flags)
Color4F color(getDisplayedColor());
color.a = getDisplayedOpacity() / 255.0f;
//check light and determine the shader used
const auto& lights = Director::getInstance()->getRunningScene()->getLights();
bool usingLight = false;
for (const auto light : lights) {
usingLight = ((unsigned int)light->getLightFlag() & _lightMask) > 0;
if (usingLight)
break;
}
if (usingLight != _shaderUsingLight)
genGLProgramState();
int i = 0;
for (auto& mesh : _meshes) {
if (!mesh->isVisible())
@ -513,6 +548,8 @@ void Sprite3D::draw(Renderer *renderer, const Mat4 &transform, uint32_t flags)
meshCommand.init(_globalZOrder, textureID, programstate, _blend, mesh->getVertexBuffer(), mesh->getIndexBuffer(), mesh->getPrimitiveType(), mesh->getIndexFormat(), mesh->getIndexCount(), transform);
meshCommand.setLightMask(_lightMask);
auto skin = mesh->getSkin();
if (skin)
{

View File

@ -113,6 +113,10 @@ public:
// set cull face enable or not
void setCullFaceEnabled(bool enable);
/** light mask getter & setter, light works only when _lightmask & light's flag is true, default value of _lightmask is 0xffff */
void setLightMask(unsigned int mask) { _lightMask = mask; }
unsigned int getLightMask() const { return _lightMask; }
CC_CONSTRUCTOR_ACCESS:
Sprite3D();
@ -162,6 +166,8 @@ protected:
mutable AABB _aabb; // cache current aabb
mutable Mat4 _nodeToWorldTransform; // cache the matrix
bool _aabbDirty;
unsigned int _lightMask;
bool _shaderUsingLight; // is current shader using light ?
};
///////////////////////////////////////////////////////

View File

@ -114,6 +114,7 @@ base/CCEventListenerTouch.cpp \
base/CCEventMouse.cpp \
base/CCEventTouch.cpp \
base/CCIMEDispatcher.cpp \
base/CCLight.cpp \
base/CCNS.cpp \
base/CCProfiling.cpp \
base/ccRandom.cpp \

View File

@ -87,6 +87,7 @@ set(COCOS2D_BASE_SRC
base/CCEventMouse.cpp
base/CCEventTouch.cpp
base/CCIMEDispatcher.cpp
base/CCLight.cpp
base/CCNS.cpp
base/CCProfiling.cpp
base/CCRef.cpp

View File

@ -47,6 +47,9 @@ Configuration::Configuration()
, _maxSamplesAllowed(0)
, _maxTextureUnits(0)
, _glExtensions(nullptr)
, _maxDirLightInShader(1)
, _maxPointLightInShader(1)
, _maxSpotLightInShader(1)
{
}
@ -244,6 +247,21 @@ bool Configuration::supportsShareableVAO() const
#endif
}
int Configuration::getMaxSupportDirLightInShader() const
{
return _maxDirLightInShader;
}
int Configuration::getMaxSupportPointLightInShader() const
{
return _maxPointLightInShader;
}
int Configuration::getMaxSupportSpotLightInShader() const
{
return _maxSpotLightInShader;
}
//
// generic getters for properties
//
@ -313,6 +331,25 @@ void Configuration::loadConfigFile(const std::string& filename)
else
CCLOG("Key already present. Ignoring '%s'",dataMapIter->first.c_str());
}
//light info
std::string name = "cocos2d.x.3d.max_dir_light_in_shader";
if (_valueDict.find(name) != dataMap.end())
_maxDirLightInShader = _valueDict[name].asInt();
else
_valueDict[name] = Value(_maxDirLightInShader);
name = "cocos2d.x.3d.max_point_light_in_shader";
if (_valueDict.find(name) != dataMap.end())
_maxPointLightInShader = _valueDict[name].asInt();
else
_valueDict[name] = Value(_maxPointLightInShader);
name = "cocos2d.x.3d.max_spot_light_in_shader";
if (_valueDict.find(name) != dataMap.end())
_maxSpotLightInShader = _valueDict[name].asInt();
else
_valueDict[name] = Value(_maxSpotLightInShader);
}
NS_CC_END

View File

@ -111,6 +111,21 @@ public:
*/
bool supportsShareableVAO() const;
/** Max support directional light in shader, for Sprite3D
@since v3.3
*/
int getMaxSupportDirLightInShader() const;
/** Max support point light in shader, for Sprite3D
*since v3.3
*/
int getMaxSupportPointLightInShader() const;
/** Max support spot light in shader, for Sprite3D
*since v3.3
*/
int getMaxSupportSpotLightInShader() const;
/** returns whether or not an OpenGL is supported */
bool checkForGLExtension(const std::string &searchName) const;
@ -150,6 +165,9 @@ protected:
GLint _maxSamplesAllowed;
GLint _maxTextureUnits;
char * _glExtensions;
int _maxDirLightInShader; //max support directional light in shader
int _maxPointLightInShader; // max support point light in shader
int _maxSpotLightInShader; // max support spot light in shader
ValueMap _valueDict;
};

192
cocos/base/CCLight.cpp Normal file
View File

@ -0,0 +1,192 @@
#include "base/CCLight.h"
#include "2d/CCScene.h"
NS_CC_BEGIN
void BaseLight::setIntensity(float intensity)
{
CC_ASSERT(intensity >= 0);
_intensity = intensity;
}
void BaseLight::onEnter()
{
auto scene = getScene();
if (scene)
{
auto &lights = scene->_lights;
auto iter = std::find(lights.begin(), lights.end(), this);
if (iter == lights.end())
lights.push_back(this);
}
Node::onEnter();
}
void BaseLight::onExit()
{
auto scene = getScene();
if (scene)
{
auto &lights = scene->_lights;
auto iter = std::find(lights.begin(), lights.end(), this);
if (iter != lights.end())
lights.erase(iter);
}
Node::onExit();
}
void BaseLight::setRotationFromDirection( const Vec3 &direction )
{
float projLen = sqrt(direction.x * direction.x + direction.z * direction.z);
float rotY = CC_RADIANS_TO_DEGREES(atan2f(-direction.x, -direction.z));
float rotX = -CC_RADIANS_TO_DEGREES(atan2f(-direction.y, projLen));
setRotation3D(Vec3(rotX, rotY, 0.0f));
}
BaseLight::BaseLight()
: _intensity(1.0f)
, _enabled(true)
, _lightFlag(LightFlag::LIGHT0)
{
}
BaseLight::~BaseLight()
{
}
////////////////////////////////////////////////////////////////////
DirectionLight* DirectionLight::create(const Vec3 &direction, const Color3B &color)
{
auto light = new (std::nothrow) DirectionLight();
light->setRotationFromDirection(direction);
light->setColor(color);
light->autorelease();
return light;
}
void DirectionLight::setDirection(const Vec3 &dir)
{
setRotationFromDirection(dir);
}
const Vec3& DirectionLight::getDirection() const
{
static Vec3 dir;
Mat4 mat = getNodeToParentTransform();
dir.set(-mat.m[8], -mat.m[9], -mat.m[10]);
return dir;
}
const Vec3& DirectionLight::getDirectionInWorld() const
{
static Vec3 dir;
Mat4 mat = getNodeToWorldTransform();
dir.set(-mat.m[8], -mat.m[9], -mat.m[10]);
return dir;
}
DirectionLight::DirectionLight()
{
}
DirectionLight::~DirectionLight()
{
}
//////////////////////////////////////////////////////////////////
PointLight* PointLight::create(const Vec3 &position, const Color3B &color, float range)
{
auto light = new (std::nothrow) PointLight();
light->setPosition3D(position);
light->setColor(color);
light->_range = range;
light->autorelease();
return light;
}
PointLight::PointLight()
{
}
PointLight::~PointLight()
{
}
//////////////////////////////////////////////////////////////
SpotLight* SpotLight::create(const Vec3 &direction, const Vec3 &position, const Color3B &color, float innerAngle, float outerAngle, float range)
{
auto light = new (std::nothrow) SpotLight();
light->setRotationFromDirection(direction);
light->setPosition3D(position);
light->setColor(color);
light->setInnerAngle(innerAngle);
light->setOuterAngle(outerAngle);
light->_range = range;
light->autorelease();
return light;
}
void SpotLight::setDirection(const Vec3 &dir)
{
setRotationFromDirection(dir);
}
const Vec3& SpotLight::getDirection() const
{
static Vec3 dir;
Mat4 mat = getNodeToParentTransform();
dir.set(-mat.m[8], -mat.m[9], -mat.m[10]);
return dir;
}
const Vec3& SpotLight::getDirectionInWorld() const
{
static Vec3 dir;
Mat4 mat = getNodeToWorldTransform();
dir.set(-mat.m[8], -mat.m[9], -mat.m[10]);
return dir;
}
void SpotLight::setInnerAngle(float angle)
{
_innerAngle = angle;
_cosInnerAngle = cosf(angle);
}
void SpotLight::setOuterAngle(float angle)
{
_outerAngle = angle;
_cosInnerAngle = cosf(angle);
}
SpotLight::SpotLight()
{
}
SpotLight::~SpotLight()
{
}
/////////////////////////////////////////////////////////////
AmbientLight* AmbientLight::create( const Color3B &color )
{
auto light = new (std::nothrow) AmbientLight();
light->setColor(color);
light->autorelease();
return light;
}
AmbientLight::AmbientLight()
{
}
AmbientLight::~AmbientLight()
{
}
NS_CC_END

276
cocos/base/CCLight.h Normal file
View File

@ -0,0 +1,276 @@
/****************************************************************************
Copyright (c) 2014 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#ifndef __CCLIGHT_H__
#define __CCLIGHT_H__
#include "2d/CCNode.h"
NS_CC_BEGIN
enum class LightType
{
DIRECTIONAL = 0,
POINT = 1,
SPOT = 2,
AMBIENT = 3,
};
enum class LightFlag
{
LIGHT0 = 1,
LIGHT1 = 1 << 1,
LIGHT2 = 1 << 2,
LIGHT3 = 1 << 3,
LIGHT4 = 1 << 4,
LIGHT5 = 1 << 5,
LIGHT6 = 1 << 6,
LIGHT7 = 1 << 7,
LIGHT8 = 1 << 8,
LIGHT9 = 1 << 9,
LIGHT10 = 1 << 10,
LIGHT11 = 1 << 11,
LIGHT12 = 1 << 12,
LIGHT13 = 1 << 13,
LIGHT14 = 1 << 14,
LIGHT15 = 1 << 15,
};
class CC_DLL BaseLight : public Node
{
public:
//get light type
virtual LightType getLightType() const = 0;
/** intensity getter and setter */
float getIntensity() const { return _intensity; }
void setIntensity(float intensity);
/**light flag getter and setter*/
LightFlag getLightFlag() const { return _lightFlag; }
void setLightFlag(LightFlag flag) { _lightFlag = flag; }
/**
* light enabled getter and setter.
*/
void setEnabled(bool enabled) { _enabled = enabled; }
bool isEnabled() const { return _enabled; }
//override
virtual void onEnter() override;
virtual void onExit() override;
CC_CONSTRUCTOR_ACCESS:
BaseLight();
virtual ~BaseLight();
protected:
void setRotationFromDirection( const Vec3 &direction );
protected:
float _intensity;
LightFlag _lightFlag;
bool _enabled;
};
class CC_DLL DirectionLight : public BaseLight
{
public:
/**
* Creates a direction light.
* @param direction The light's direction
* @param color The light's color.
*
* @return The new direction light.
*/
static DirectionLight* create(const Vec3 &direction, const Color3B &color);
//get light type
virtual LightType getLightType() const override { return LightType::DIRECTIONAL; }
/**
* Sets the Direction in parent.
*
* @param dir The Direction in parent.
*/
void setDirection(const Vec3 &dir);
/**
* Returns the Direction in parent.
*/
const Vec3& getDirection() const;
/**
* Returns direction in world.
*/
const Vec3& getDirectionInWorld() const;
CC_CONSTRUCTOR_ACCESS:
DirectionLight();
virtual ~DirectionLight();
};
class CC_DLL PointLight : public BaseLight
{
public:
/**
* Creates a point light.
* @param position The light's position
* @param color The light's color.
* @param range The light's range.
*
* @return The new point light.
*/
static PointLight* create(const Vec3 &position, const Color3B &color, float range);
//get light type
virtual LightType getLightType() const override { return LightType::POINT; }
/** get or set range */
float getRange() const { return _range; }
void setRange(float range) { _range = range; }
CC_CONSTRUCTOR_ACCESS:
PointLight();
virtual ~PointLight();
protected:
float _range;
};
class CC_DLL SpotLight : public BaseLight
{
public:
/**
* Creates a spot light.
* @param direction The light's direction
* @param position The light's position
* @param color The light's color.
* @param innerAngle The light's inner angle (in radians).
* @param outerAngle The light's outer angle (in radians).
* @param range The light's range.
*
* @return The new spot light.
*/
static SpotLight* create(const Vec3 &direction, const Vec3 &position, const Color3B &color, float innerAngle, float outerAngle, float range);
//get light type
virtual LightType getLightType() const override { return LightType::SPOT; }
/**
* Sets the Direction in parent.
*
* @param dir The Direction in parent.
*/
void setDirection(const Vec3 &dir);
/**
* Returns the Direction in parent.
*/
const Vec3& getDirection() const;
/**
* Returns direction in world.
*/
const Vec3& getDirectionInWorld() const;
/**
* Sets the range of point or spot light.
*
* @param range The range of point or spot light.
*/
void setRange(float range) { _range = range; }
/**
* Returns the range of point or spot light.
*
* @return The range of the point or spot light.
*/
float getRange() const { return _range; }
/**
* Sets the inner angle of a spot light (in radians).
*
* @param angle The angle of spot light (in radians).
*/
void setInnerAngle(float angle);
/**
* Returns the inner angle the spot light (in radians).
*/
float getInnerAngle() const { return _innerAngle; }
/** get cos innerAngle */
float getCosInnerAngle() const { return _cosInnerAngle; }
/**
* Sets the outer angle of a spot light (in radians).
*
* @param outerAngle The angle of spot light (in radians).
*/
void setOuterAngle(float angle);
/**
* Returns the outer angle of the spot light (in radians).
*/
float getOuterAngle() const { return _outerAngle; }
/** get cos outAngle */
float getCosOuterAngle() const { return _cosInnerAngle; }
CC_CONSTRUCTOR_ACCESS:
SpotLight();
virtual ~SpotLight();
protected:
float _range;
float _innerAngle;
float _cosInnerAngle;
float _outerAngle;
float _cosOuterAngle;
};
class CC_DLL AmbientLight : public BaseLight
{
public:
/**
* Creates a ambient light.
* @param color The light's color.
*
* @return The new ambient light.
*/
static AmbientLight* create(const Color3B &color);
//get light type
virtual LightType getLightType() const override { return LightType::AMBIENT; }
CC_CONSTRUCTOR_ACCESS:
AmbientLight();
virtual ~AmbientLight();
};
NS_CC_END
#endif

View File

@ -62,6 +62,7 @@ THE SOFTWARE.
#include "base/CCIMEDispatcher.h"
#include "base/ccUtils.h"
#include "base/CCCamera.h"
#include "base/CCLight.h"
// EventDispatcher
#include "base/CCEventType.h"

View File

@ -72,12 +72,17 @@ const char* GLProgram::SHADER_NAME_LABEL_OUTLINE = "ShaderLabelOutline";
const char* GLProgram::SHADER_3D_POSITION = "Shader3DPosition";
const char* GLProgram::SHADER_3D_POSITION_TEXTURE = "Shader3DPositionTexture";
const char* GLProgram::SHADER_3D_SKINPOSITION_TEXTURE = "Shader3DSkinPositionTexture";
const char* GLProgram::SHADER_3D_POSITION_NORMAL = "Shader3DPositionNormal";
const char* GLProgram::SHADER_3D_POSITION_NORMAL_TEXTURE = "Shader3DPositionNormalTexture";
const char* GLProgram::SHADER_3D_SKINPOSITION_NORMAL_TEXTURE = "Shader3DSkinPositionNormalTexture";
// uniform names
const char* GLProgram::UNIFORM_NAME_AMBIENT_COLOR = "CC_AmbientColor";
const char* GLProgram::UNIFORM_NAME_P_MATRIX = "CC_PMatrix";
const char* GLProgram::UNIFORM_NAME_MV_MATRIX = "CC_MVMatrix";
const char* GLProgram::UNIFORM_NAME_MVP_MATRIX = "CC_MVPMatrix";
const char* GLProgram::UNIFORM_NAME_NORMAL_MATRIX = "CC_NormalMatrix";
const char* GLProgram::UNIFORM_NAME_TIME = "CC_Time";
const char* GLProgram::UNIFORM_NAME_SIN_TIME = "CC_SinTime";
const char* GLProgram::UNIFORM_NAME_COS_TIME = "CC_CosTime";
@ -307,56 +312,56 @@ void GLProgram::parseVertexAttribs()
{
_vertexAttribs.clear();
// Query and store vertex attribute meta-data from the program.
GLint activeAttributes;
GLint length;
glGetProgramiv(_program, GL_ACTIVE_ATTRIBUTES, &activeAttributes);
if(activeAttributes > 0)
{
// Query and store vertex attribute meta-data from the program.
GLint activeAttributes;
GLint length;
glGetProgramiv(_program, GL_ACTIVE_ATTRIBUTES, &activeAttributes);
if(activeAttributes > 0)
{
VertexAttrib attribute;
glGetProgramiv(_program, GL_ACTIVE_ATTRIBUTE_MAX_LENGTH, &length);
if(length > 0)
{
GLchar* attribName = (GLchar*) alloca(length + 1);
glGetProgramiv(_program, GL_ACTIVE_ATTRIBUTE_MAX_LENGTH, &length);
if(length > 0)
{
GLchar* attribName = (GLchar*) alloca(length + 1);
for(int i = 0; i < activeAttributes; ++i)
{
// Query attribute info.
glGetActiveAttrib(_program, i, length, nullptr, &attribute.size, &attribute.type, attribName);
attribName[length] = '\0';
for(int i = 0; i < activeAttributes; ++i)
{
// Query attribute info.
glGetActiveAttrib(_program, i, length, nullptr, &attribute.size, &attribute.type, attribName);
attribName[length] = '\0';
attribute.name = std::string(attribName);
// Query the pre-assigned attribute location
attribute.index = glGetAttribLocation(_program, attribName);
// Query the pre-assigned attribute location
attribute.index = glGetAttribLocation(_program, attribName);
_vertexAttribs[attribute.name] = attribute;
}
}
}
}
}
}
}
void GLProgram::parseUniforms()
{
_userUniforms.clear();
// Query and store uniforms from the program.
GLint activeUniforms;
glGetProgramiv(_program, GL_ACTIVE_UNIFORMS, &activeUniforms);
if(activeUniforms > 0)
{
// Query and store uniforms from the program.
GLint activeUniforms;
glGetProgramiv(_program, GL_ACTIVE_UNIFORMS, &activeUniforms);
if(activeUniforms > 0)
{
GLint length;
glGetProgramiv(_program, GL_ACTIVE_UNIFORM_MAX_LENGTH, &length);
if(length > 0)
{
glGetProgramiv(_program, GL_ACTIVE_UNIFORM_MAX_LENGTH, &length);
if(length > 0)
{
Uniform uniform;
GLchar* uniformName = (GLchar*)alloca(length + 1);
GLchar* uniformName = (GLchar*)alloca(length + 1);
for(int i = 0; i < activeUniforms; ++i)
{
// Query uniform info.
glGetActiveUniform(_program, i, length, nullptr, &uniform.size, &uniform.type, uniformName);
uniformName[length] = '\0';
for(int i = 0; i < activeUniforms; ++i)
{
// Query uniform info.
glGetActiveUniform(_program, i, length, nullptr, &uniform.size, &uniform.type, uniformName);
uniformName[length] = '\0';
// Only add uniforms that are not built-in.
// The ones that start with 'CC_' are built-ins
@ -382,9 +387,9 @@ void GLProgram::parseUniforms()
_userUniforms[uniform.name] = uniform;
}
}
}
}
}
}
}
}
Uniform* GLProgram::getUniform(const std::string &name)
@ -422,11 +427,12 @@ bool GLProgram::compileShader(GLuint * shader, GLenum type, const GLchar* source
const GLchar *sources[] = {
#if (CC_TARGET_PLATFORM != CC_PLATFORM_WIN32 && CC_TARGET_PLATFORM != CC_PLATFORM_LINUX && CC_TARGET_PLATFORM != CC_PLATFORM_MAC)
(type == GL_VERTEX_SHADER ? "precision highp float;\n" : "precision mediump float;\n"),
(type == GL_VERTEX_SHADER ? "precision highp float;\n precision highp int;\n" : "precision mediump float;\n precision mediump int;\n"),
#endif
"uniform mat4 CC_PMatrix;\n"
"uniform mat4 CC_MVMatrix;\n"
"uniform mat4 CC_MVPMatrix;\n"
"uniform mat3 CC_NormalMatrix;\n"
"uniform vec4 CC_Time;\n"
"uniform vec4 CC_SinTime;\n"
"uniform vec4 CC_CosTime;\n"
@ -486,9 +492,11 @@ void GLProgram::bindAttribLocation(const std::string &attributeName, GLuint inde
void GLProgram::updateUniforms()
{
_builtInUniforms[UNIFORM_AMBIENT_COLOR] = glGetUniformLocation(_program, UNIFORM_NAME_AMBIENT_COLOR);
_builtInUniforms[UNIFORM_P_MATRIX] = glGetUniformLocation(_program, UNIFORM_NAME_P_MATRIX);
_builtInUniforms[UNIFORM_MV_MATRIX] = glGetUniformLocation(_program, UNIFORM_NAME_MV_MATRIX);
_builtInUniforms[UNIFORM_MVP_MATRIX] = glGetUniformLocation(_program, UNIFORM_NAME_MVP_MATRIX);
_builtInUniforms[UNIFORM_NORMAL_MATRIX] = glGetUniformLocation(_program, UNIFORM_NAME_NORMAL_MATRIX);
_builtInUniforms[UNIFORM_TIME] = glGetUniformLocation(_program, UNIFORM_NAME_TIME);
_builtInUniforms[UNIFORM_SIN_TIME] = glGetUniformLocation(_program, UNIFORM_NAME_SIN_TIME);
@ -504,6 +512,7 @@ void GLProgram::updateUniforms()
_flags.usesP = _builtInUniforms[UNIFORM_P_MATRIX] != -1;
_flags.usesMV = _builtInUniforms[UNIFORM_MV_MATRIX] != -1;
_flags.usesMVP = _builtInUniforms[UNIFORM_MVP_MATRIX] != -1;
_flags.usesNormal = _builtInUniforms[UNIFORM_NORMAL_MATRIX] != -1;
_flags.usesTime = (
_builtInUniforms[UNIFORM_TIME] != -1 ||
_builtInUniforms[UNIFORM_SIN_TIME] != -1 ||
@ -785,6 +794,17 @@ void GLProgram::setUniformLocationWith4f(GLint location, GLfloat f1, GLfloat f2,
}
}
void GLProgram::setUniformLocationWith1fv( GLint location, const GLfloat* floats, unsigned int numberOfArrays )
{
bool updated = updateUniformLocation(location, floats, sizeof(float)*numberOfArrays);
if( updated )
{
glUniform1fv( (GLint)location, (GLsizei)numberOfArrays, floats );
}
}
void GLProgram::setUniformLocationWith2fv(GLint location, const GLfloat* floats, unsigned int numberOfArrays)
{
bool updated = updateUniformLocation(location, floats, sizeof(float)*2*numberOfArrays);
@ -870,6 +890,19 @@ void GLProgram::setUniformsForBuiltins(const Mat4 &matrixMV)
setUniformLocationWithMatrix4fv(_builtInUniforms[UNIFORM_MVP_MATRIX], matrixMVP.m, 1);
}
if (_flags.usesNormal)
{
Mat4 mvInverse = matrixMV;
mvInverse.m[12] = mvInverse.m[13] = mvInverse.m[14] = 0.0f;
mvInverse.inverse();
mvInverse.transpose();
GLfloat normalMat[9];
normalMat[0] = mvInverse.m[0];normalMat[1] = mvInverse.m[1];normalMat[2] = mvInverse.m[2];
normalMat[3] = mvInverse.m[4];normalMat[4] = mvInverse.m[5];normalMat[5] = mvInverse.m[6];
normalMat[6] = mvInverse.m[8];normalMat[7] = mvInverse.m[9];normalMat[8] = mvInverse.m[10];
setUniformLocationWithMatrix3fv(_builtInUniforms[UNIFORM_NORMAL_MATRIX], normalMat, 1);
}
if(_flags.usesTime) {
Director *director = Director::getInstance();
// This doesn't give the most accurate global time value.

View File

@ -103,9 +103,11 @@ public:
enum
{
UNIFORM_AMBIENT_COLOR,
UNIFORM_P_MATRIX,
UNIFORM_MV_MATRIX,
UNIFORM_MVP_MATRIX,
UNIFORM_NORMAL_MATRIX,
UNIFORM_TIME,
UNIFORM_SIN_TIME,
UNIFORM_COS_TIME,
@ -140,11 +142,16 @@ public:
static const char* SHADER_3D_POSITION;
static const char* SHADER_3D_POSITION_TEXTURE;
static const char* SHADER_3D_SKINPOSITION_TEXTURE;
static const char* SHADER_3D_POSITION_NORMAL;
static const char* SHADER_3D_POSITION_NORMAL_TEXTURE;
static const char* SHADER_3D_SKINPOSITION_NORMAL_TEXTURE;
// uniform names
static const char* UNIFORM_NAME_AMBIENT_COLOR;
static const char* UNIFORM_NAME_P_MATRIX;
static const char* UNIFORM_NAME_MV_MATRIX;
static const char* UNIFORM_NAME_MVP_MATRIX;
static const char* UNIFORM_NAME_NORMAL_MATRIX;
static const char* UNIFORM_NAME_TIME;
static const char* UNIFORM_NAME_SIN_TIME;
static const char* UNIFORM_NAME_COS_TIME;
@ -197,8 +204,8 @@ public:
static GLProgram* createWithFilenames(const std::string& vShaderFilename, const std::string& fShaderFilename);
bool initWithFilenames(const std::string& vShaderFilename, const std::string& fShaderFilename);
//void bindUniform(std::string uniformName, int value);
Uniform* getUniform(const std::string& name);
//void bindUniform(std::string uniformName, int value);
Uniform* getUniform(const std::string& name);
VertexAttrib* getVertexAttrib(const std::string& name);
/** It will add a new attribute to the shader by calling glBindAttribLocation */
@ -277,6 +284,9 @@ public:
*/
void setUniformLocationWith4f(GLint location, GLfloat f1, GLfloat f2, GLfloat f3, GLfloat f4);
/** calls glUniformfv only if the values are different than the previous call for this same shader program. */
void setUniformLocationWith1fv(GLint location, const GLfloat* floats, unsigned int numberOfArrays);
/** calls glUniform2fv only if the values are different than the previous call for this same shader program. */
void setUniformLocationWith2fv(GLint location, const GLfloat* floats, unsigned int numberOfArrays);
@ -340,7 +350,7 @@ protected:
GLuint _fragShader;
GLint _builtInUniforms[UNIFORM_MAX];
struct _hashUniformEntry* _hashForUniforms;
bool _hasShaderCompiler;
bool _hasShaderCompiler;
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) || (CC_TARGET_PLATFORM == CC_PLATFORM_WP8)
std::string _shaderId;
@ -348,11 +358,11 @@ protected:
struct flag_struct {
unsigned int usesTime:1;
unsigned int usesNormal:1;
unsigned int usesMVP:1;
unsigned int usesMV:1;
unsigned int usesP:1;
unsigned int usesRandom:1;
unsigned int usesRandom:1;
// handy way to initialize the bitfield
flag_struct() { memset(this, 0, sizeof(*this)); }
} _flags;

View File

@ -30,6 +30,7 @@ THE SOFTWARE.
#include "renderer/CCGLProgram.h"
#include "renderer/ccShaders.h"
#include "base/ccMacros.h"
#include "base/CCConfiguration.h"
NS_CC_BEGIN
@ -52,6 +53,9 @@ enum {
kShaderType_3DPosition,
kShaderType_3DPositionTex,
kShaderType_3DSkinPositionTex,
kShaderType_3DPositionNormal,
kShaderType_3DPositionNormalTex,
kShaderType_3DSkinPositionNormalTex,
kShaderType_MAX,
};
@ -171,8 +175,8 @@ void GLProgramCache::loadDefaultGLPrograms()
_programs.insert( std::make_pair(GLProgram::SHADER_NAME_POSITION_U_COLOR, p) );
//
// Position, Legth(TexCoords, Color (used by Draw Node basically )
//
// Position, Legth(TexCoords, Color (used by Draw Node basically )
//
p = new (std::nothrow) GLProgram();
loadDefaultGLProgram(p, kShaderType_PositionLengthTexureColor);
_programs.insert( std::make_pair(GLProgram::SHADER_NAME_POSITION_LENGTH_TEXTURE_COLOR, p) );
@ -204,6 +208,18 @@ void GLProgramCache::loadDefaultGLPrograms()
p = new (std::nothrow) GLProgram();
loadDefaultGLProgram(p, kShaderType_3DSkinPositionTex);
_programs.insert(std::make_pair(GLProgram::SHADER_3D_SKINPOSITION_TEXTURE, p));
p = new GLProgram();
loadDefaultGLProgram(p, kShaderType_3DPositionNormal);
_programs.insert( std::make_pair(GLProgram::SHADER_3D_POSITION_NORMAL, p) );
p = new GLProgram();
loadDefaultGLProgram(p, kShaderType_3DPositionNormalTex);
_programs.insert( std::make_pair(GLProgram::SHADER_3D_POSITION_NORMAL_TEXTURE, p) );
p = new GLProgram();
loadDefaultGLProgram(p, kShaderType_3DSkinPositionNormalTex);
_programs.insert(std::make_pair(GLProgram::SHADER_3D_SKINPOSITION_NORMAL_TEXTURE, p));
}
void GLProgramCache::reloadDefaultGLPrograms()
@ -271,8 +287,8 @@ void GLProgramCache::reloadDefaultGLPrograms()
loadDefaultGLProgram(p, kShaderType_Position_uColor);
//
// Position, Legth(TexCoords, Color (used by Draw Node basically )
//
// Position, Legth(TexCoords, Color (used by Draw Node basically )
//
p = getGLProgram(GLProgram::SHADER_NAME_POSITION_LENGTH_TEXTURE_COLOR);
p->reset();
loadDefaultGLProgram(p, kShaderType_PositionLengthTexureColor);
@ -304,6 +320,18 @@ void GLProgramCache::reloadDefaultGLPrograms()
p = getGLProgram(GLProgram::SHADER_3D_SKINPOSITION_TEXTURE);
p->reset();
loadDefaultGLProgram(p, kShaderType_3DSkinPositionTex);
p = getGLProgram(GLProgram::SHADER_3D_POSITION_NORMAL);
p->reset();
loadDefaultGLProgram(p, kShaderType_3DPositionNormal);
p = getGLProgram(GLProgram::SHADER_3D_POSITION_NORMAL_TEXTURE);
p->reset();
loadDefaultGLProgram(p, kShaderType_3DPositionNormalTex);
p = getGLProgram(GLProgram::SHADER_3D_SKINPOSITION_NORMAL_TEXTURE);
p->reset();
loadDefaultGLProgram(p, kShaderType_3DSkinPositionNormalTex);
}
void GLProgramCache::loadDefaultGLProgram(GLProgram *p, int type)
@ -322,7 +350,6 @@ void GLProgramCache::loadDefaultGLProgram(GLProgram *p, int type)
case kShaderType_PositionTextureColorAlphaTestNoMV:
p->initWithByteArrays(ccPositionTextureColor_noMVP_vert, ccPositionTextureColorAlphaTest_frag);
break;
case kShaderType_PositionColor:
p->initWithByteArrays(ccPositionColor_vert ,ccPositionColor_frag);
break;
@ -366,6 +393,24 @@ void GLProgramCache::loadDefaultGLProgram(GLProgram *p, int type)
case kShaderType_3DSkinPositionTex:
p->initWithByteArrays(cc3D_SkinPositionTex_vert, cc3D_ColorTex_frag);
break;
case kShaderType_3DPositionNormal:
{
std::string def = getShaderMacrosForLight();
p->initWithByteArrays((def + std::string(cc3D_PositionNormalTex_vert)).c_str(), (def + std::string(cc3D_ColorNormal_frag)).c_str());
}
break;
case kShaderType_3DPositionNormalTex:
{
std::string def = getShaderMacrosForLight();
p->initWithByteArrays((def + std::string(cc3D_PositionNormalTex_vert)).c_str(), (def + std::string(cc3D_ColorNormalTex_frag)).c_str());
}
break;
case kShaderType_3DSkinPositionNormalTex:
{
std::string def = getShaderMacrosForLight();
p->initWithByteArrays((def + std::string(cc3D_SkinPositionNormalTex_vert)).c_str(), (def + std::string(cc3D_ColorNormalTex_frag)).c_str());
}
break;
default:
CCLOG("cocos2d: %s:%d, error shader type", __FUNCTION__, __LINE__);
return;
@ -393,4 +438,14 @@ void GLProgramCache::addGLProgram(GLProgram* program, const std::string &key)
_programs[key] = program;
}
std::string GLProgramCache::getShaderMacrosForLight() const
{
GLchar def[256];
sprintf(def, "\n#define MAX_DIRECTIONAL_LIGHT_NUM %d \n"
"\n#define MAX_POINT_LIGHT_NUM %d \n"
"\n#define MAX_SPOT_LIGHT_NUM %d \n"
, Configuration::getInstance()->getMaxSupportDirLightInShader(), Configuration::getInstance()->getMaxSupportPointLightInShader(), Configuration::getInstance()->getMaxSupportSpotLightInShader());
return std::string(def);
}
NS_CC_END

View File

@ -93,6 +93,8 @@ private:
bool init();
void loadDefaultGLProgram(GLProgram *program, int type);
std::string getShaderMacrosForLight() const;
// Dictionary* _programs;
std::unordered_map<std::string, GLProgram*> _programs;
};

View File

@ -30,6 +30,8 @@
#include "base/CCEventListenerCustom.h"
#include "base/CCEventDispatcher.h"
#include "base/CCEventType.h"
#include "base/CCConfiguration.h"
#include "base/CCLight.h"
#include "renderer/ccGLStateCache.h"
#include "renderer/CCGLProgramState.h"
#include "renderer/CCRenderer.h"
@ -46,6 +48,33 @@ static GLenum s_cullFace = 0;
static bool s_depthTestEnabled = false;
static bool s_depthWriteEnabled = false;
struct DirectionLightUniformNames
{
std::string color;
std::string dir;
};
struct PointLightUniformNames
{
std::string color;
std::string position;
std::string rangeInverse;
};
struct SpotLightUniformNames
{
std::string color;
std::string position;
std::string dir;
std::string innerAngleCos;
std::string outerAngleCos;
std::string rangeInverse;
};
static std::vector<DirectionLightUniformNames> s_dirLightUniformNames;
static std::vector<PointLightUniformNames> s_pointLightUniformNames;
static std::vector<SpotLightUniformNames> s_spotLightUniformNames;
MeshCommand::MeshCommand()
: _textureID(0)
, _blendType(BlendFunc::DISABLE)
@ -59,6 +88,7 @@ MeshCommand::MeshCommand()
, _matrixPaletteSize(0)
, _materialID(0)
, _vao(0)
, _lightMask(-1)
{
_type = RenderCommand::Type::MESH_COMMAND;
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID || CC_TARGET_PLATFORM == CC_PLATFORM_WP8)
@ -92,6 +122,8 @@ void MeshCommand::init(float globalOrder,
_indexFormat = indexFormat;
_indexCount = indexCount;
_mv.set(mv);
setLightUniformNames();
}
void MeshCommand::setCullFaceEnabled(bool enable)
@ -220,6 +252,9 @@ void MeshCommand::batchDraw()
}
if (Director::getInstance()->getRunningScene()->getLights().size() > 0)
setLightUniforms();
_glProgramState->applyGLProgram(_mv);
_glProgramState->applyUniforms();
@ -260,6 +295,9 @@ void MeshCommand::execute()
}
if (Director::getInstance()->getRunningScene()->getLights().size() > 0)
setLightUniforms();
_glProgramState->apply(_mv);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _indexBuffer);
@ -306,11 +344,198 @@ void MeshCommand::releaseVAO()
}
}
void MeshCommand::setLightUniforms()
{
Director *director = Director::getInstance();
auto scene = director->getRunningScene();
const auto& conf = Configuration::getInstance();
int maxDirLight = conf->getMaxSupportDirLightInShader();
int maxPointLight = conf->getMaxSupportPointLightInShader();
int maxSpotLight = conf->getMaxSupportSpotLightInShader();
auto &lights = scene->getLights();
if (_glProgramState->getVertexAttribsFlags() & (1 << GLProgram::VERTEX_ATTRIB_NORMAL))
{
GLint enabledDirLightNum = 0;
GLint enabledPointLightNum = 0;
GLint enabledSpotLightNum = 0;
Vec3 ambientColor;
for (const auto& light : lights)
{
bool useLight = light->isEnabled() && ((unsigned int)light->getLightFlag() & _lightMask);
if (useLight)
{
float intensity = light->getIntensity();
switch (light->getLightType())
{
case LightType::DIRECTIONAL:
{
CCASSERT(enabledDirLightNum < maxDirLight, "");
auto dirLight = static_cast<DirectionLight *>(light);
Vec3 dir = dirLight->getDirectionInWorld();
dir.normalize();
const Color3B &col = dirLight->getDisplayedColor();
_glProgramState->setUniformVec3(s_dirLightUniformNames[enabledDirLightNum].color, Vec3(col.r / 255.0f * intensity, col.g / 255.0f * intensity, col.b / 255.0f * intensity));
_glProgramState->setUniformVec3(s_dirLightUniformNames[enabledDirLightNum].dir, dir);
++enabledDirLightNum;
}
break;
case LightType::POINT:
{
CCASSERT(enabledPointLightNum < maxPointLight, "");
auto pointLight = static_cast<PointLight *>(light);
Mat4 mat= pointLight->getNodeToWorldTransform();
const Color3B &col = pointLight->getDisplayedColor();
_glProgramState->setUniformVec3(s_pointLightUniformNames[enabledPointLightNum].color, Vec3(col.r / 255.0f * intensity, col.g / 255.0f * intensity, col.b / 255.0f * intensity));
_glProgramState->setUniformVec3(s_pointLightUniformNames[enabledPointLightNum].position, Vec3(mat.m[12], mat.m[13], mat.m[14]));
_glProgramState->setUniformFloat(s_pointLightUniformNames[enabledPointLightNum].rangeInverse, 1.0f / pointLight->getRange());
++enabledPointLightNum;
}
break;
case LightType::SPOT:
{
CCASSERT(enabledSpotLightNum < maxSpotLight, "");
auto spotLight = static_cast<SpotLight *>(light);
Vec3 dir = spotLight->getDirectionInWorld();
dir.normalize();
Mat4 mat= light->getNodeToWorldTransform();
const Color3B &col = spotLight->getDisplayedColor();
_glProgramState->setUniformVec3(s_spotLightUniformNames[enabledSpotLightNum].color, Vec3(col.r / 255.0f * intensity, col.g / 255.0f * intensity, col.b / 255.0f * intensity));
_glProgramState->setUniformVec3(s_spotLightUniformNames[enabledSpotLightNum].position, Vec3(mat.m[12], mat.m[13], mat.m[14]));
_glProgramState->setUniformVec3(s_spotLightUniformNames[enabledSpotLightNum].dir, dir);
_glProgramState->setUniformFloat(s_spotLightUniformNames[enabledSpotLightNum].innerAngleCos, spotLight->getCosInnerAngle());
_glProgramState->setUniformFloat(s_spotLightUniformNames[enabledSpotLightNum].outerAngleCos, spotLight->getCosOuterAngle());
_glProgramState->setUniformFloat(s_spotLightUniformNames[enabledSpotLightNum].rangeInverse, 1.0f / spotLight->getRange());
++enabledSpotLightNum;
}
break;
case LightType::AMBIENT:
{
auto ambLight = static_cast<AmbientLight *>(light);
const Color3B &col = ambLight->getDisplayedColor();
ambientColor += Vec3(col.r / 255.0f * intensity, col.g / 255.0f * intensity, col.b / 255.0f * intensity);
}
break;
default:
break;
}
}
}
for (unsigned short i = enabledDirLightNum; i < maxDirLight; ++i)
{
_glProgramState->setUniformVec3(s_dirLightUniformNames[i].color, Vec3::ZERO);
_glProgramState->setUniformVec3(s_dirLightUniformNames[i].dir, Vec3::ZERO);
}
for (unsigned short i = enabledPointLightNum; i < maxPointLight; ++i)
{
_glProgramState->setUniformVec3(s_pointLightUniformNames[i].color, Vec3::ZERO);
_glProgramState->setUniformVec3(s_pointLightUniformNames[i].position, Vec3::ZERO);
_glProgramState->setUniformFloat(s_pointLightUniformNames[i].rangeInverse, 0.0f);
}
for (unsigned short i = enabledSpotLightNum; i < maxSpotLight; ++i)
{
_glProgramState->setUniformVec3(s_spotLightUniformNames[i].color, Vec3::ZERO);
_glProgramState->setUniformVec3(s_spotLightUniformNames[i].position, Vec3::ZERO);
_glProgramState->setUniformVec3(s_spotLightUniformNames[i].dir, Vec3::ZERO);
_glProgramState->setUniformFloat(s_spotLightUniformNames[i].innerAngleCos, 0.0f);
_glProgramState->setUniformFloat(s_spotLightUniformNames[i].outerAngleCos, 0.0f);
_glProgramState->setUniformFloat(s_spotLightUniformNames[i].rangeInverse, 0.0f);
}
_glProgramState->setUniformVec3("u_AmbientLightSourceColor", ambientColor);
}
else // normal does not exist
{
Vec3 ambient(0.0f, 0.0f, 0.0f);
bool hasAmbient;
for (const auto& light : lights)
{
if (light->getLightType() == LightType::AMBIENT)
{
bool useLight = light->isEnabled() && ((unsigned int)light->getLightFlag() & _lightMask);
if (useLight)
{
hasAmbient = true;
const Color3B &col = light->getDisplayedColor();
ambient.x += col.r * light->getIntensity();
ambient.y += col.g * light->getIntensity();
ambient.z += col.b * light->getIntensity();
}
}
}
if (hasAmbient)
{
ambient.x /= 255.f; ambient.y /= 255.f; ambient.z /= 255.f;
}
_glProgramState->setUniformVec4("u_color", Vec4(_displayColor.x * ambient.x, _displayColor.y * ambient.y, _displayColor.z * ambient.z, _displayColor.w));
}
}
void MeshCommand::setLightUniformNames()
{
const auto& conf = Configuration::getInstance();
int maxDirLight = conf->getMaxSupportDirLightInShader();
int maxPointLight = conf->getMaxSupportPointLightInShader();
int maxSpotLight = conf->getMaxSupportSpotLightInShader();
if (s_dirLightUniformNames.size() != maxDirLight)
{
s_dirLightUniformNames.resize(maxDirLight);
char str[64];
for (unsigned int i = 0; i < maxDirLight; ++i)
{
sprintf(str, "u_DirLightSourceColor[%d]", i);
s_dirLightUniformNames[i].color = str;
sprintf(str, "u_DirLightSourceDirection[%d]", i);
s_dirLightUniformNames[i].dir = str;
}
}
if (s_pointLightUniformNames.size() != maxPointLight)
{
s_pointLightUniformNames.resize(maxPointLight);
char str[64];
for (unsigned int i = 0; i < maxPointLight; ++i)
{
sprintf(str, "u_PointLightSourceColor[%d]", i);
s_pointLightUniformNames[i].color = str;
sprintf(str, "u_PointLightSourcePosition[%d]", i);
s_pointLightUniformNames[i].position = str;
sprintf(str, "u_PointLightSourceRangeInverse[%d]", i);
s_pointLightUniformNames[i].rangeInverse = str;
}
}
if (s_spotLightUniformNames.size() != maxSpotLight)
{
s_spotLightUniformNames.resize(maxSpotLight);
char str[64];
for (unsigned int i = 0; i < maxSpotLight; ++i)
{
sprintf(str, "u_SpotLightSourceColor[%d]", i);
s_spotLightUniformNames[i].color = str;
sprintf(str, "u_SpotLightSourcePosition[%d]", i);
s_spotLightUniformNames[i].position = str;
sprintf(str, "u_SpotLightSourceDirection[%d]", i);
s_spotLightUniformNames[i].dir = str;
sprintf(str, "u_SpotLightSourceInnerAngleCos[%d]", i);
s_spotLightUniformNames[i].innerAngleCos = str;
sprintf(str, "u_SpotLightSourceOuterAngleCos[%d]", i);
s_spotLightUniformNames[i].outerAngleCos = str;
sprintf(str, "u_SpotLightSourceRangeInverse[%d]", i);
s_spotLightUniformNames[i].rangeInverse = str;
}
}
}
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID || CC_TARGET_PLATFORM == CC_PLATFORM_WP8)
void MeshCommand::listenRendererRecreated(EventCustom* event)
{
_vao = 0;
}
#endif
NS_CC_END

View File

@ -62,6 +62,8 @@ public:
void setMatrixPaletteSize(int size) { _matrixPaletteSize = size; }
void setLightMask(unsigned int lightmask) { _lightMask = lightmask; }
void execute();
//used for bath
@ -85,11 +87,15 @@ protected:
// apply renderstate
void applyRenderState();
void setLightUniforms();
//restore to all false
void restoreRenderState();
void MatrixPalleteCallBack( GLProgram* glProgram, Uniform* uniform);
void setLightUniformNames();
GLuint _textureID;
GLProgramState* _glProgramState;
BlendFunc _blendType;
@ -121,6 +127,8 @@ protected:
// ModelView transform
Mat4 _mv;
unsigned int _lightMask;
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID || CC_TARGET_PLATFORM == CC_PLATFORM_WP8)
EventListenerCustom* _rendererRecreatedListener;
#endif

View File

@ -0,0 +1,112 @@
const char* cc3D_ColorNormal_frag = STRINGIFY(
\n#if (MAX_DIRECTIONAL_LIGHT_NUM > 0)\n
uniform vec3 u_DirLightSourceColor[MAX_DIRECTIONAL_LIGHT_NUM];
uniform vec3 u_DirLightSourceDirection[MAX_DIRECTIONAL_LIGHT_NUM];
\n#endif\n
\n#if (MAX_POINT_LIGHT_NUM > 0)\n
uniform vec3 u_PointLightSourceColor[MAX_POINT_LIGHT_NUM];
uniform float u_PointLightSourceRangeInverse[MAX_POINT_LIGHT_NUM];
\n#endif\n
\n#if (MAX_SPOT_LIGHT_NUM > 0)\n
uniform vec3 u_SpotLightSourceColor[MAX_SPOT_LIGHT_NUM];
uniform vec3 u_SpotLightSourceDirection[MAX_SPOT_LIGHT_NUM];
uniform float u_SpotLightSourceInnerAngleCos[MAX_SPOT_LIGHT_NUM];
uniform float u_SpotLightSourceOuterAngleCos[MAX_SPOT_LIGHT_NUM];
uniform float u_SpotLightSourceRangeInverse[MAX_SPOT_LIGHT_NUM];
\n#endif\n
uniform vec3 u_AmbientLightSourceColor;
\n#ifdef GL_ES\n
varying mediump vec2 TextureCoordOut;
\n#if MAX_POINT_LIGHT_NUM\n
varying mediump vec3 v_vertexToPointLightDirection[MAX_POINT_LIGHT_NUM];
\n#endif\n
\n#if MAX_SPOT_LIGHT_NUM\n
varying mediump vec3 v_vertexToSpotLightDirection[MAX_SPOT_LIGHT_NUM];
\n#endif\n
\n#if ((MAX_DIRECTIONAL_LIGHT_NUM > 0) || (MAX_POINT_LIGHT_NUM > 0) || (MAX_SPOT_LIGHT_NUM > 0))\n
varying mediump vec3 v_normal;
\n#endif\n
\n#else\n
varying vec2 TextureCoordOut;
\n#if MAX_POINT_LIGHT_NUM\n
varying vec3 v_vertexToPointLightDirection[MAX_POINT_LIGHT_NUM];
\n#endif\n
\n#if MAX_SPOT_LIGHT_NUM\n
varying vec3 v_vertexToSpotLightDirection[MAX_SPOT_LIGHT_NUM];
\n#endif\n
\n#if ((MAX_DIRECTIONAL_LIGHT_NUM > 0) || (MAX_POINT_LIGHT_NUM > 0) || (MAX_SPOT_LIGHT_NUM > 0))\n
varying vec3 v_normal;
\n#endif\n
\n#endif\n
uniform vec4 u_color;
vec3 computeLighting(vec3 normalVector, vec3 lightDirection, vec3 lightColor, float attenuation)
{
float diffuse = max(dot(normalVector, lightDirection), 0.0);
vec3 diffuseColor = lightColor * diffuse * attenuation;
return diffuseColor;
}
void main(void)
{
\n#if ((MAX_DIRECTIONAL_LIGHT_NUM > 0) || (MAX_POINT_LIGHT_NUM > 0) || (MAX_SPOT_LIGHT_NUM > 0))\n
vec3 normal = normalize(v_normal);
\n#endif\n
vec4 combinedColor = vec4(u_AmbientLightSourceColor, 1.0);
// Directional light contribution
\n#if (MAX_DIRECTIONAL_LIGHT_NUM > 0)\n
for (int i = 0; i < MAX_DIRECTIONAL_LIGHT_NUM; ++i)
{
vec3 lightDirection = normalize(u_DirLightSourceDirection[i] * 2.0);
combinedColor.xyz += computeLighting(normal, -lightDirection, u_DirLightSourceColor[i], 1.0);
}
\n#endif\n
// Point light contribution
\n#if (MAX_POINT_LIGHT_NUM > 0)\n
for (int i = 0; i < MAX_POINT_LIGHT_NUM; ++i)
{
vec3 ldir = v_vertexToPointLightDirection[i] * u_PointLightSourceRangeInverse[i];
float attenuation = clamp(1.0 - dot(ldir, ldir), 0.0, 1.0);
combinedColor.xyz += computeLighting(normal, normalize(v_vertexToPointLightDirection[i]), u_PointLightSourceColor[i], attenuation);
}
\n#endif\n
// Spot light contribution
\n#if (MAX_SPOT_LIGHT_NUM > 0)\n
for (int i = 0; i < MAX_SPOT_LIGHT_NUM; ++i)
{
// Compute range attenuation
vec3 ldir = v_vertexToSpotLightDirection[i] * u_SpotLightSourceRangeInverse[i];
float attenuation = clamp(1.0 - dot(ldir, ldir), 0.0, 1.0);
vec3 vertexToSpotLightDirection = normalize(v_vertexToSpotLightDirection[i]);
vec3 spotLightDirection = normalize(u_SpotLightSourceDirection[i] * 2.0);
// "-lightDirection" is used because light direction points in opposite direction to spot direction.
float spotCurrentAngleCos = dot(spotLightDirection, -vertexToSpotLightDirection);
// Apply spot attenuation
attenuation *= smoothstep(u_SpotLightSourceOuterAngleCos[i], u_SpotLightSourceInnerAngleCos[i], spotCurrentAngleCos);
combinedColor.xyz += computeLighting(normal, vertexToSpotLightDirection, u_SpotLightSourceColor[i], attenuation);
}
\n#endif\n
\n#if ((MAX_DIRECTIONAL_LIGHT_NUM > 0) || (MAX_POINT_LIGHT_NUM > 0) || (MAX_SPOT_LIGHT_NUM > 0))\n
gl_FragColor = u_color * combinedColor;
\n#else\n
gl_FragColor = u_color;
\n#endif\n
}
);

View File

@ -0,0 +1,112 @@
const char* cc3D_ColorNormalTex_frag = STRINGIFY(
\n#if (MAX_DIRECTIONAL_LIGHT_NUM > 0)\n
uniform vec3 u_DirLightSourceColor[MAX_DIRECTIONAL_LIGHT_NUM];
uniform vec3 u_DirLightSourceDirection[MAX_DIRECTIONAL_LIGHT_NUM];
\n#endif\n
\n#if (MAX_POINT_LIGHT_NUM > 0)\n
uniform vec3 u_PointLightSourceColor[MAX_POINT_LIGHT_NUM];
uniform float u_PointLightSourceRangeInverse[MAX_POINT_LIGHT_NUM];
\n#endif\n
\n#if (MAX_SPOT_LIGHT_NUM > 0)\n
uniform vec3 u_SpotLightSourceColor[MAX_SPOT_LIGHT_NUM];
uniform vec3 u_SpotLightSourceDirection[MAX_SPOT_LIGHT_NUM];
uniform float u_SpotLightSourceInnerAngleCos[MAX_SPOT_LIGHT_NUM];
uniform float u_SpotLightSourceOuterAngleCos[MAX_SPOT_LIGHT_NUM];
uniform float u_SpotLightSourceRangeInverse[MAX_SPOT_LIGHT_NUM];
\n#endif\n
uniform vec3 u_AmbientLightSourceColor;
\n#ifdef GL_ES\n
varying mediump vec2 TextureCoordOut;
\n#if MAX_POINT_LIGHT_NUM\n
varying mediump vec3 v_vertexToPointLightDirection[MAX_POINT_LIGHT_NUM];
\n#endif\n
\n#if MAX_SPOT_LIGHT_NUM\n
varying mediump vec3 v_vertexToSpotLightDirection[MAX_SPOT_LIGHT_NUM];
\n#endif\n
\n#if ((MAX_DIRECTIONAL_LIGHT_NUM > 0) || (MAX_POINT_LIGHT_NUM > 0) || (MAX_SPOT_LIGHT_NUM > 0))\n
varying mediump vec3 v_normal;
\n#endif\n
\n#else\n
varying vec2 TextureCoordOut;
\n#if MAX_POINT_LIGHT_NUM\n
varying vec3 v_vertexToPointLightDirection[MAX_POINT_LIGHT_NUM];
\n#endif\n
\n#if MAX_SPOT_LIGHT_NUM\n
varying vec3 v_vertexToSpotLightDirection[MAX_SPOT_LIGHT_NUM];
\n#endif\n
\n#if ((MAX_DIRECTIONAL_LIGHT_NUM > 0) || (MAX_POINT_LIGHT_NUM > 0) || (MAX_SPOT_LIGHT_NUM > 0))\n
varying vec3 v_normal;
\n#endif\n
\n#endif\n
uniform vec4 u_color;
vec3 computeLighting(vec3 normalVector, vec3 lightDirection, vec3 lightColor, float attenuation)
{
float diffuse = max(dot(normalVector, lightDirection), 0.0);
vec3 diffuseColor = lightColor * diffuse * attenuation;
return diffuseColor;
}
void main(void)
{
\n#if ((MAX_DIRECTIONAL_LIGHT_NUM > 0) || (MAX_POINT_LIGHT_NUM > 0) || (MAX_SPOT_LIGHT_NUM > 0))\n
vec3 normal = normalize(v_normal);
\n#endif\n
vec4 combinedColor = vec4(u_AmbientLightSourceColor, 1.0);
// Directional light contribution
\n#if (MAX_DIRECTIONAL_LIGHT_NUM > 0)\n
for (int i = 0; i < MAX_DIRECTIONAL_LIGHT_NUM; ++i)
{
vec3 lightDirection = normalize(u_DirLightSourceDirection[i] * 2.0);
combinedColor.xyz += computeLighting(normal, -lightDirection, u_DirLightSourceColor[i], 1.0);
}
\n#endif\n
// Point light contribution
\n#if (MAX_POINT_LIGHT_NUM > 0)\n
for (int i = 0; i < MAX_POINT_LIGHT_NUM; ++i)
{
vec3 ldir = v_vertexToPointLightDirection[i] * u_PointLightSourceRangeInverse[i];
float attenuation = clamp(1.0 - dot(ldir, ldir), 0.0, 1.0);
combinedColor.xyz += computeLighting(normal, normalize(v_vertexToPointLightDirection[i]), u_PointLightSourceColor[i], attenuation);
}
\n#endif\n
// Spot light contribution
\n#if (MAX_SPOT_LIGHT_NUM > 0)\n
for (int i = 0; i < MAX_SPOT_LIGHT_NUM; ++i)
{
// Compute range attenuation
vec3 ldir = v_vertexToSpotLightDirection[i] * u_SpotLightSourceRangeInverse[i];
float attenuation = clamp(1.0 - dot(ldir, ldir), 0.0, 1.0);
vec3 vertexToSpotLightDirection = normalize(v_vertexToSpotLightDirection[i]);
vec3 spotLightDirection = normalize(u_SpotLightSourceDirection[i] * 2.0);
// "-lightDirection" is used because light direction points in opposite direction to spot direction.
float spotCurrentAngleCos = dot(spotLightDirection, -vertexToSpotLightDirection);
// Apply spot attenuation
attenuation *= smoothstep(u_SpotLightSourceOuterAngleCos[i], u_SpotLightSourceInnerAngleCos[i], spotCurrentAngleCos);
combinedColor.xyz += computeLighting(normal, vertexToSpotLightDirection, u_SpotLightSourceColor[i], attenuation);
}
\n#endif\n
\n#if ((MAX_DIRECTIONAL_LIGHT_NUM > 0) || (MAX_POINT_LIGHT_NUM > 0) || (MAX_SPOT_LIGHT_NUM > 0))\n
gl_FragColor = texture2D(CC_Texture0, TextureCoordOut) * u_color * combinedColor;
\n#else\n
gl_FragColor = texture2D(CC_Texture0, TextureCoordOut) * u_color;
\n#endif\n
}
);

View File

@ -0,0 +1,178 @@
const char* cc3D_PositionNormalTex_vert = STRINGIFY(
\n#define MAX_DIRECTIONAL_LIGHT_NUM 1 \n
\n#define MAX_POINT_LIGHT_NUM 1 \n
\n#define MAX_SPOT_LIGHT_NUM 1 \n
\n#define MAX_AMBIENT_LIGHT_NUM 1 \n
\n#if (MAX_POINT_LIGHT_NUM > 0)\n
uniform vec3 u_PointLightSourcePosition[MAX_POINT_LIGHT_NUM];
\n#endif\n
\n#if (MAX_SPOT_LIGHT_NUM > 0)\n
uniform vec3 u_SpotLightSourcePosition[MAX_SPOT_LIGHT_NUM];
\n#endif\n
attribute vec4 a_position;
attribute vec2 a_texCoord;
attribute vec3 a_normal;
varying vec2 TextureCoordOut;
\n#if MAX_POINT_LIGHT_NUM\n
varying vec3 v_vertexToPointLightDirection[MAX_POINT_LIGHT_NUM];
\n#endif\n
\n#if MAX_SPOT_LIGHT_NUM\n
varying vec3 v_vertexToSpotLightDirection[MAX_SPOT_LIGHT_NUM];
\n#endif\n
\n#if ((MAX_DIRECTIONAL_LIGHT_NUM > 0) || (MAX_POINT_LIGHT_NUM > 0) || (MAX_SPOT_LIGHT_NUM > 0))\n
varying vec3 v_normal;
\n#endif\n
void main(void)
{
vec4 ePosition = CC_MVMatrix * a_position;
\n#if (MAX_POINT_LIGHT_NUM > 0)\n
for (int i = 0; i < MAX_POINT_LIGHT_NUM; ++i)
{
v_vertexToPointLightDirection[i] = u_PointLightSourcePosition[i].xyz - ePosition.xyz;
}
\n#endif\n
\n#if (MAX_SPOT_LIGHT_NUM > 0)\n
for (int i = 0; i < MAX_SPOT_LIGHT_NUM; ++i)
{
v_vertexToSpotLightDirection[i] = u_SpotLightSourcePosition[i] - ePosition.xyz;
}
\n#endif\n
\n#if ((MAX_DIRECTIONAL_LIGHT_NUM > 0) || (MAX_POINT_LIGHT_NUM > 0) || (MAX_SPOT_LIGHT_NUM > 0))\n
v_normal = CC_NormalMatrix * a_normal;
\n#endif\n
TextureCoordOut = a_texCoord;
TextureCoordOut.y = 1.0 - TextureCoordOut.y;
gl_Position = CC_PMatrix * ePosition;
}
);
const char* cc3D_SkinPositionNormalTex_vert = STRINGIFY(
\n#define MAX_DIRECTIONAL_LIGHT_NUM 1 \n
\n#define MAX_POINT_LIGHT_NUM 1 \n
\n#define MAX_SPOT_LIGHT_NUM 1 \n
\n#define MAX_AMBIENT_LIGHT_NUM 1 \n
\n#if (MAX_POINT_LIGHT_NUM > 0)\n
uniform vec3 u_PointLightSourcePosition[MAX_POINT_LIGHT_NUM];
\n#endif\n
\n#if (MAX_SPOT_LIGHT_NUM > 0)\n
uniform vec3 u_SpotLightSourcePosition[MAX_SPOT_LIGHT_NUM];
\n#endif\n
attribute vec3 a_position;
attribute vec4 a_blendWeight;
attribute vec4 a_blendIndex;
attribute vec2 a_texCoord;
attribute vec3 a_normal;
const int SKINNING_JOINT_COUNT = 60;
// Uniforms
uniform vec4 u_matrixPalette[SKINNING_JOINT_COUNT * 3];
// Varyings
varying vec2 TextureCoordOut;
\n#if MAX_POINT_LIGHT_NUM\n
varying vec3 v_vertexToPointLightDirection[MAX_POINT_LIGHT_NUM];
\n#endif\n
\n#if MAX_SPOT_LIGHT_NUM\n
varying vec3 v_vertexToSpotLightDirection[MAX_SPOT_LIGHT_NUM];
\n#endif\n
varying vec3 v_normal;
void getPositionAndNormal(out vec4 position, out vec3 normal)
{
float blendWeight = a_blendWeight[0];
int matrixIndex = int (a_blendIndex[0]) * 3;
vec4 matrixPalette1 = u_matrixPalette[matrixIndex] * blendWeight;
vec4 matrixPalette2 = u_matrixPalette[matrixIndex + 1] * blendWeight;
vec4 matrixPalette3 = u_matrixPalette[matrixIndex + 2] * blendWeight;
blendWeight = a_blendWeight[1];
if (blendWeight > 0.0)
{
matrixIndex = int(a_blendIndex[1]) * 3;
matrixPalette1 += u_matrixPalette[matrixIndex] * blendWeight;
matrixPalette2 += u_matrixPalette[matrixIndex + 1] * blendWeight;
matrixPalette3 += u_matrixPalette[matrixIndex + 2] * blendWeight;
}
blendWeight = a_blendWeight[2];
if (blendWeight > 0.0)
{
matrixIndex = int(a_blendIndex[2]) * 3;
matrixPalette1 += u_matrixPalette[matrixIndex] * blendWeight;
matrixPalette2 += u_matrixPalette[matrixIndex + 1] * blendWeight;
matrixPalette3 += u_matrixPalette[matrixIndex + 2] * blendWeight;
}
blendWeight = a_blendWeight[3];
if (blendWeight > 0.0)
{
matrixIndex = int(a_blendIndex[3]) * 3;
matrixPalette1 += u_matrixPalette[matrixIndex] * blendWeight;
matrixPalette2 += u_matrixPalette[matrixIndex + 1] * blendWeight;
matrixPalette3 += u_matrixPalette[matrixIndex + 2] * blendWeight;
}
vec4 p = vec4(a_position, 1.0);
position.x = dot(p, matrixPalette1);
position.y = dot(p, matrixPalette2);
position.z = dot(p, matrixPalette3);
position.w = p.w;
\n#if ((MAX_DIRECTIONAL_LIGHT_NUM > 0) || (MAX_POINT_LIGHT_NUM > 0) || (MAX_SPOT_LIGHT_NUM > 0))\n
vec4 n = vec4(a_normal, 0.0);
normal.x = dot(n, matrixPalette1);
normal.y = dot(n, matrixPalette2);
normal.z = dot(n, matrixPalette3);
\n#endif\n
}
void main()
{
vec4 position;
vec3 normal;
getPositionAndNormal(position, normal);
vec4 ePosition = CC_MVMatrix * position;
\n#if (MAX_POINT_LIGHT_NUM > 0)\n
for (int i = 0; i < MAX_POINT_LIGHT_NUM; ++i)
{
v_vertexToPointLightDirection[i] = u_PointLightSourcePosition[i].xyz- ePosition.xyz;
}
\n#endif\n
\n#if (MAX_SPOT_LIGHT_NUM > 0)\n
for (int i = 0; i < MAX_SPOT_LIGHT_NUM; ++i)
{
v_vertexToSpotLightDirection[i] = u_SpotLightSourcePosition[i] - ePosition.xyz;
}
\n#endif\n
\n#if ((MAX_DIRECTIONAL_LIGHT_NUM > 0) || (MAX_POINT_LIGHT_NUM > 0) || (MAX_SPOT_LIGHT_NUM > 0))\n
v_normal = CC_NormalMatrix * normal;
\n#endif\n
TextureCoordOut = a_texCoord;
TextureCoordOut.y = 1.0 - TextureCoordOut.y;
gl_Position = CC_PMatrix * ePosition;
}
);

View File

@ -74,5 +74,8 @@ NS_CC_BEGIN
#include "ccShader_3D_PositionTex.vert"
#include "ccShader_3D_Color.frag"
#include "ccShader_3D_ColorTex.frag"
#include "ccShader_3D_PositionNormalTex.vert"
#include "ccShader_3D_ColorNormal.frag"
#include "ccShader_3D_ColorNormalTex.frag"
NS_CC_END

View File

@ -73,6 +73,10 @@ extern CC_DLL const GLchar * cc3D_PositionTex_vert;
extern CC_DLL const GLchar * cc3D_SkinPositionTex_vert;
extern CC_DLL const GLchar * cc3D_ColorTex_frag;
extern CC_DLL const GLchar * cc3D_Color_frag;
extern CC_DLL const GLchar * cc3D_PositionNormalTex_vert;
extern CC_DLL const GLchar * cc3D_SkinPositionNormalTex_vert;
extern CC_DLL const GLchar * cc3D_ColorNormalTex_frag;
extern CC_DLL const GLchar * cc3D_ColorNormal_frag;
// end of shaders group
/// @}

View File

@ -351,6 +351,8 @@
"cocos/base/CCIMEDelegate.h",
"cocos/base/CCIMEDispatcher.cpp",
"cocos/base/CCIMEDispatcher.h",
"cocos/base/CCLight.cpp",
"cocos/base/CCLight.h",
"cocos/base/CCMap.h",
"cocos/base/CCNS.cpp",
"cocos/base/CCNS.h",

View File

@ -137,6 +137,7 @@ set(TESTS_SRC
Classes/LabelTest/LabelTest.cpp
Classes/LabelTest/LabelTestNew.cpp
Classes/LayerTest/LayerTest.cpp
Classes/LightTest/LightTest.cpp
Classes/MenuTest/MenuTest.cpp
Classes/MotionStreakTest/MotionStreakTest.cpp
Classes/MutiTouchTest/MutiTouchTest.cpp

View File

@ -0,0 +1,362 @@
#include "LightTest.h"
static int sceneIdx = -1;
static std::function<Layer*()> createFunctions[] =
{
CL(LightTest)
};
#define MAX_LAYER (sizeof(createFunctions) / sizeof(createFunctions[0]))
static Layer* nextSpriteTestAction()
{
sceneIdx++;
sceneIdx = sceneIdx % MAX_LAYER;
auto layer = (createFunctions[sceneIdx])();
return layer;
}
static Layer* backSpriteTestAction()
{
sceneIdx--;
int total = MAX_LAYER;
if( sceneIdx < 0 )
sceneIdx += total;
auto layer = (createFunctions[sceneIdx])();
return layer;
}
static Layer* restartSpriteTestAction()
{
auto layer = (createFunctions[sceneIdx])();
return layer;
}
LightTest::LightTest()
: _directionalLight(nullptr)
, _pointLight(nullptr)
, _spotLight(nullptr)
{
addSprite();
addLights();
scheduleUpdate();
auto s = Director::getInstance()->getWinSize();
auto camera = Camera::createPerspective(60, (GLfloat)s.width/s.height, 1.0f, 1000.0f);
camera->setCameraFlag(CameraFlag::USER1);
camera->setPosition3D(Vec3(0.0, 100, 100));
camera->lookAt(Vec3(0.0, 0.0, 0.0), Vec3(0.0, 1.0, 0.0));
addChild(camera);
TTFConfig ttfConfig("fonts/arial.ttf", 15);
_ambientLightLabel = Label::createWithTTF(ttfConfig,"Ambient Light ON");
_ambientLightLabel->retain();
auto menuItem0 = MenuItemLabel::create(_ambientLightLabel, CC_CALLBACK_1(LightTest::SwitchLight,this,LightType::AMBIENT));
_directionalLightLabel = Label::createWithTTF(ttfConfig,"Directional Light OFF");
_directionalLightLabel->retain();
auto menuItem1 = MenuItemLabel::create(_directionalLightLabel, CC_CALLBACK_1(LightTest::SwitchLight,this,LightType::DIRECTIONAL));
_pointLightLabel = Label::createWithTTF(ttfConfig,"Point Light OFF");
_pointLightLabel->retain();
auto menuItem2 = MenuItemLabel::create(_pointLightLabel, CC_CALLBACK_1(LightTest::SwitchLight,this,LightType::POINT));
_spotLightLabel = Label::createWithTTF(ttfConfig,"Spot Light OFF");
_spotLightLabel->retain();
auto menuItem3 = MenuItemLabel::create(_spotLightLabel, CC_CALLBACK_1(LightTest::SwitchLight,this,LightType::SPOT));
auto menu = Menu::create(menuItem0, menuItem1,menuItem2,menuItem3,NULL);
menu->setPosition(Vec2::ZERO);
menuItem0->setAnchorPoint(Vec2::ANCHOR_TOP_LEFT);
menuItem0->setPosition( Vec2(VisibleRect::left().x, VisibleRect::top().y-50) );
menuItem1->setAnchorPoint(Vec2::ANCHOR_TOP_LEFT);
menuItem1->setPosition( Vec2(VisibleRect::left().x, VisibleRect::top().y-100) );
menuItem2->setAnchorPoint(Vec2::ANCHOR_TOP_LEFT);
menuItem2->setPosition( Vec2(VisibleRect::left().x, VisibleRect::top().y -150));
menuItem3->setAnchorPoint(Vec2::ANCHOR_TOP_LEFT);
menuItem3->setPosition( Vec2(VisibleRect::left().x, VisibleRect::top().y -200));
addChild(menu);
}
LightTest::~LightTest()
{
if (_spotLightLabel)
_spotLightLabel->release();
if (_pointLightLabel)
_pointLightLabel->release();
if (_directionalLightLabel)
_directionalLightLabel->release();
if (_spotLight)
_spotLight->release();
if (_pointLight)
_pointLight->release();
if (_directionalLight)
_directionalLight->release();
if (_ambientLight)
_ambientLight->release();
}
std::string LightTest::title() const
{
return "Light Test";
}
std::string LightTest::subtitle() const
{
return "";
}
void LightTest::restartCallback( Ref* sender )
{
auto s = new LightTestScene();
s->addChild(restartSpriteTestAction());
Director::getInstance()->replaceScene(s);
s->release();
}
void LightTest::nextCallback( Ref* sender )
{
auto s = new LightTestScene();
s->addChild( nextSpriteTestAction() );
Director::getInstance()->replaceScene(s);
s->release();
}
void LightTest::backCallback( Ref* sender )
{
auto s = new LightTestScene();
s->addChild( backSpriteTestAction() );
Director::getInstance()->replaceScene(s);
s->release();
}
void LightTest::onEnter()
{
BaseTest::onEnter();
}
void LightTest::onExit()
{
BaseTest::onExit();
}
void LightTest::addSprite()
{
auto s = Director::getInstance()->getWinSize();
//{
// std::string fileName = "Sprite3DTest/plane.c3b";
// auto sprite = Sprite3D::create(fileName);
// sprite->setRotation3D(Vec3(-90.0, 0.0, 0.0));
// sprite->setScale(5.0f);
// sprite->setPosition(Vec2(0.0, -50.0));
// addChild(sprite);
// sprite->setCameraMask(2);
//}
{
std::string fileName = "Sprite3DTest/orc.c3b";
auto sprite = Sprite3D::create(fileName);
sprite->setRotation3D(Vec3(0.0, 180.0, 0.0));
sprite->setPosition(Vec2(0.0, 0.0));
sprite->setScale(2.0);
auto sp = Sprite3D::create("Sprite3DTest/axe.c3b");
sprite->getAttachNode("Bip001 R Hand")->addChild(sp);
auto animation = Animation3D::create(fileName);
if (animation)
{
auto animate = Animate3D::create(animation);
sprite->runAction(RepeatForever::create(animate));
}
addChild(sprite);
sprite->setCameraMask(2);
}
{
std::string fileName = "Sprite3DTest/sphere.c3b";
auto sprite = Sprite3D::create(fileName);
sprite->setPosition(Vec2(30.0, 0.0));
addChild(sprite);
sprite->setCameraMask(2);
}
{
std::string fileName = "Sprite3DTest/sphere.c3b";
auto sprite = Sprite3D::create(fileName);
sprite->setScale(0.5f);
sprite->setPosition(Vec2(-50.0, 0.0));
addChild(sprite);
sprite->setCameraMask(2);
}
{
std::string fileName = "Sprite3DTest/sphere.c3b";
auto sprite = Sprite3D::create(fileName);
sprite->setScale(0.5f);
sprite->setPosition(Vec2(-30.0, 10.0));
addChild(sprite);
sprite->setCameraMask(2);
}
}
void LightTest::addLights()
{
auto s = Director::getInstance()->getWinSize();
_ambientLight = AmbientLight::create(Color3B(200, 200, 200));
_ambientLight->retain();
_ambientLight->setEnabled(true);
addChild(_ambientLight);
_ambientLight->setCameraMask(2);
_directionalLight = DirectionLight::create(Vec3(-1.0f, -1.0f, 0.0f), Color3B(200, 200, 200));
_directionalLight->retain();
_directionalLight->setEnabled(false);
addChild(_directionalLight);
_directionalLight->setCameraMask(2);
_pointLight = PointLight::create(Vec3(0.0f, 0.0f, 0.0f), Color3B(200, 200, 200), 10000.0f);
_pointLight->retain();
_pointLight->setEnabled(false);
addChild(_pointLight);
_pointLight->setCameraMask(2);
_spotLight = SpotLight::create(Vec3(-1.0f, -1.0f, 0.0f), Vec3(0.0f, 0.0f, 0.0f), Color3B(200, 200, 200), 0.0, 0.5, 10000.0f);
_spotLight->retain();
_spotLight->setEnabled(false);
addChild(_spotLight);
_spotLight->setCameraMask(2);
{
auto tintto1 = TintTo::create(4, 0, 0, 255);
auto tintto2 = TintTo::create(4, 0, 255, 0);
auto tintto3 = TintTo::create(4, 255, 0, 0);
auto tintto4 = TintTo::create(4, 255, 255, 255);
auto seq = Sequence::create(tintto1,tintto2, tintto3, tintto4, NULL);
_ambientLight->runAction(RepeatForever::create(seq));
}
{
auto tintto1 = TintTo::create(4, 255, 0, 0);
auto tintto2 = TintTo::create(4, 0, 255, 0);
auto tintto3 = TintTo::create(4, 0, 0, 255);
auto tintto4 = TintTo::create(4, 255, 255, 255);
auto seq = Sequence::create(tintto1,tintto2, tintto3, tintto4, NULL);
_directionalLight->runAction(RepeatForever::create(seq));
}
{
auto tintto1 = TintTo::create(4, 255, 0, 0);
auto tintto2 = TintTo::create(4, 0, 255, 0);
auto tintto3 = TintTo::create(4, 0, 0, 255);
auto tintto4 = TintTo::create(4, 255, 255, 255);
auto seq = Sequence::create(tintto2, tintto1, tintto3, tintto4, NULL);
_pointLight->runAction(RepeatForever::create(seq));
}
{
auto tintto1 = TintTo::create(4, 255, 0, 0);
auto tintto2 = TintTo::create(4, 0, 255, 0);
auto tintto3 = TintTo::create(4, 0, 0, 255);
auto tintto4 = TintTo::create(4, 255, 255, 255);
auto seq = Sequence::create(tintto3, tintto2, tintto1, tintto4, NULL);
_spotLight->runAction(RepeatForever::create(seq));
}
}
void LightTest::update( float delta )
{
static float angleDelta = 0.0;
if (_directionalLight)
{
_directionalLight->setRotation3D(Vec3(-45.0, -CC_RADIANS_TO_DEGREES(angleDelta), 0.0f));
}
if (_pointLight)
{
_pointLight->setPositionX(100.0f * cosf(angleDelta + 2.0 * delta));
_pointLight->setPositionY(100.0f);
_pointLight->setPositionZ(100.0f * sinf(angleDelta + 2.0 * delta));
}
if (_spotLight)
{
_spotLight->setPositionX(100.0f * cosf(angleDelta + 4.0 * delta));
_spotLight->setPositionY(100.0f);
_spotLight->setPositionZ(100.0f * sinf(angleDelta + 4.0 * delta));
_spotLight->setDirection(-Vec3(cosf(angleDelta + 4.0 * delta), 1.0, sinf(angleDelta + 4.0 * delta)));
}
angleDelta += delta;
BaseTest::update(delta);
}
void LightTest::SwitchLight( Ref* sender, LightType lightType )
{
switch (lightType)
{
case LightType::AMBIENT:
{
char str[32];
bool isON = !_ambientLight->isEnabled();
sprintf(str, "Ambient Light %s", isON == true? "ON":"OFF");
_ambientLight->setEnabled(isON);
_ambientLightLabel->setString(str);
}
break;
case LightType::DIRECTIONAL:
{
char str[32];
bool isON = !_directionalLight->isEnabled();
sprintf(str, "Directional Light %s", isON == true? "ON":"OFF");
_directionalLight->setEnabled(isON);
_directionalLightLabel->setString(str);
}
break;
case LightType::POINT:
{
char str[32];
bool isON = !_pointLight->isEnabled();
sprintf(str, "Point Light %s", isON == true? "ON":"OFF");
_pointLight->setEnabled(isON);
_pointLightLabel->setString(str);
}
break;
case LightType::SPOT:
{
char str[32];
bool isON = !_spotLight->isEnabled();
sprintf(str, "Spot Light %s", isON == true? "ON":"OFF");
_spotLight->setEnabled(isON);
_spotLightLabel->setString(str);
}
break;
default:
break;
}
}
void LightTestScene::runThisTest()
{
auto layer = nextSpriteTestAction();
addChild(layer);
Director::getInstance()->replaceScene(this);
}
LightTestScene::LightTestScene()
{
}

View File

@ -0,0 +1,79 @@
/****************************************************************************
Copyright (c) 2013 cocos2d-x.org
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#ifndef _LIGHT_TEST_H_
#define _LIGHT_TEST_H_
#include "../testBasic.h"
#include "../BaseTest.h"
#include "base/CCLight.h"
class LightTest : public BaseTest
{
public:
CREATE_FUNC(LightTest);
LightTest();
virtual ~LightTest();
virtual std::string title() const;
virtual std::string subtitle() const;
virtual void restartCallback(Ref* sender);
virtual void nextCallback(Ref* sender);
virtual void backCallback(Ref* sender);
virtual void onEnter() override;
virtual void onExit() override;
virtual void update(float delta);
void SwitchLight(Ref* sender, LightType lightType);
private:
void addSprite();
void addLights();
private:
AmbientLight *_ambientLight;
DirectionLight *_directionalLight;
PointLight *_pointLight;
SpotLight *_spotLight;
Label *_ambientLightLabel;
Label *_directionalLightLabel;
Label *_pointLightLabel;
Label *_spotLightLabel;
};
class LightTestScene : public TestScene
{
public:
LightTestScene();
virtual void runThisTest();
};
#endif

View File

@ -29,6 +29,7 @@
#include "3d/CCAttachNode.h"
#include "3d/CCRay.h"
#include "3d/CCSprite3D.h"
#include "base/CCLight.h"
#include "renderer/CCVertexIndexBuffer.h"
#include "DrawNode3D.h"
@ -309,6 +310,11 @@ void Sprite3DTestScene::runThisTest()
Director::getInstance()->replaceScene(this);
}
Sprite3DTestScene::Sprite3DTestScene()
{
}
static int tuple_sort( const std::tuple<ssize_t,Effect3D*,CustomCommand> &tuple1, const std::tuple<ssize_t,Effect3D*,CustomCommand> &tuple2 )
{
return std::get<0>(tuple1) < std::get<0>(tuple2);
@ -552,7 +558,7 @@ void Effect3DOutline::draw(const Mat4 &transform)
_glProgramState->apply(transform);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mesh->getIndexBuffer());
glDrawElements(mesh->getPrimitiveType(), mesh->getIndexCount(), mesh->getIndexFormat(), 0);
glDrawElements(mesh->getPrimitiveType(), (GLsizei)mesh->getIndexCount(), mesh->getIndexFormat(), 0);
CC_INCREMENT_GL_DRAWN_BATCHES_AND_VERTICES(1, mesh->getIndexCount());
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);

View File

@ -324,6 +324,7 @@ protected:
class Sprite3DTestScene : public TestScene
{
public:
Sprite3DTestScene();
virtual void runThisTest();
};

View File

@ -70,6 +70,7 @@ Controller g_aTestNames[] = {
{ "Node: Label - New API", [](){return new AtlasTestSceneNew(); } },
{ "Node: Label - Old API", [](){return new AtlasTestScene(); } },
{ "Node: Layer", [](){return new LayerTestScene();} },
{ "Node: Light", [](){return new LightTestScene();} },
{ "Node: Menu", [](){return new MenuTestScene();} },
{ "Node: MotionStreak", [](){return new MotionStreakTestScene();} },
{ "Node: Node", [](){return new CocosNodeTestScene();} },

View File

@ -74,6 +74,7 @@
#include "Sprite3DTest/Sprite3DTest.h"
#include "Camera3DTest/Camera3DTest.h"
#include "BillBoardTest/BillBoardTest.h"
#include "LightTest/LightTest.h"
#include "OpenURLTest/OpenURLTest.h"

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

View File

@ -16,6 +16,12 @@
<false/>
<key>cocos2d.x.testcpp.autorun</key>
<false/>
<key>cocos2d.x.3d.max_dir_light_in_shader</key>
<integer>1</integer>
<key>cocos2d.x.3d.max_point_light_in_shader</key>
<integer>1</integer>
<key>cocos2d.x.3d.max_spot_light_in_shader</key>
<integer>1</integer>
</dict>
<key>metadata</key>
<dict>

View File

@ -139,6 +139,7 @@ LOCAL_SRC_FILES := main.cpp \
../../Classes/LabelTest/LabelTest.cpp \
../../Classes/LabelTest/LabelTestNew.cpp \
../../Classes/LayerTest/LayerTest.cpp \
../../Classes/LightTest/LightTest.cpp \
../../Classes/MenuTest/MenuTest.cpp \
../../Classes/MotionStreakTest/MotionStreakTest.cpp \
../../Classes/MutiTouchTest/MutiTouchTest.cpp \

View File

@ -1,4 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
@ -168,6 +168,7 @@
<ClCompile Include="..\Classes\FileUtilsTest\FileUtilsTest.cpp" />
<ClCompile Include="..\Classes\InputTest\MouseTest.cpp" />
<ClCompile Include="..\Classes\LabelTest\LabelTestNew.cpp" />
<ClCompile Include="..\Classes\LightTest\LightTest.cpp" />
<ClCompile Include="..\Classes\NewEventDispatcherTest\NewEventDispatcherTest.cpp" />
<ClCompile Include="..\Classes\NewRendererTest\NewRendererTest.cpp" />
<ClCompile Include="..\Classes\PerformanceTest\PerformanceAllocTest.cpp" />
@ -358,6 +359,7 @@
<ClInclude Include="..\Classes\FileUtilsTest\FileUtilsTest.h" />
<ClInclude Include="..\Classes\InputTest\MouseTest.h" />
<ClInclude Include="..\Classes\LabelTest\LabelTestNew.h" />
<ClInclude Include="..\Classes\LightTest\LightTest.h" />
<ClInclude Include="..\Classes\NewEventDispatcherTest\NewEventDispatcherTest.h" />
<ClInclude Include="..\Classes\NewRendererTest\NewRendererTest.h" />
<ClInclude Include="..\Classes\PerformanceTest\PerformanceAllocTest.h" />

View File

@ -325,6 +325,9 @@
<Filter Include="Classes\Camera3DTest">
<UniqueIdentifier>{7f85be1c-98c5-4412-afc5-6f39ae1452a7}</UniqueIdentifier>
</Filter>
<Filter Include="Classes\LightTest">
<UniqueIdentifier>{9befe67d-c725-4807-885f-edee45f95951}</UniqueIdentifier>
</Filter>
<Filter Include="Classes\BillBoardTest">
<UniqueIdentifier>{54a30b92-ddfb-420e-908b-886c23c21cf1}</UniqueIdentifier>
</Filter>
@ -870,6 +873,9 @@
<ClCompile Include="..\Classes\BillBoardTest\BillBoardTest.cpp">
<Filter>Classes\BillBoardTest</Filter>
</ClCompile>
<ClCompile Include="..\Classes\LightTest\LightTest.cpp">
<Filter>Classes\LightTest</Filter>
</ClCompile>
<ClCompile Include="..\Classes\UITest\CocoStudioGUITest\UIWebViewTest\UIWebViewTest.cpp">
<Filter>Classes\UITest\CocostudioGUISceneTest\UIWebViewTest</Filter>
</ClCompile>
@ -1610,6 +1616,9 @@
<ClInclude Include="..\Classes\BillBoardTest\BillBoardTest.h">
<Filter>Classes\BillBoardTest</Filter>
</ClInclude>
<ClInclude Include="..\Classes\LightTest\LightTest.h">
<Filter>Classes\LightTest</Filter>
</ClInclude>
<ClInclude Include="..\Classes\UITest\CocoStudioGUITest\UIWebViewTest\UIWebViewTest.h">
<Filter>Classes\UITest\CocostudioGUISceneTest\UIWebViewTest</Filter>
</ClInclude>

View File

@ -126,7 +126,7 @@ skip = Node::[setGLServerState description getUserObject .*UserData getGLServerS
TurnOffTiles::[shuffle],
LabelTTF::[*],
LabelBMFont::[*],
Scene::[getCameras],
Scene::[getCameras getLights],
Animate3D::[*],
Sprite3D::[*],
AttachNode::[*],
@ -139,7 +139,12 @@ skip = Node::[setGLServerState description getUserObject .*UserData getGLServerS
Bone3D::[*],
Device::[getTextureDataForText],
BillBoard::[*],
Camera::[unproject]
Camera::[unproject],
BaseLight3D::[*],
DirectionLight3D::[*],
PointLight3D::[*],
SpotLight3D::[*],
AmbientLight3D::[*]
rename_functions = SpriteFrameCache::[addSpriteFramesWithFile=addSpriteFrames getSpriteFrameByName=getSpriteFrame],
ProgressTimer::[setReverseProgress=setReverseDirection],