diff --git a/AUTHORS b/AUTHORS index 20e52a271b..c309c66ac9 100644 --- a/AUTHORS +++ b/AUTHORS @@ -64,7 +64,13 @@ Developers: folecr contribute for Android module building - + + Yannick Loriot + author of CCControlExtension of cocos2d-iphone port. + + Angus Comrie + contributes cocos2d-x port of CCControlExtension + Cocos2d-x can not grow so fast without the active community. Thanks to all developers who report & trace bugs, dicuss the engine usage in forum & QQ groups! Special thanks to Ricardo Quesada for giving us lots of guidances & suggestions. diff --git a/HelloWorld/ios/HelloWorld.xcodeproj/project.pbxproj.REMOVED.git-id b/HelloWorld/ios/HelloWorld.xcodeproj/project.pbxproj.REMOVED.git-id index 9f3249cea0..e2b45e9e43 100644 --- a/HelloWorld/ios/HelloWorld.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/HelloWorld/ios/HelloWorld.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -ba02d3744870cd69d88ef40bfe303f99d85313a6 \ No newline at end of file +2521e728e0473ff63635745b44a19f8e9cdcac48 \ No newline at end of file diff --git a/cocos2dx/Android.mk b/cocos2dx/Android.mk index e21114d443..d527e3cc09 100644 --- a/cocos2dx/Android.mk +++ b/cocos2dx/Android.mk @@ -22,6 +22,7 @@ actions/CCActionManager.cpp \ actions/CCActionPageTurn3D.cpp \ actions/CCActionProgressTimer.cpp \ actions/CCActionTiledGrid.cpp \ +actions/CCActionTween.cpp \ base_nodes/CCAtlasNode.cpp \ base_nodes/CCNode.cpp \ cocoa/CCAffineTransform.cpp \ @@ -38,7 +39,19 @@ cocos2d.cpp \ CCDirector.cpp \ effects/CCGrabber.cpp \ effects/CCGrid.cpp \ -extensions/CCNotificationCenter.cpp \ +extensions/CCNotificationCenter/CCNotificationCenter.cpp \ +extensions/CCControlExtension/CCControl.cpp \ +extensions/CCControlExtension/CCControlButton.cpp \ +extensions/CCControlExtension/CCControlColourPicker.cpp \ +extensions/CCControlExtension/CCControlHuePicker.cpp \ +extensions/CCControlExtension/CCControlSaturationBrightnessPicker.cpp \ +extensions/CCControlExtension/CCControlSlider.cpp \ +extensions/CCControlExtension/CCControlSwitch.cpp \ +extensions/CCControlExtension/CCControlUtils.cpp \ +extensions/CCControlExtension/CCInvocation.cpp \ +extensions/CCControlExtension/CCMenuPassive.cpp \ +extensions/CCControlExtension/CCScale9Sprite.cpp \ +extensions/CCControlExtension/CCSpacer.cpp \ kazmath/src/aabb.c \ kazmath/src/mat3.c \ kazmath/src/mat4.c \ diff --git a/cocos2dx/CCDirector.cpp b/cocos2dx/CCDirector.cpp index 16a0d477b3..7291846acb 100644 --- a/cocos2dx/CCDirector.cpp +++ b/cocos2dx/CCDirector.cpp @@ -49,7 +49,7 @@ THE SOFTWARE. #include "CCAnimationCache.h" #include "CCTouch.h" #include "CCUserDefault.h" -#include "extensions/CCNotificationCenter.h" +#include "extensions/CCNotificationCenter/CCNotificationCenter.h" #include "ccGLStateCache.h" #include "CCShaderCache.h" #include "kazmath/kazmath.h" diff --git a/cocos2dx/actions/CCActionTween.cpp b/cocos2dx/actions/CCActionTween.cpp new file mode 100644 index 0000000000..4f00a89975 --- /dev/null +++ b/cocos2dx/actions/CCActionTween.cpp @@ -0,0 +1,75 @@ +/**************************************************************************** +Copyright (c) 2010-2011 cocos2d-x.org +Copyright 2009 lhunath (Maarten Billemont) + +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. +****************************************************************************/ + +#include "CCActionTween.h" + +NS_CC_BEGIN + +CCActionTween* CCActionTween::actionWithDuration(ccTime aDuration, const char* key, float from, float to) +{ + CCActionTween* pRet = new CCActionTween(); + if (pRet && pRet->initWithDuration(aDuration, key, from, to)) + { + pRet->autorelease(); + } + else + { + CC_SAFE_DELETE(pRet); + } + return pRet; +} + +bool CCActionTween::initWithDuration(ccTime aDuration, const char* key, float from, float to) +{ + if (CCActionInterval::initWithDuration(aDuration)) + { + key_ = key; + to_ = to; + from_ = from; + return true; + } + + return false; +} + +void CCActionTween::startWithTarget(CCNode *pTarget) +{ + CCAssert(dynamic_cast(pTarget), "target must implement CCActionTweenDelegate"); + CCActionInterval::startWithTarget(pTarget); + delta_ = to_ - from_; +} + +void CCActionTween::update(ccTime dt) +{ + dynamic_cast(m_pTarget)->updateTweenAction(to_ - delta_ * (1 - dt), key_.c_str()); +} + +CCActionInterval* CCActionTween::reverse() +{ + return CCActionTween::actionWithDuration(m_fDuration, key_.c_str(), to_, from_); +} + + +NS_CC_END diff --git a/cocos2dx/cocoa/CCDictionary.cpp b/cocos2dx/cocoa/CCDictionary.cpp index 004088bc13..79e4a727c1 100644 --- a/cocos2dx/cocoa/CCDictionary.cpp +++ b/cocos2dx/cocoa/CCDictionary.cpp @@ -193,6 +193,10 @@ void CCDictionary::setObject(CCObject* pObject, int key) void CCDictionary::removeObjectForKey(const CCString& key) { + if (m_eOldDictType == kCCDictUnknown) + { + return; + } CCAssert(m_eDictType == kCCDictStr, "this dictionary does not use string as its key"); CCAssert(key.length() > 0, "Invalid Argument!"); CCDictElement *pElement = NULL; @@ -202,6 +206,10 @@ void CCDictionary::removeObjectForKey(const CCString& key) void CCDictionary::removeObjectForKey(int key) { + if (m_eOldDictType == kCCDictUnknown) + { + return; + } CCAssert(m_eDictType == kCCDictInt, "this dictionary does not use integer as its key"); CCDictElement *pElement = NULL; HASH_FIND_INT(m_pElements, &key, pElement); diff --git a/cocos2dx/extensions/CCControlExtension/CCControl.cpp b/cocos2dx/extensions/CCControlExtension/CCControl.cpp new file mode 100644 index 0000000000..b1afc2ea15 --- /dev/null +++ b/cocos2dx/extensions/CCControlExtension/CCControl.cpp @@ -0,0 +1,302 @@ +/* + * CCControl.m + * + * Copyright 2011 Yannick Loriot. + * http://yannickloriot.com + * + * 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. + * + * + * converted to c++ / cocos2d-x by Angus C + */ + +#include "CCControl.h" +#include "CCDirector.h" +#include "CCTouchDispatcher.h" +#include "CCMenu.h" +#include "CCTouch.h" + +NS_CC_BEGIN + +CCControl::CCControl() +{ + +} + +bool CCControl::init() +{ + if (CCLayer::init()) + { + //this->setIsTouchEnabled(true); + //m_bIsTouchEnabled=true; + // Initialise instance variables + m_nState=CCControlStateNormal; + m_bEnabled=true; + m_bSelected=false; + m_bHighlighted=false; + + // Set the touch dispatcher priority by default to 1 + m_nDefaultTouchPriority = 1; + this->setDefaultTouchPriority(m_nDefaultTouchPriority); + // Initialise the tables + dispatchTable=new CCDictionary(); + //dispatchTable->autorelease(); + // dispatchTable_ = [[NSMutableDictionary alloc] initWithCapacity:1]; + return true; + } + else + return false; +} + +CCControl::~CCControl() +{ + CC_SAFE_RELEASE(dispatchTable); +} + + //Menu - Events +void CCControl::registerWithTouchDispatcher() +{ + CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this, kCCMenuHandlerPriority, true); +} + +void CCControl::onEnter() +{ + //CCTouchDispatcher::sharedDispatcher()->addTargetedDelegate(this, m_nDefaultTouchPriority, true); + CCLayer::onEnter(); +} + +void CCControl::onExit() +{ + //CCTouchDispatcher::sharedDispatcher()->removeDelegate(this); + CCLayer::onExit(); +} + +void CCControl::sendActionsForControlEvents(CCControlEvent controlEvents) +{ + // For each control events + for (int i = 0; i < CONTROL_EVENT_TOTAL_NUMBER; i++) + { + // If the given controlEvents bitmask contains the curent event + if ((controlEvents & (1 << i))) + { + // Call invocations + // + CCArray* invocationList=CCControl::dispatchListforControlEvent(1<invoke(this); + } + } + } +} +void CCControl::addTargetWithActionForControlEvents(CCObject* target, SEL_MenuHandler action, CCControlEvent controlEvents) +{ + // For each control events + for (int i = 0; i < CONTROL_EVENT_TOTAL_NUMBER; i++) + { + // If the given controlEvents bitmask contains the curent event + if ((controlEvents & (1 << i))) + { + CCControl::addTargetWithActionForControlEvent(target, action, 1<autorelease(); + // Add the invocation into the dispatch list for the given control event + CCArray* eventInvocationList = dispatchListforControlEvent(controlEvent); + eventInvocationList->addObject(invocation); +} + +void CCControl::removeTargetWithActionForControlEvents(CCObject* target, SEL_MenuHandler action, CCControlEvent controlEvents) +{ + // For each control events + for (int i = 0; i < CONTROL_EVENT_TOTAL_NUMBER; i++) + { + // If the given controlEvents bitmask contains the curent event + if ((controlEvents & (1 << i))) + { + removeTargetWithActionForControlEvent(target, action, 1 << i); + } + } +} + +/** + * Removes a target and action for a particular event from an internal dispatch + * table. + * + * @param target The target object—that is, the object to which the action + * message is sent. Pass nil to remove all targets paired with action and the + * specified control events. + * @param action A selector identifying an action message. Pass NULL to remove + * all action messages paired with target. + * @param controlEvent A control event for which the action message is sent. + * See "CCControlEvent" for constants. + */ +void CCControl::removeTargetWithActionForControlEvent(CCObject* target, SEL_MenuHandler action, CCControlEvent controlEvent) +{ + // Retrieve all invocations for the given control event + // + CCArray *eventInvocationList=dispatchListforControlEvent(controlEvent); + + //remove all invocations if the target and action are null + //TODO: should the invocations be deleted, or just removed from the array? Won't that cause issues if you add a single invocation for multiple events? + bool bDeleteObjects=true; + if (target == NULL && action == NULL) + { + //remove objects + eventInvocationList->removeAllObjects(); + } + else + { + //normally we would use a predicate, but this won't work here. Have to do it manually + CCObject* pObj = NULL; + CCARRAY_FOREACH(eventInvocationList, pObj) + { + CCInvocation *invocation = (CCInvocation*)pObj; + bool shouldBeRemoved=true; + if (target) + shouldBeRemoved=(target==invocation->getTarget()); + if (action) + shouldBeRemoved=(shouldBeRemoved && (action==invocation->getAction())); + // Remove the corresponding invocation object + if (shouldBeRemoved) + eventInvocationList->removeObject(invocation, bDeleteObjects); + } + } +} + + +//CRGBA protocol +void CCControl::setColor(const ccColor3B& color) +{ + m_tColor=color; + CCObject* child; + CCArray* children=getChildren(); + CCARRAY_FOREACH(children, child) + { + CCRGBAProtocol* pNode = dynamic_cast(child); + if (pNode) + { + pNode->setColor(m_tColor); + } + } +} + +const ccColor3B& CCControl::getColor(void) +{ + return m_tColor; +} + + +void CCControl::setOpacity(GLubyte opacity) +{ + m_cOpacity = opacity; + + CCObject* child; + CCArray* children=getChildren(); + CCARRAY_FOREACH(children, child) + { + CCRGBAProtocol* pNode = dynamic_cast(child); + if (pNode) + { + pNode->setOpacity(opacity); + } + } + +} + +GLubyte CCControl::getOpacity() +{ + return m_cOpacity; +} + + +void CCControl::setIsOpacityModifyRGB(bool opacityModifyRGB) +{ + m_bIsOpacityModifyRGB=opacityModifyRGB; + CCObject* child; + CCArray* children=getChildren(); + CCARRAY_FOREACH(children, child) + { + CCRGBAProtocol* pNode = dynamic_cast(child); + if (pNode) + { + pNode->setIsOpacityModifyRGB(opacityModifyRGB); + } + } +} + +bool CCControl::getIsOpacityModifyRGB() +{ + return m_bIsOpacityModifyRGB; +} + + +CCPoint CCControl::getTouchLocation(CCTouch* touch) +{ + CCPoint touchLocation=touch->locationInView();; // Get the touch position + touchLocation = CCDirector::sharedDirector()->convertToGL(touchLocation); // Convert the position to GL space + touchLocation = this->getParent()->convertToNodeSpace(touchLocation); // Convert to the node space of this class + + return touchLocation; +} + +bool CCControl::isTouchInside(CCTouch* touch) +{ + CCPoint touchLocation=getTouchLocation(touch); + CCRect bBox=boundingBox(); + return CCRect::CCRectContainsPoint(bBox, touchLocation); +} + +CCArray* CCControl::dispatchListforControlEvent(CCControlEvent controlEvent) +{ + CCArray* invocationList = (CCArray*)dispatchTable->objectForKey(controlEvent); + + // If the invocation list does not exist for the dispatch table, we create it + if (invocationList == NULL) + { + invocationList = CCArray::arrayWithCapacity(1); + dispatchTable->setObject(invocationList, controlEvent); + } + return invocationList; +} + +NS_CC_END diff --git a/cocos2dx/extensions/CCControlExtension/CCControl.h b/cocos2dx/extensions/CCControlExtension/CCControl.h new file mode 100644 index 0000000000..f2bc114b96 --- /dev/null +++ b/cocos2dx/extensions/CCControlExtension/CCControl.h @@ -0,0 +1,211 @@ +/* + * CCControl.h + * + * Copyright 2011 Yannick Loriot. + * http://yannickloriot.com + * + * 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. + * + * Converted to c++ / cocos2d-x by Angus C + */ + + +#ifndef __CCCONTROL_H__ +#define __CCCONTROL_H__ + +#include "CCInvocation.h" +#include "CCControlUtils.h" +#include "CCLayer.h" + +NS_CC_BEGIN + +class CCInvocation; + +/** Number of kinds of control event. */ +#define CONTROL_EVENT_TOTAL_NUMBER 9 + +/** Kinds of possible events for the control objects. */ +enum +{ + CCControlEventTouchDown = 1 << 0, // A touch-down event in the control. + CCControlEventTouchDragInside = 1 << 1, // An event where a finger is dragged inside the bounds of the control. + CCControlEventTouchDragOutside = 1 << 2, // An event where a finger is dragged just outside the bounds of the control. + CCControlEventTouchDragEnter = 1 << 3, // An event where a finger is dragged into the bounds of the control. + CCControlEventTouchDragExit = 1 << 4, // An event where a finger is dragged from within a control to outside its bounds. + CCControlEventTouchUpInside = 1 << 5, // A touch-up event in the control where the finger is inside the bounds of the control. + CCControlEventTouchUpOutside = 1 << 6, // A touch-up event in the control where the finger is outside the bounds of the control. + CCControlEventTouchCancel = 1 << 7, // A system event canceling the current touches for the control. + CCControlEventValueChanged = 1 << 8 // A touch dragging or otherwise manipulating a control, causing it to emit a series of different values. +}; +typedef unsigned int CCControlEvent; + +/** The possible state for a control. */ +enum +{ + CCControlStateNormal = 1 << 0, // The normal, or default state of a control—that is, enabled but neither selected nor highlighted. + CCControlStateHighlighted = 1 << 1, // Highlighted state of a control. A control enters this state when a touch down, drag inside or drag enter is performed. You can retrieve and set this value through the highlighted property. + CCControlStateDisabled = 1 << 2, // Disabled state of a control. This state indicates that the control is currently disabled. You can retrieve and set this value through the enabled property. + CCControlStateSelected = 1 << 3, // Selected state of a control. This state indicates that the control is currently selected. You can retrieve and set this value through the selected property. + CCControlStateInitial = 1 << 3 +}; +typedef unsigned int CCControlState; + +/* + * @class + * CCControl is inspired by the UIControl API class from the UIKit library of + * CocoaTouch. It provides a base class for control CCSprites such as CCButton + * or CCSlider that convey user intent to the application. + * + * The goal of CCControl is to define an interface and base implementation for + * preparing action messages and initially dispatching them to their targets when + * certain events occur. + * + * To use the CCControl you have to subclass it. + */ +class CC_DLL CCControl : public CCLayer, public CCRGBAProtocol +{ + + //CCRGBAProtocol + CC_PROPERTY(GLubyte, m_cOpacity, Opacity); + CC_PROPERTY_PASS_BY_REF(ccColor3B, m_tColor, Color); + CC_PROPERTY(bool, m_bIsOpacityModifyRGB, IsOpacityModifyRGB); + + /** Changes the priority of the button. The lower the number, the higher the priority. */ + CC_SYNTHESIZE(int, m_nDefaultTouchPriority, DefaultTouchPriority); + /** The current control state constant. */ + CC_SYNTHESIZE_READONLY(CCControlState, m_nState, State); + /** Tells whether the control is enabled. */ + CC_SYNTHESIZE(bool, m_bEnabled, IsEnabled); + /** A Boolean value that determines the control’s selected state. */ + CC_SYNTHESIZE(bool, m_bSelected, IsSelected); + /** A Boolean value that determines whether the control is highlighted. */ + CC_SYNTHESIZE(bool, m_bHighlighted, IsHighlighted); + + protected: + // CCControlState, CCArray + CCDictionary* dispatchTable; + + + +public: + CCControl(); + virtual bool init(void); + virtual ~CCControl(); + + + virtual void onEnter(); + virtual void onExit(); + virtual void registerWithTouchDispatcher(); + + /** + * Sends action messages for the given control events. + * + * @param controlEvents A bitmask whose set flags specify the control events for + * which action messages are sent. See "CCControlEvent" for bitmask constants. + */ + virtual void sendActionsForControlEvents(CCControlEvent controlEvents); + + /** + * Adds a target and action for a particular event (or events) to an internal + * dispatch table. + * The action message may optionnaly include the sender and the event as + * parameters, in that order. + * When you call this method, target is not retained. + * + * @param target The target object—that is, the object to which the action + * message is sent. It cannot be nil. The target is not retained. + * @param action A selector identifying an action message. It cannot be NULL. + * @param controlEvents A bitmask specifying the control events for which the + * action message is sent. See "CCControlEvent" for bitmask constants. + */ + virtual void addTargetWithActionForControlEvents(CCObject* target, SEL_MenuHandler action, CCControlEvent controlEvents); + + /** + * Removes a target and action for a particular event (or events) from an + * internal dispatch table. + * + * @param target The target object—that is, the object to which the action + * message is sent. Pass nil to remove all targets paired with action and the + * specified control events. + * @param action A selector identifying an action message. Pass NULL to remove + * all action messages paired with target. + * @param controlEvents A bitmask specifying the control events associated with + * target and action. See "CCControlEvent" for bitmask constants. + */ + virtual void removeTargetWithActionForControlEvents(CCObject* target, SEL_MenuHandler action, CCControlEvent controlEvents); + + /** + * Returns a point corresponding to the touh location converted into the + * control space coordinates. + * @param touch A CCTouch object that represents a touch. + */ + virtual CCPoint getTouchLocation(CCTouch* touch); + + + /** + * Returns a boolean value that indicates whether a touch is inside the bounds + * of the receiver. The given touch must be relative to the world. + * + * @param touch A CCTouch object that represents a touch. + * + * @return YES whether a touch is inside the receiver’s rect. + */ + virtual bool isTouchInside(CCTouch * touch); + + +protected: + /** + * Returns an CCInvocation object able to construct messages using a given + * target-action pair. (The invocation may optionnaly include the sender and + * the event as parameters, in that order) + * + * @param target The target object. + * @param action A selector identifying an action message. + * @param controlEvent A control events for which the action message is sent. + * See "CCControlEvent" for constants. + * + * @return an CCInvocation object able to construct messages using a given + * target-action pair. + */ + CCInvocation* invocationWithTargetAndActionForControlEvent(CCObject* target, SEL_MenuHandler action, CCControlEvent controlEvent); + + + + /** + * Returns the CCInvocation list for the given control event. If the list does + * not exist, it'll create an empty array before returning it. + * + * @param controlEvent A control events for which the action message is sent. + * See "CCControlEvent" for constants. + * + * @return the CCInvocation list for the given control event. + */ + // + CCArray* dispatchListforControlEvent(CCControlEvent controlEvent); +public: + void addTargetWithActionForControlEvent(CCObject* target, SEL_MenuHandler action, CCControlEvent controlEvent); + void removeTargetWithActionForControlEvent(CCObject* target, SEL_MenuHandler action, CCControlEvent controlEvent); + + LAYER_NODE_FUNC(CCControl); + +}; + +NS_CC_END + +#endif \ No newline at end of file diff --git a/cocos2dx/extensions/CCControlExtension/CCControlButton.cpp b/cocos2dx/extensions/CCControlExtension/CCControlButton.cpp new file mode 100644 index 0000000000..9f30856a2c --- /dev/null +++ b/cocos2dx/extensions/CCControlExtension/CCControlButton.cpp @@ -0,0 +1,465 @@ +/* + * CCControlButton.m + * + * Copyright 2011 Yannick Loriot. + * http://yannickloriot.com + * + * 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. + * + */ + +#include "CCControlButton.h" +#include "CCScale9Sprite.h" +#include "CCPointExtension.h" +#include "CCLabelTTF.h" +#include "CCAction.h" +#include "CCActionInterval.h" + +using namespace std; + +NS_CC_BEGIN + +enum +{ + kZoomActionTag = 0xCCCB0001, +}; + +CCControlButton::~CCControlButton() +{ + CC_SAFE_RELEASE(m_backgroundSpriteDispatchTable); + CC_SAFE_RELEASE(m_titleLabelDispatchTable); + CC_SAFE_RELEASE(m_titleColorDispatchTable); + CC_SAFE_RELEASE(m_titleDispatchTable); +} + +//initialisers + + +bool CCControlButton::initWithLabelAndBackgroundSprite(CCNode* node, CCScale9Sprite* backgroundSprite) +{ + if (CCControl::init()) + { + assert(node != NULL); + CCLabelProtocol* label = dynamic_cast(node); + CCRGBAProtocol* rgbaLabel = dynamic_cast(node); + assert(label != NULL || rgbaLabel!=NULL || backgroundSprite != NULL); + + setIsTouchEnabled(true); + pushed=false; + m_nState=CCControlStateInitial; + m_currentTitle=NULL; + m_backgroundSprite=NULL; + m_titleLabel=NULL; + + // Adjust the background image by default + m_adjustBackgroundImage=true; + + // Set the default anchor point + setIsRelativeAnchorPoint(true); + setAnchorPoint(ccp(0.5f, 0.5f)); + + // Set the nodes + m_titleLabel=(node); + m_backgroundSprite=(backgroundSprite); + + + // Initialize the button state tables + m_titleDispatchTable=new CCDictionary(); + //m_titleDispatchTable->autorelease(); + m_titleColorDispatchTable=new CCDictionary(); + //m_titleColorDispatchTable->autorelease(); + m_titleLabelDispatchTable=new CCDictionary(); + //m_titleLabelDispatchTable->autorelease(); + m_backgroundSpriteDispatchTable=new CCDictionary(); + //m_backgroundSpriteDispatchTable->autorelease(); + + // Set the default color and opacity + setColor(ccc3(255, 255, 255)); + setOpacity(255); + setIsOpacityModifyRGB(true); + + // Initialize the dispatch table + + CCString* tempString = CCString::stringWithCString(label->getString()); + //tempString->autorelease(); + setTitleForState(tempString, CCControlStateNormal); + setTitleColorForState(rgbaLabel->getColor(), CCControlStateNormal); + setTitleLabelForState(node, CCControlStateNormal); + setBackgroundSpriteForState(backgroundSprite, CCControlStateNormal); + + m_nState=CCControlStateNormal; + + //default margins + m_marginH=24; + m_marginV=12; + + // Layout update + needsLayout(); + + return true; + } + //couldn't init the CCControl + else + return false; +} + +CCControlButton* CCControlButton::buttonWithLabelAndBackgroundSprite(CCNode* label, CCScale9Sprite* backgroundSprite) +{ + CCControlButton *pRet = new CCControlButton(); + pRet->initWithLabelAndBackgroundSprite(label, backgroundSprite); + pRet->autorelease(); + return pRet; +} + +bool CCControlButton::initWithTitleAndFontNameAndFontSize(string title, const char * fontName, float fontSize) +{ + CCLabelTTF *label = CCLabelTTF::labelWithString(title.c_str(), fontName, fontSize); + return initWithLabelAndBackgroundSprite(label, CCScale9Sprite::node()); +} + +CCControlButton* CCControlButton::buttonWithTitleAndFontNameAndFontSize(string title, const char * fontName, float fontSize) +{ + CCControlButton *pRet = new CCControlButton(); + pRet->initWithTitleAndFontNameAndFontSize(title, fontName, fontSize); + pRet->autorelease(); + return pRet; +} + +bool CCControlButton::initWithBackgroundSprite(CCScale9Sprite* sprite) +{ + CCLabelTTF *label = CCLabelTTF::labelWithString("", "Arial", 30);// + return initWithLabelAndBackgroundSprite(label, sprite); +} + +CCControlButton* CCControlButton::buttonWithBackgroundSprite(CCScale9Sprite* sprite) +{ + CCControlButton *pRet = new CCControlButton(); + pRet->initWithBackgroundSprite(sprite); + pRet->autorelease(); + return pRet; +} + + +void CCControlButton::setMargins(int marginH, int marginV) +{ + m_marginV=marginV; + m_marginH=marginH; + needsLayout(); +} + +void CCControlButton::setIsEnabled(bool enabled) +{ + CCControl::setIsEnabled(enabled); + needsLayout(); +} + +void CCControlButton::setIsSelected(bool enabled) +{ + CCControl::setIsSelected(enabled); + needsLayout(); +} + +void CCControlButton::setIsHighlighted(bool enabled) +{ + CCControl::setIsHighlighted(enabled); + + CCAction *action =getActionByTag(kZoomActionTag); + if (action) + { + stopAction(action); + } + needsLayout(); + + float scaleValue = (getIsHighlighted() && getIsEnabled() && !getIsSelected()) ? 1.1f : 1.0f; + CCAction *zoomAction =CCScaleTo::actionWithDuration(0.05f, scaleValue); + zoomAction->setTag(kZoomActionTag); + runAction(zoomAction); +} +void CCControlButton::setAdjustBackgroundImage(bool adjustBackgroundImage) +{ + m_adjustBackgroundImage=adjustBackgroundImage; + needsLayout(); +} + +bool CCControlButton::getAdjustBackgroundImage() +{ + return m_adjustBackgroundImage; +} + +CCString* CCControlButton::getTitleForState(CCControlState state) +{ + CCString* title=(CCString*)m_titleDispatchTable->objectForKey(state); + if (title) + { + return title; + } + return (CCString*)m_titleDispatchTable->objectForKey(CCControlStateNormal); +} + +void CCControlButton::setTitleForState(CCString* title, CCControlState state) +{ + m_titleDispatchTable->removeObjectForKey(state); + + if (title) + { + m_titleDispatchTable->setObject(title, state); + } + + // If the current state if equal to the given state we update the layout + if (getState() == state) + { + needsLayout(); + } +} + + +const ccColor3B CCControlButton::getTitleColorForState(CCControlState state) +{ + ccColor3B returnColor; + CCColor3bObject* colorObject=(CCColor3bObject*)m_titleColorDispatchTable->objectForKey(state); + if (colorObject) + { + returnColor= colorObject->value; + return returnColor; + } + colorObject=(CCColor3bObject*)m_titleColorDispatchTable->objectForKey(CCControlStateNormal); + returnColor=colorObject->value; + return returnColor; +} + +void CCControlButton::setTitleColorForState(ccColor3B color, CCControlState state) +{ + //ccColor3B* colorValue=&color; + m_titleColorDispatchTable->removeObjectForKey(state); + CCColor3bObject* pColor3bObject = new CCColor3bObject(color); + pColor3bObject->autorelease(); + m_titleColorDispatchTable->setObject(pColor3bObject, state); + + // If the current state if equal to the given state we update the layout + if (getState() == state) + { + needsLayout(); + } +} + +CCNode* CCControlButton::getTitleLabelForState(CCControlState state) +{ + CCNode* titleLabel=(CCNode*)m_titleLabelDispatchTable->objectForKey(state); + if (titleLabel) + { + return titleLabel; + } + return (CCNode*)m_titleLabelDispatchTable->objectForKey(CCControlStateNormal); +} + +void CCControlButton::setTitleLabelForState(CCNode* titleLabel, CCControlState state) +{ + CCNode* previousLabel = (CCNode*)m_titleLabelDispatchTable->objectForKey(state); + if (previousLabel) + { + removeChild(previousLabel, true); + m_titleLabelDispatchTable->removeObjectForKey(state); + } + + m_titleLabelDispatchTable->setObject(titleLabel, state); + titleLabel->setIsVisible(false); + titleLabel->setAnchorPoint(ccp(0.5f, 0.5f)); + addChild(titleLabel, 1); + + // If the current state if equal to the given state we update the layout + if (getState() == state) + { + needsLayout(); + } +} + + +CCScale9Sprite* CCControlButton::getBackgroundSpriteForState(CCControlState state) +{ + CCScale9Sprite* backgroundSprite=(CCScale9Sprite*)m_backgroundSpriteDispatchTable->objectForKey(state); + if (backgroundSprite) + { + return backgroundSprite; + } + return (CCScale9Sprite*)m_backgroundSpriteDispatchTable->objectForKey(CCControlStateNormal); +} + + +void CCControlButton::setBackgroundSpriteForState(CCScale9Sprite* sprite, CCControlState state) +{ + CCScale9Sprite* previousSprite = (CCScale9Sprite*)m_backgroundSpriteDispatchTable->objectForKey(state); + if (previousSprite) + { + removeChild(previousSprite, true); + m_backgroundSpriteDispatchTable->removeObjectForKey(state); + } + + m_backgroundSpriteDispatchTable->setObject(sprite, state); + sprite->setIsVisible(false); + sprite->setAnchorPoint(ccp(0.5f, 0.5f)); + addChild(sprite); + + // If the current state if equal to the given state we update the layout + if (getState() == state) + { + needsLayout(); + } +} + +void CCControlButton::needsLayout() +{ + // Hide the background and the label + m_titleLabel->setIsVisible(false); + m_backgroundSprite->setIsVisible(false); + + // Update the label to match with the current state + //CC_SAFE_RELEASE(m_currentTitle) + + m_currentTitle=getTitleForState(m_nState); + m_currentTitleColor=getTitleColorForState(m_nState); + + m_titleLabel=getTitleLabelForState(m_nState); + + CCLabelProtocol* label = dynamic_cast(m_titleLabel); + if (label) + label->setString(m_currentTitle->getCString()); + CCRGBAProtocol* rgbaLabel = dynamic_cast(m_titleLabel); + if (rgbaLabel) + rgbaLabel->setColor(m_currentTitleColor); + m_titleLabel->setPosition(ccp (getContentSize().width / 2, getContentSize().height / 2)); + + + // Update the background sprite + m_backgroundSprite=getBackgroundSpriteForState(m_nState); + m_backgroundSprite->setPosition(ccp (getContentSize().width / 2, getContentSize().height / 2)); + + // Get the title label size + CCSize titleLabelSize =m_titleLabel->boundingBox().size; + + // Adjust the background image if necessary + if (m_adjustBackgroundImage) + { + // Add the margins + m_backgroundSprite->setContentSize(CCSizeMake(titleLabelSize.width + m_marginH * 2, titleLabelSize.height + m_marginV * 2)); + } + else + { + //TODO: should this also have margins if one of the preferred sizes is relaxed? + CCSize preferredSize = m_backgroundSprite->getPreferredSize(); + if (preferredSize.width <= 0) + { + preferredSize.width = titleLabelSize.width; + } + if (preferredSize.height <= 0) + { + preferredSize.height = titleLabelSize.height; + } + + m_backgroundSprite->setContentSize(preferredSize); + } + + // Set the content size + + CCRect maxRect = CCControlUtils::CCRectUnion(m_titleLabel->boundingBox(), m_backgroundSprite->boundingBox()); + setContentSize(CCSizeMake(maxRect.size.width, maxRect.size.height)); + + m_titleLabel->setPosition(ccp(getContentSize().width/2, getContentSize().height/2)); + m_backgroundSprite->setPosition(ccp(getContentSize().width/2, getContentSize().height/2)); + + // Make visible the background and the label + m_titleLabel->setIsVisible(true); + m_backgroundSprite->setIsVisible(true); +} + + + +bool CCControlButton::ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent) +{ + if (!isTouchInside(pTouch) || !getIsEnabled()) + { + return false; + } + + m_nState=CCControlStateHighlighted; + pushed=true; + this->setIsHighlighted(true); + sendActionsForControlEvents(CCControlEventTouchDown); + return true; +} + +void CCControlButton::ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent) +{ + if (!m_bEnabled || !pushed || m_bSelected) + { + if (m_bHighlighted) + { + setIsHighlighted(false); + } + return; + } + + bool isTouchMoveInside = isTouchInside(pTouch); + if (isTouchMoveInside && !m_bHighlighted) + { + m_nState = CCControlStateHighlighted; + setIsHighlighted(true); + sendActionsForControlEvents(CCControlEventTouchDragEnter); + } + else if (isTouchMoveInside && m_bHighlighted) + { + sendActionsForControlEvents(CCControlEventTouchDragInside); + } + else if (!isTouchMoveInside && m_bHighlighted) + { + m_nState = CCControlStateNormal; + setIsHighlighted(false); + + sendActionsForControlEvents(CCControlEventTouchDragExit); + } + else if (!isTouchMoveInside && !m_bHighlighted) + { + sendActionsForControlEvents(CCControlEventTouchDragOutside); + } +} +void CCControlButton::ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent) +{ + m_nState = CCControlStateNormal; + pushed = false; + setIsHighlighted(false); + + + if (isTouchInside(pTouch)) + { + sendActionsForControlEvents(CCControlEventTouchUpInside); + } + else + { + sendActionsForControlEvents(CCControlEventTouchUpOutside); + } +} + +void CCControlButton::ccTouchCancelled(CCTouch *pTouch, CCEvent *pEvent) +{ + m_nState = CCControlStateNormal; + pushed = false; + setIsHighlighted(false); + sendActionsForControlEvents(CCControlEventTouchCancel); +} + +NS_CC_END diff --git a/cocos2dx/extensions/CCControlExtension/CCControlButton.h b/cocos2dx/extensions/CCControlExtension/CCControlButton.h new file mode 100644 index 0000000000..689e56fdad --- /dev/null +++ b/cocos2dx/extensions/CCControlExtension/CCControlButton.h @@ -0,0 +1,186 @@ +/* + * CCControlButton.h + * + * Copyright 2011 Yannick Loriot. All rights reserved. + * http://yannickloriot.com + * + * 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. + * + * Converted to c++ / cocos2d-x by Angus C + */ + + +#ifndef __CCCONTROL_BUTTON_H__ +#define __CCCONTROL_BUTTON_H__ + +#include "CCControl.h" +#include "CCInvocation.h" +#include "CCScale9Sprite.h" + +NS_CC_BEGIN + +/** @class CCControlButton Button control for Cocos2D. */ +class CC_DLL CCControlButton : public CCControl +{ +public: + virtual ~CCControlButton(); + virtual void needsLayout(void); + + virtual void setIsEnabled(bool enabled); + virtual void setIsSelected(bool enabled); + virtual void setIsHighlighted(bool enabled); +protected: + // CCRGBAProtocol + //bool m_bIsOpacityModifyRGB; + + /** Adjust the background image. YES by default. If the property is set to NO, the + background will use the prefered size of the background image. */ + CC_PROPERTY(bool, m_adjustBackgroundImage, AdjustBackgroundImage); + + + /** The current title that is displayed on the button. */ + CC_SYNTHESIZE_READONLY(CCString*, m_currentTitle, CurrentTitle); + /** The current color used to display the title. */ + CC_SYNTHESIZE_READONLY_PASS_BY_REF(ccColor3B, m_currentTitleColor, CurrentTitleColor); + /** The current title label. */ + //CC_PROPERTY(CCNode*, m_titleLabel, TitleLabel); + CCNode* m_titleLabel; + /** The current background sprite. */ + //CC_PROPERTY(CCScale9Sprite*, m_backgroundSprite, BackgroundSprite); + CCScale9Sprite* m_backgroundSprite; + + /** Flag to know if the button is currently pushed. */ + CC_SYNTHESIZE_READONLY(bool, pushed, IsPushed); + // + CCDictionary* m_titleDispatchTable; + // + CCDictionary* m_titleColorDispatchTable; + // + CCDictionary* m_titleLabelDispatchTable; + // + CCDictionary* m_backgroundSpriteDispatchTable; + + /* Define the button margin for Top/Bottom edge */ + CC_SYNTHESIZE_READONLY(int, m_marginV, VerticalMargin); + /* Define the button margin for Left/Right edge */ + CC_SYNTHESIZE_READONLY(int, m_marginH, HorizontalOrigin); + //set the margins at once (so we only have to do one call of needsLayout) + virtual void setMargins(int marginH, int marginV); + + +public: + virtual bool initWithLabelAndBackgroundSprite(CCNode* label, CCScale9Sprite* backgroundSprite); + static CCControlButton* buttonWithLabelAndBackgroundSprite(CCNode* label, CCScale9Sprite* backgroundSprite); + + virtual bool initWithTitleAndFontNameAndFontSize(std::string title, const char * fontName, float fontSize); + static CCControlButton* buttonWithTitleAndFontNameAndFontSize(std::string title, const char * fontName, float fontSize); + + virtual bool initWithBackgroundSprite(CCScale9Sprite* sprite); + static CCControlButton* buttonWithBackgroundSprite(CCScale9Sprite* sprite); + + //events + virtual bool ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent); + virtual void ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent); + virtual void ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent); + virtual void ccTouchCancelled(CCTouch *pTouch, CCEvent *pEvent); + + + + /** + * Returns the title used for a state. + * + * @param state The state that uses the title. Possible values are described in + * "CCControlState". + * + * @return The title for the specified state. + */ + virtual CCString* getTitleForState(CCControlState state); + + /** + * Sets the title string to use for the specified state. + * If a property is not specified for a state, the default is to use + * the CCButtonStateNormal value. + * + * @param title The title string to use for the specified state. + * @param state The state that uses the specified title. The values are described + * in "CCControlState". + */ + virtual void setTitleForState(CCString* title, CCControlState state); + + /** + * Returns the title color used for a state. + * + * @param state The state that uses the specified color. The values are described + * in "CCControlState". + * + * @return The color of the title for the specified state. + */ + + virtual const ccColor3B getTitleColorForState(CCControlState state); + + /** + * Sets the color of the title to use for the specified state. + * + * @param color The color of the title to use for the specified state. + * @param state The state that uses the specified color. The values are described + * in "CCControlState". + */ + virtual void setTitleColorForState(ccColor3B color, CCControlState state); + + /** + * Returns the title label used for a state. + * + * @param state The state that uses the title label. Possible values are described + * in "CCControlState". + */ + virtual CCNode* getTitleLabelForState(CCControlState state); + + /** + * Sets the title label to use for the specified state. + * If a property is not specified for a state, the default is to use + * the CCButtonStateNormal value. + * + * @param title The title label to use for the specified state. + * @param state The state that uses the specified title. The values are described + * in "CCControlState". + */ + virtual void setTitleLabelForState(CCNode* label, CCControlState state); + + /** + * Returns the background sprite used for a state. + * + * @param state The state that uses the background sprite. Possible values are + * described in "CCControlState". + */ + virtual CCScale9Sprite* getBackgroundSpriteForState(CCControlState state); + + /** + * Sets the background sprite to use for the specified button state. + * + * @param sprite The background sprite to use for the specified state. + * @param state The state that uses the specified image. The values are described + * in "CCControlState". + */ + virtual void setBackgroundSpriteForState(CCScale9Sprite* sprite, CCControlState state); + +}; + +NS_CC_END + +#endif \ No newline at end of file diff --git a/cocos2dx/extensions/CCControlExtension/CCControlColourPicker.cpp b/cocos2dx/extensions/CCControlExtension/CCControlColourPicker.cpp new file mode 100644 index 0000000000..e567886323 --- /dev/null +++ b/cocos2dx/extensions/CCControlExtension/CCControlColourPicker.cpp @@ -0,0 +1,161 @@ +/* + * CCControlColourPicker.m + * + * Copyright 2012 Stewart Hamilton-Arrandale. + * http://creativewax.co.uk + * + * Modified by Yannick Loriot. + * http://yannickloriot.com + * + * 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. + * + * converted to c++ / cocos2d-x by Angus C + */ + +#include "CCControlColourPicker.h" +#include "CCPointExtension.h" +#include "CCSpriteFrameCache.h" +#include "CCSpriteBatchNode.h" + +NS_CC_BEGIN + +bool CCControlColourPicker::init() +{ + if (CCControl::init()) + { + setIsTouchEnabled(true); + // Cache the sprites + CCSpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile("extensions/CCControlColourPickerSpriteSheet.plist"); + + // Create the sprite batch node + CCSpriteBatchNode *spriteSheet = CCSpriteBatchNode::batchNodeWithFile("extensions/CCControlColourPickerSpriteSheet.png"); + addChild(spriteSheet); + + // MIPMAP + ccTexParams params = {GL_LINEAR_MIPMAP_LINEAR, GL_LINEAR, GL_REPEAT, GL_REPEAT}; + spriteSheet->getTexture()->setAliasTexParameters(); + spriteSheet->getTexture()->setTexParameters(¶ms); + spriteSheet->getTexture()->generateMipmap(); + + // Init default color + m_hsv.h = 0; + m_hsv.s = 0; + m_hsv.v = 0; + + // Add image + m_background=CCControlUtils::addSpriteToTargetWithPosAndAnchor("menuColourPanelBackground.png", spriteSheet, CCPointZero, ccp(0.5f, 0.5f)); + + CCPoint backgroundPointZero = ccpSub(m_background->getPosition(), ccp (m_background->getContentSize().width / 2, m_background->getContentSize().height / 2)); + + // Setup panels . currently hard-coded... + float hueShift = 8; + float colourShift = 28; + + m_huePicker=CCControlHuePicker::pickerWithTargetAndPos(spriteSheet, ccp(backgroundPointZero.x + hueShift, backgroundPointZero.y + hueShift)); + m_colourPicker=CCControlSaturationBrightnessPicker::pickerWithTargetAndPos(spriteSheet, ccp(backgroundPointZero.x + colourShift, backgroundPointZero.y + colourShift)); + + // Setup events + m_huePicker->addTargetWithActionForControlEvents(this, menu_selector(CCControlColourPicker::hueSliderValueChanged), CCControlEventValueChanged); + m_colourPicker->addTargetWithActionForControlEvents(this, menu_selector(CCControlColourPicker::colourSliderValueChanged), CCControlEventValueChanged); + + // Set defaults + updateHueAndControlPicker(); + addChild(m_huePicker); + addChild(m_colourPicker); + + // Set content size + setContentSize(m_background->getContentSize()); + return true; + } + else + return false; +} + +CCControlColourPicker* CCControlColourPicker::colourPicker() +{ + CCControlColourPicker *pRet = new CCControlColourPicker(); + pRet->init(); + pRet->autorelease(); + return pRet; +} + + +void CCControlColourPicker::setColorValue(const ccColor3B& colorValue) +{ + m_colorValue = colorValue; + + RGBA rgba; + rgba.r = colorValue.r / 255.0f; + rgba.g = colorValue.g / 255.0f; + rgba.b = colorValue.b / 255.0f; + rgba.a = 1.0f; + + m_hsv=CCControlUtils::HSVfromRGB(rgba); + updateHueAndControlPicker(); +} + +//need two events to prevent an infinite loop! (can't update huePicker when the huePicker triggers the callback due to CCControlEventValueChanged) +void CCControlColourPicker::updateControlPicker() +{ + m_huePicker->setHue(m_hsv.h); + m_colourPicker->updateWithHSV(m_hsv); +} + +void CCControlColourPicker::updateHueAndControlPicker() +{ + m_huePicker->setHue(m_hsv.h); + m_colourPicker->updateWithHSV(m_hsv); + m_colourPicker->updateDraggerWithHSV(m_hsv); +} + + +void CCControlColourPicker::hueSliderValueChanged(CCObject * sender) +{ + m_hsv.h = ((CCControlHuePicker*)sender)->getHue(); + + // Update the value + RGBA rgb = CCControlUtils::RGBfromHSV(m_hsv); + m_colorValue= ccc3((GLubyte)(rgb.r * 255.0f), (GLubyte)(rgb.g * 255.0f), (GLubyte)(rgb.b * 255.0f)); + + // Send CCControl callback + sendActionsForControlEvents(CCControlEventValueChanged); + updateControlPicker(); +} + +void CCControlColourPicker::colourSliderValueChanged(CCObject * sender) +{ + m_hsv.s=((CCControlSaturationBrightnessPicker*)sender)->getSaturation(); + m_hsv.v=((CCControlSaturationBrightnessPicker*)sender)->getBrightness(); + + + // Update the value + RGBA rgb = CCControlUtils::RGBfromHSV(m_hsv); + m_colorValue=ccc3((GLubyte)(rgb.r * 255.0f), (GLubyte)(rgb.g * 255.0f), (GLubyte)(rgb.b * 255.0f)); + + // Send CCControl callback + sendActionsForControlEvents(CCControlEventValueChanged); +} + +//ignore all touches, handled by children +bool CCControlColourPicker::ccTouchBegan(CCTouch* touch, CCEvent* pEvent) +{ + return false; +} + +NS_CC_END diff --git a/cocos2dx/extensions/CCControlExtension/CCControlColourPicker.h b/cocos2dx/extensions/CCControlExtension/CCControlColourPicker.h new file mode 100644 index 0000000000..40eb1847a2 --- /dev/null +++ b/cocos2dx/extensions/CCControlExtension/CCControlColourPicker.h @@ -0,0 +1,70 @@ +/* + * CCControlColourPicker.h + * + * Copyright 2012 Stewart Hamilton-Arrandale. + * http://creativewax.co.uk + * + * Modified by Yannick Loriot. + * http://yannickloriot.com + * + * 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. + * + * Converted to c++ / cocos2d-x by Angus C + */ + +#ifndef __CCCONTROL_COLOUR_PICKER_H__ +#define __CCCONTROL_COLOUR_PICKER_H__ + + +#include "CCControl.h" +#include "CCControlUtils.h" +#include "CCControlHuePicker.h" +#include "CCControlSaturationBrightnessPicker.h" + +NS_CC_BEGIN + +class CC_DLL CCControlColourPicker: public CCControl +{ + CC_SYNTHESIZE_READONLY_PASS_BY_REF(ccColor3B, m_colorValue, ColorValue); + virtual void setColorValue(const ccColor3B& colorValue); + +protected: + HSV m_hsv; + CCControlSaturationBrightnessPicker* m_colourPicker; + CCControlHuePicker* m_huePicker; + + CC_SYNTHESIZE_READONLY(CCSprite*, m_background, Background); + +public: + static CCControlColourPicker* colourPicker(); + virtual bool init(); + //virtual ~CCControlColourPicker(); + void hueSliderValueChanged(CCObject * sender); + void colourSliderValueChanged(CCObject * sender); + +protected: + void updateControlPicker(); + void updateHueAndControlPicker(); + virtual bool ccTouchBegan(CCTouch* touch, CCEvent* pEvent); + +}; + +NS_CC_END + +#endif \ No newline at end of file diff --git a/cocos2dx/extensions/CCControlExtension/CCControlExtensions.h b/cocos2dx/extensions/CCControlExtension/CCControlExtensions.h new file mode 100644 index 0000000000..82a31ce500 --- /dev/null +++ b/cocos2dx/extensions/CCControlExtension/CCControlExtensions.h @@ -0,0 +1,14 @@ +#ifndef __CCCONTROL_EXTENSIONS_H__ +#define __CCCONTROL_EXTENSIONS_H__ + +#include "CCControl.h" +#include "CCControlButton.h" +#include "CCControlColourPicker.h" +#include "CCControlHuePicker.h" +#include "CCControlSaturationBrightnessPicker.h" +#include "CCControlSlider.h" +#include "CCControlSwitch.h" +#include "CCMenuPassive.h" +#include "CCSpacer.h" + +#endif \ No newline at end of file diff --git a/cocos2dx/extensions/CCControlExtension/CCControlHuePicker.cpp b/cocos2dx/extensions/CCControlExtension/CCControlHuePicker.cpp new file mode 100644 index 0000000000..1aab5505e4 --- /dev/null +++ b/cocos2dx/extensions/CCControlExtension/CCControlHuePicker.cpp @@ -0,0 +1,161 @@ +/* + * CCControlHuePicker.m + * + * Copyright 2012 Stewart Hamilton-Arrandale. + * http://creativewax.co.uk + * + * Modified by Yannick Loriot. + * http://yannickloriot.com + * + * 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. + * + * Converted to c++ / cocos2d-x by Angus C + */ + +#include "CCControlHuePicker.h" +#include "CCPointExtension.h" + +NS_CC_BEGIN + +CCControlHuePicker::~CCControlHuePicker() +{ + +} + +CCControlHuePicker* CCControlHuePicker::pickerWithTargetAndPos(CCNode* target, CCPoint pos) +{ + CCControlHuePicker *pRet = new CCControlHuePicker(); + pRet->initWithTargetAndPos(target, pos); + pRet->autorelease(); + return pRet; +} + + +bool CCControlHuePicker::initWithTargetAndPos(CCNode* target, CCPoint pos) +{ + if (CCControl::init()) + { + setIsTouchEnabled(true); + // Add background and slider sprites + m_background=CCControlUtils::addSpriteToTargetWithPosAndAnchor("huePickerBackground.png", target, pos, ccp(0.0f, 0.0f)); + m_slider=CCControlUtils::addSpriteToTargetWithPosAndAnchor("colourPicker.png", target, pos, ccp(0.5f, 0.5f)); + + m_slider->setPosition(ccp(pos.x, pos.y + m_background->boundingBox().size.height * 0.5f)); + m_startPos=pos; + + // Sets the default value + m_hue=0.0f; + m_huePercentage=0.0f; + return true; + } + else + return false; +} + +void CCControlHuePicker::setHue(float hueValue) +{ + m_hue=hueValue; + setHuePercentage(m_hue/360.0f); +} + +void CCControlHuePicker::setHuePercentage(float hueValueInPercent) +{ + m_huePercentage=hueValueInPercent; + m_hue=m_huePercentage*360.0f; + + // Clamp the position of the icon within the circle + CCRect backgroundBox=m_background->boundingBox(); + + // Get the center point of the background image + float centerX = m_startPos.x + backgroundBox.size.width * 0.5f; + float centerY = m_startPos.y + backgroundBox.size.height * 0.5f; + + // Work out the limit to the distance of the picker when moving around the hue bar + float limit = backgroundBox.size.width * 0.5f - 15.0f; + + // Update angle + float angleDeg = m_huePercentage * 360.0f - 180.0f; + float angle = CC_DEGREES_TO_RADIANS(angleDeg); + + // Set new position of the slider + float x = centerX + limit * cosf(angle); + float y = centerY + limit * sinf(angle); + m_slider->setPosition(ccp(x, y)); + +} + +void CCControlHuePicker::updateSliderPosition(CCPoint location) +{ + + // Clamp the position of the icon within the circle + CCRect backgroundBox=m_background->boundingBox(); + + // Get the center point of the background image + float centerX = m_startPos.x + backgroundBox.size.width * 0.5f; + float centerY = m_startPos.y + backgroundBox.size.height * 0.5f; + + // Work out the distance difference between the location and center + float dx = location.x - centerX; + float dy = location.y - centerY; + + // Update angle by using the direction of the location + float angle = atan2f(dy, dx); + float angleDeg = CC_RADIANS_TO_DEGREES(angle) + 180.0f; + + // use the position / slider width to determin the percentage the dragger is at + setHue(angleDeg); + + // send CCControl callback + sendActionsForControlEvents(CCControlEventValueChanged); +} + +bool CCControlHuePicker::checkSliderPosition(CCPoint location) +{ + // check that the touch location is within the bounding rectangle before sending updates + if (CCRect::CCRectContainsPoint(m_background->boundingBox(), location)) + { + updateSliderPosition(location); + return true; + } + return false; +} + +bool CCControlHuePicker::ccTouchBegan(CCTouch* touch, CCEvent* event) +{ + // Get the touch location + CCPoint touchLocation=getTouchLocation(touch); + + // Check the touch position on the slider + return checkSliderPosition(touchLocation); +} + + +void CCControlHuePicker::ccTouchMoved(CCTouch* touch, CCEvent* event) +{ + // Get the touch location + CCPoint touchLocation=getTouchLocation(touch); + + //small modification: this allows changing of the colour, even if the touch leaves the bounding area + updateSliderPosition(touchLocation); + sendActionsForControlEvents(CCControlEventValueChanged); + // Check the touch position on the slider + //checkSliderPosition(touchLocation); +} + +NS_CC_END diff --git a/cocos2dx/extensions/CCControlExtension/CCControlHuePicker.h b/cocos2dx/extensions/CCControlExtension/CCControlHuePicker.h new file mode 100644 index 0000000000..0f5c3fc0f8 --- /dev/null +++ b/cocos2dx/extensions/CCControlExtension/CCControlHuePicker.h @@ -0,0 +1,69 @@ +/* + * CCControlHuePicker.h + * + * Copyright 2012 Stewart Hamilton-Arrandale. + * http://creativewax.co.uk + * + * Modified by Yannick Loriot. + * http://yannickloriot.com + * + * 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. + * + * Converted to c++ / cocos2d-x by Angus C + */ + + +#ifndef __CCCONTROL_HUE_PICKER_H__ +#define __CCCONTROL_HUE_PICKER_H__ + +#include "CCControl.h" +#include "CCInvocation.h" + +NS_CC_BEGIN + +class CC_DLL CCControlHuePicker : public CCControl +{ + //maunally put in the setters + CC_SYNTHESIZE_READONLY(float, m_hue, Hue); + virtual void setHue(float val); + CC_SYNTHESIZE_READONLY(float, m_huePercentage, HuePercentage); + virtual void setHuePercentage(float val); + + + //not sure if these need to be there actually. I suppose someone might want to access the sprite? + CC_SYNTHESIZE_READONLY(CCSprite*, m_background, Background); + CC_SYNTHESIZE_READONLY(CCSprite*, m_slider, Slider); + CC_SYNTHESIZE_READONLY(CCPoint, m_startPos, StartPos); + +public: + virtual ~CCControlHuePicker(); + virtual bool initWithTargetAndPos(CCNode* target, CCPoint pos); + static CCControlHuePicker* pickerWithTargetAndPos(CCNode* target, CCPoint pos); + +protected: + void updateSliderPosition(CCPoint location); + bool checkSliderPosition(CCPoint location); + + virtual bool ccTouchBegan(CCTouch* touch, CCEvent* pEvent); + virtual void ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent); +}; + +NS_CC_END + +#endif \ No newline at end of file diff --git a/cocos2dx/extensions/CCControlExtension/CCControlSaturationBrightnessPicker.cpp b/cocos2dx/extensions/CCControlExtension/CCControlSaturationBrightnessPicker.cpp new file mode 100644 index 0000000000..367757bd1d --- /dev/null +++ b/cocos2dx/extensions/CCControlExtension/CCControlSaturationBrightnessPicker.cpp @@ -0,0 +1,179 @@ +/* + * CCControlSaturationBrightnessPicker.m + * + * Copyright 2012 Stewart Hamilton-Arrandale. + * http://creativewax.co.uk + * + * Modified by Yannick Loriot. + * http://yannickloriot.com + * + * 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. + * + * Converted to c++ / cocos2d-x by Angus C + */ + +#include "CCControlSaturationBrightnessPicker.h" +#include "CCPointExtension.h" + +NS_CC_BEGIN + +CCControlSaturationBrightnessPicker::~CCControlSaturationBrightnessPicker() +{ + +} + +bool CCControlSaturationBrightnessPicker::initWithTargetAndPos(CCNode* target, CCPoint pos) +{ + if (CCControl::init()) + { + setIsTouchEnabled(true); + // Add background and slider sprites + m_background=CCControlUtils::addSpriteToTargetWithPosAndAnchor("colourPickerBackground.png", target, pos, ccp(0.0f, 0.0f)); + m_overlay=CCControlUtils::addSpriteToTargetWithPosAndAnchor("colourPickerOverlay.png", target, pos, ccp(0.0f, 0.0f)); + m_shadow=CCControlUtils::addSpriteToTargetWithPosAndAnchor("colourPickerShadow.png", target, pos, ccp(0.0f, 0.0f)); + m_slider=CCControlUtils::addSpriteToTargetWithPosAndAnchor("colourPicker.png", target, pos, ccp(0.5f, 0.5f)); + + m_startPos=pos; // starting position of the colour picker + boxPos = 35; // starting position of the virtual box area for picking a colour + boxSize = 150; // the size (width and height) of the virtual box for picking a colour from + return true; + } + else + return false; +} + +CCControlSaturationBrightnessPicker* CCControlSaturationBrightnessPicker::pickerWithTargetAndPos(CCNode* target, CCPoint pos) +{ + CCControlSaturationBrightnessPicker *pRet = new CCControlSaturationBrightnessPicker(); + pRet->initWithTargetAndPos(target, pos); + pRet->autorelease(); + return pRet; +} + + + +void CCControlSaturationBrightnessPicker::updateWithHSV(HSV hsv) +{ + HSV hsvTemp; + hsvTemp.s = 1; + hsvTemp.h = hsv.h; + hsvTemp.v = 1; + + RGBA rgb = CCControlUtils::RGBfromHSV(hsvTemp); + m_background->setColor(ccc3((GLubyte)(rgb.r * 255.0f), (GLubyte)(rgb.g * 255.0f), (GLubyte)(rgb.b * 255.0f))); +} + +void CCControlSaturationBrightnessPicker::updateDraggerWithHSV(HSV hsv) +{ + // Set the position of the slider to the correct saturation and brightness + CCPoint pos = CCPointMake(m_startPos.x + boxPos + (boxSize*(1 - hsv.s)), + m_startPos.y + boxPos + (boxSize*hsv.v)); + + // update + updateSliderPosition(pos); +} + +void CCControlSaturationBrightnessPicker::updateSliderPosition(CCPoint sliderPosition) +{ + // Clamp the position of the icon within the circle + + // Get the center point of the bkgd image + float centerX = m_startPos.x + m_background->boundingBox().size.width*.5; + float centerY = m_startPos.y + m_background->boundingBox().size.height*.5; + + // Work out the distance difference between the location and center + float dx = sliderPosition.x - centerX; + float dy = sliderPosition.y - centerY; + float dist = sqrtf(dx * dx + dy * dy); + + // Update angle by using the direction of the location + float angle = atan2f(dy, dx); + + // Set the limit to the slider movement within the colour picker + float limit = m_background->boundingBox().size.width*.5; + + // Check distance doesn't exceed the bounds of the circle + if (dist > limit) + { + sliderPosition.x = centerX + limit * cosf(angle); + sliderPosition.y = centerY + limit * sinf(angle); + } + + // Set the position of the dragger + m_slider->setPosition(sliderPosition); + + + // Clamp the position within the virtual box for colour selection + if (sliderPosition.x < m_startPos.x + boxPos) sliderPosition.x = m_startPos.x + boxPos; + else if (sliderPosition.x > m_startPos.x + boxPos + boxSize - 1) sliderPosition.x = m_startPos.x + boxPos + boxSize - 1; + if (sliderPosition.y < m_startPos.y + boxPos) sliderPosition.y = m_startPos.y + boxPos; + else if (sliderPosition.y > m_startPos.y + boxPos + boxSize) sliderPosition.y = m_startPos.y + boxPos + boxSize; + + // Use the position / slider width to determin the percentage the dragger is at + m_saturation = 1.0 - fabs((m_startPos.x + (float)boxPos - sliderPosition.x)/(float)boxSize); + m_brightness = fabs((m_startPos.y + (float)boxPos - sliderPosition.y)/(float)boxSize); +} + +bool CCControlSaturationBrightnessPicker::checkSliderPosition(CCPoint location) +{ + // Clamp the position of the icon within the circle + + // get the center point of the bkgd image + float centerX = m_startPos.x + m_background->boundingBox().size.width*.5; + float centerY = m_startPos.y + m_background->boundingBox().size.height*.5; + + // work out the distance difference between the location and center + float dx = location.x - centerX; + float dy = location.y - centerY; + float dist = sqrtf(dx*dx+dy*dy); + + // check that the touch location is within the bounding rectangle before sending updates + if (dist <= m_background->boundingBox().size.width*.5) + { + updateSliderPosition(location); + sendActionsForControlEvents(CCControlEventValueChanged); + return true; + } + return false; +} + + +bool CCControlSaturationBrightnessPicker::ccTouchBegan(CCTouch* touch, CCEvent* event) +{ + // Get the touch location + CCPoint touchLocation=getTouchLocation(touch); + + // Check the touch position on the slider + return checkSliderPosition(touchLocation); +} + + +void CCControlSaturationBrightnessPicker::ccTouchMoved(CCTouch* touch, CCEvent* event) +{ + // Get the touch location + CCPoint touchLocation=getTouchLocation(touch); + + //small modification: this allows changing of the colour, even if the touch leaves the bounding area + updateSliderPosition(touchLocation); + sendActionsForControlEvents(CCControlEventValueChanged); + // Check the touch position on the slider + //checkSliderPosition(touchLocation); +} + +NS_CC_END diff --git a/cocos2dx/extensions/CCControlExtension/CCControlSaturationBrightnessPicker.h b/cocos2dx/extensions/CCControlExtension/CCControlSaturationBrightnessPicker.h new file mode 100644 index 0000000000..f4a01b2802 --- /dev/null +++ b/cocos2dx/extensions/CCControlExtension/CCControlSaturationBrightnessPicker.h @@ -0,0 +1,73 @@ +/* + * CCControlSaturationBrightnessPicker.h + * + * Copyright 2012 Stewart Hamilton-Arrandale. + * http://creativewax.co.uk + * + * Modified by Yannick Loriot. + * http://yannickloriot.com + * + * 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. + * + * Converted to c++ / cocos2d-x by Angus C + */ + + +#ifndef __CCCONTROL_SATURATION_PICKER_H__ +#define __CCCONTROL_SATURATION_PICKER_H__ + +#include "CCControl.h" +#include "CCInvocation.h" + +NS_CC_BEGIN + +class CC_DLL CCControlSaturationBrightnessPicker : public CCControl +{ + CC_SYNTHESIZE_READONLY(float, m_saturation, Saturation); + CC_SYNTHESIZE_READONLY(float, m_brightness, Brightness); + + //not sure if these need to be there actually. I suppose someone might want to access the sprite? + CC_SYNTHESIZE_READONLY(CCSprite*, m_background, Background); + CC_SYNTHESIZE_READONLY(CCSprite*, m_overlay, Overlay); + CC_SYNTHESIZE_READONLY(CCSprite*, m_shadow, Shadow); + CC_SYNTHESIZE_READONLY(CCSprite*, m_slider, Slider); + CC_SYNTHESIZE_READONLY(CCPoint, m_startPos, StartPos); + +protected: + int boxPos; + int boxSize; + +public: + virtual ~CCControlSaturationBrightnessPicker(); + virtual bool initWithTargetAndPos(CCNode* target, CCPoint pos); + static CCControlSaturationBrightnessPicker* pickerWithTargetAndPos(CCNode* target, CCPoint pos); + virtual void updateWithHSV(HSV hsv); + virtual void updateDraggerWithHSV(HSV hsv); + +protected: + void updateSliderPosition(CCPoint location); + bool checkSliderPosition(CCPoint location); + + virtual bool ccTouchBegan(CCTouch* touch, CCEvent* pEvent); + virtual void ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent); +}; + +NS_CC_END + +#endif \ No newline at end of file diff --git a/cocos2dx/extensions/CCControlExtension/CCControlSlider.cpp b/cocos2dx/extensions/CCControlExtension/CCControlSlider.cpp new file mode 100644 index 0000000000..e47ae4a8e6 --- /dev/null +++ b/cocos2dx/extensions/CCControlExtension/CCControlSlider.cpp @@ -0,0 +1,221 @@ +/* + * CCControlSlider + * + * Copyright 2011 Yannick Loriot. + * http://yannickloriot.com + * + * 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. + * + * Converted to c++ / cocos2d-x by Angus C +* + */ + +#include "CCControlSlider.h" +#include "CCPointExtension.h" +#include "CCTouch.h" +#include "CCDirector.h" + +NS_CC_BEGIN + +CCControlSlider::~CCControlSlider() +{ + +} + +CCControlSlider* CCControlSlider::sliderWithFiles(const char* bgFile, const char* progressFile, const char* thumbFile) +{ + // Prepare background for slider + CCSprite *backgroundSprite = CCSprite::spriteWithFile(bgFile); + + // Prepare progress for slider + CCSprite *progressSprite = CCSprite::spriteWithFile(progressFile); + + // Prepare thumb (menuItem) for slider + CCSprite *thumbNormal = CCSprite::spriteWithFile(thumbFile); + CCSprite *thumbSelected = CCSprite::spriteWithFile(thumbFile); + thumbSelected->setColor(ccGRAY); + + CCMenuItemSprite* thumbMenuItem =CCMenuItemSprite::itemWithNormalSprite(thumbNormal, thumbSelected); + + return CCControlSlider::sliderWithSprites(backgroundSprite, progressSprite, thumbMenuItem); +} + +CCControlSlider* CCControlSlider::sliderWithSprites(CCSprite * backgroundSprite, CCSprite* pogressSprite, CCMenuItem* thumbItem) +{ + CCControlSlider *pRet = new CCControlSlider(); + pRet->initWithSprites(backgroundSprite, pogressSprite, thumbItem); + pRet->autorelease(); + return pRet; +} + + bool CCControlSlider::initWithSprites(CCSprite * backgroundSprite, CCSprite* progessSprite, CCMenuItem* thumbItem) + { + if (CCControl::init()) + { + setIsRelativeAnchorPoint(true); + setIsTouchEnabled(true); + + m_backgroundSprite=backgroundSprite; + m_progressSprite=progessSprite; + m_thumbItem=thumbItem; + + // Defines the content size + CCRect maxRect = CCControlUtils::CCRectUnion(backgroundSprite->boundingBox(), thumbItem->boundingBox()); + CCSize size=CCSizeMake(maxRect.size.width+2*SLIDER_MARGIN_H, maxRect.size.height+2*SLIDER_MARGIN_V); + setContentSize(size); + //setContentSize(CCSizeMake(backgroundSprite->getContentSize().width, thumbItem->getContentSize().height)); + // Add the slider background + m_backgroundSprite->setAnchorPoint(ccp(0.5f, 0.5f)); + m_backgroundSprite->setPosition(ccp(size.width / 2, size.height / 2)); + addChild(m_backgroundSprite); + + // Add the progress bar + m_progressSprite->setAnchorPoint(ccp(0.0f, 0.5f)); + m_progressSprite->setPosition(ccp(0.0f+SLIDER_MARGIN_H, size.height / 2)); + addChild(m_progressSprite); + + // Add the slider thumb + m_thumbItem->setPosition(ccp(0+SLIDER_MARGIN_H, size.height / 2)); + addChild(m_thumbItem); + + // Init default values + m_minimumValue = 0.0f; + m_maximumValue = 1.0f; + m_snappingInterval=-1.0f; + setValue(m_minimumValue); + return true; + } + else + { + return false; + } + } + + + void CCControlSlider::setValue(float value) + { + //clamp between the two bounds + value=MAX(value, m_minimumValue); + value=MIN(value, m_maximumValue); + + //if we're snapping + if (m_snappingInterval>=0) + { + //int nTotal=(int)(ceil(m_maximumValue-m_minimumValue)/m_snappingInterval); + //floor (n + 0.5f) == round(n) + value=floor(0.5f + value/m_snappingInterval)*m_snappingInterval; + } + m_value=value; + + // Update thumb position for new value + float percent = (m_value - m_minimumValue) / (m_maximumValue - m_minimumValue); + CCPoint pos= m_thumbItem->getPosition(); + pos.x = percent * m_backgroundSprite->getContentSize().width+SLIDER_MARGIN_H; + m_thumbItem->setPosition(pos); + + // Stretches content proportional to newLevel + CCRect textureRect = m_progressSprite->getTextureRect(); + textureRect = CCRectMake(textureRect.origin.x, textureRect.origin.y, percent * m_backgroundSprite->getContentSize().width, textureRect.size.height); + m_progressSprite->setTextureRect(textureRect); + sendActionsForControlEvents(CCControlEventValueChanged); + } + + void CCControlSlider::setMinimumValue(float minimumValue) + { + m_minimumValue=minimumValue; + if (m_minimumValue >= m_maximumValue) + m_maximumValue = m_minimumValue + 1.0f; + setValue(m_value); + } + + void CCControlSlider::setMaximumValue(float maximumValue) + { + m_maximumValue=maximumValue; + if (m_maximumValue <= m_minimumValue) + m_minimumValue = m_maximumValue - 1.0f; + setValue(m_value); + } + + //this is the same as CCControl::getTouchLocation, but it returns the position relative to the position of this control + CCPoint CCControlSlider::getTouchLocationInControl(CCTouch* touch) +{ + CCPoint touchLocation=touch->locationInView();; // Get the touch position + touchLocation = CCDirector::sharedDirector()->convertToGL(touchLocation); // Convert the position to GL space + touchLocation = convertToNodeSpace(touchLocation); // Convert to the node space of this class + + if (touchLocation.x < 0) + { + touchLocation.x = 0; + } + else if (touchLocation.x > m_backgroundSprite->getContentSize().width+SLIDER_MARGIN_H) + { + touchLocation.x = m_backgroundSprite->getContentSize().width+SLIDER_MARGIN_H; + } + return touchLocation; +} + + bool CCControlSlider::ccTouchBegan(CCTouch* touch, CCEvent* pEvent) + { + if (!isTouchInside(touch)) + return false; + + CCPoint location = getTouchLocationInControl(touch); + sliderBegan(location); + return true; +} + +void CCControlSlider::ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent) +{ + CCPoint location = getTouchLocationInControl(pTouch); + sliderMoved(location); +} + +void CCControlSlider::ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent) +{ + CCPoint location = getTouchLocationInControl(pTouch); + sliderEnded(CCPointZero); +} + +void CCControlSlider::sliderBegan(CCPoint location) +{ + m_thumbItem->selected(); + setValue(valueForLocation(location)); +} + +void CCControlSlider::sliderMoved(CCPoint location) +{ + setValue(valueForLocation(location)); +} + +void CCControlSlider::sliderEnded(CCPoint location) +{ + if (m_thumbItem->getIsSelected()) + { + m_thumbItem->unselected(); + setValue(valueForLocation(m_thumbItem->getPosition())); + } +} + +float CCControlSlider::valueForLocation(CCPoint location) +{ + float percent = (location.x-SLIDER_MARGIN_H)/ m_backgroundSprite->getContentSize().width; + return m_minimumValue + percent * (m_maximumValue - m_minimumValue); +} + +NS_CC_END diff --git a/cocos2dx/extensions/CCControlExtension/CCControlSlider.h b/cocos2dx/extensions/CCControlExtension/CCControlSlider.h new file mode 100644 index 0000000000..f8131f47b8 --- /dev/null +++ b/cocos2dx/extensions/CCControlExtension/CCControlSlider.h @@ -0,0 +1,111 @@ +/* + * CCControlSlider + * + * Copyright 2011 Yannick Loriot. All rights reserved. + * http://yannickloriot.com + * + * 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. + * + * Converted to c++ / cocos2d-x by Angus C + */ + + +#ifndef __CCCONTROL_SLIDER_H__ +#define __CCCONTROL_SLIDER_H__ + +#include "CCControl.h" +#include "CCInvocation.h" +#include "CCSprite.h" +#include "CCMenuItem.h" + +#define SLIDER_MARGIN_H 24 +#define SLIDER_MARGIN_V 8 + +NS_CC_BEGIN + +class CC_DLL CCControlSlider: public CCControl +{ + //maunally put in the setters + CC_SYNTHESIZE_READONLY(float, m_value, Value); + virtual void setValue(float val); + CC_SYNTHESIZE_READONLY(float, m_minimumValue, MinimumValue); + virtual void setMinimumValue(float val); + CC_SYNTHESIZE_READONLY(float, m_maximumValue, MaximumValue); + virtual void setMaximumValue(float val); + + //interval to snap to + CC_SYNTHESIZE(float, m_snappingInterval, SnappingInterval); + + // maybe this should be read-only + CC_SYNTHESIZE_READONLY(CCMenuItem*, m_thumbItem, ThumbItem); + CC_SYNTHESIZE_READONLY(CCSprite*, m_progressSprite, ProgressSprite); + CC_SYNTHESIZE_READONLY(CCSprite*, m_backgroundSprite, BackgroundSprite); + +public: + + virtual ~CCControlSlider(); + + /** + * Initializes a slider with a background sprite, a progress bar and a thumb + * item. + * + * @param backgroundSprite CCSprite, that is used as a background. + * @param progressSprite CCSprite, that is used as a progress bar. + * @param thumbItem CCMenuItem, that is used as a thumb. + */ + virtual bool initWithSprites(CCSprite * backgroundSprite, CCSprite* progessSprite, CCMenuItem* thumbItem); + + + /** + * Creates slider with a background filename, a progress filename and a + * thumb image filename. + */ + static CCControlSlider* sliderWithFiles(const char* bgFile, const char* progressFile, const char* thumbFile); + + /** + * Creates a slider with a given background sprite and a progress bar and a + * thumb item. + * + * @see initWithBackgroundSprite:progressSprite:thumbMenuItem: + */ + static CCControlSlider* sliderWithSprites(CCSprite * backgroundSprite, CCSprite* pogressSprite, CCMenuItem* thumbItem); + + + + +protected: + void sliderBegan(CCPoint location); + void sliderMoved(CCPoint location); + void sliderEnded(CCPoint location); + + virtual CCPoint getTouchLocationInControl(CCTouch* touch); + + virtual bool ccTouchBegan(CCTouch* touch, CCEvent* pEvent); + virtual void ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent); + virtual void ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent); + + + +/** Returns the value for the given location. */ + float valueForLocation(CCPoint location); +}; + +NS_CC_END + +#endif \ No newline at end of file diff --git a/cocos2dx/extensions/CCControlExtension/CCControlSwitch.cpp b/cocos2dx/extensions/CCControlExtension/CCControlSwitch.cpp new file mode 100644 index 0000000000..84676921d2 --- /dev/null +++ b/cocos2dx/extensions/CCControlExtension/CCControlSwitch.cpp @@ -0,0 +1,441 @@ +/* + * + * Copyright 2012 Yannick Loriot. All rights reserved. + * http://yannickloriot.com + * + * 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. + * + */ + +#include "CCControlSwitch.h" +#include "CCPointExtension.h" +#include "CCLabelTTF.h" +#include "CCRenderTexture.h" +#include "CCTouch.h" +#include "CCDirector.h" +#include "ccShaders.h" +#include "CCActionTween.h" + +NS_CC_BEGIN + +// CCControlSwitchSprite + +class CCControlSwitchSprite : public CCSprite, public CCActionTweenDelegate +{ +public: + CCControlSwitchSprite(); + virtual ~CCControlSwitchSprite(); + bool initWithMaskSprite( + CCSprite *maskSprite, + CCSprite *onSprite, + CCSprite *offSprite, + CCSprite *thumbSprite, + CCLabelTTF* onLabel, + CCLabelTTF* offLabel); + void draw(); + void needsLayout(); + void setSliderXPosition(CCFloat sliderXPosition); + CCFloat getSliderXPosition() {return m_fSliderXPosition;} + CCFloat onSideWidth(); + CCFloat offSideWidth(); + virtual void updateTweenAction(float value, const char* key); +/** Contains the position (in x-axis) of the slider inside the receiver. */ + CCFloat m_fSliderXPosition; + CC_SYNTHESIZE(CCFloat, m_fOnPosition, OnPosition) + CC_SYNTHESIZE(CCFloat, m_fOffPosition, OffPosition) + + CC_SYNTHESIZE_RETAIN(CCTexture2D*, m_pMaskTexture, MaskTexture) + CC_SYNTHESIZE(GLuint, m_uTextureLocation, TextureLocation) + CC_SYNTHESIZE(GLuint, m_uMaskLocation, MaskLocation) + + CC_SYNTHESIZE_RETAIN(CCSprite*, m_pOnSprite, OnSprite) + CC_SYNTHESIZE_RETAIN(CCSprite*, m_pOffSprite, OffSprite) + CC_SYNTHESIZE_RETAIN(CCSprite*, m_ThumbSprite, ThumbSprite) + CC_SYNTHESIZE_RETAIN(CCLabelTTF*, m_pOnLabel, OnLabel) + CC_SYNTHESIZE_RETAIN(CCLabelTTF*, m_pOffLabel, OffLabel) +}; + +CCControlSwitchSprite::CCControlSwitchSprite() +: m_fSliderXPosition(0.0f) +, m_fOnPosition(0.0f) +, m_fOffPosition(0.0f) +, m_pMaskTexture(NULL) +, m_uTextureLocation(0) +, m_uMaskLocation(0) +, m_pOnSprite(NULL) +, m_pOffSprite(NULL) +, m_ThumbSprite(NULL) +, m_pOnLabel(NULL) +, m_pOffLabel(NULL) +{ + +} + +CCControlSwitchSprite::~CCControlSwitchSprite() +{ + CC_SAFE_RELEASE(m_pOnSprite); + CC_SAFE_RELEASE(m_pOffSprite); + CC_SAFE_RELEASE(m_ThumbSprite); + CC_SAFE_RELEASE(m_pOnLabel); + CC_SAFE_RELEASE(m_pOffLabel); + CC_SAFE_RELEASE(m_pMaskTexture); +} + +bool CCControlSwitchSprite::initWithMaskSprite( + CCSprite *maskSprite, + CCSprite *onSprite, + CCSprite *offSprite, + CCSprite *thumbSprite, + CCLabelTTF* onLabel, + CCLabelTTF* offLabel) +{ + if (CCSprite::initWithTexture(maskSprite->getTexture())) + { + // Sets the default values + m_fOnPosition = 0; + m_fOffPosition = -onSprite->getContentSize().width + thumbSprite->getContentSize().width / 2; + m_fSliderXPosition = m_fOnPosition; + + setOnSprite(onSprite); + setOffSprite(offSprite); + setThumbSprite(thumbSprite); + setOnLabel(onLabel); + setOffLabel(offLabel); + + addChild(m_ThumbSprite); + + // Set up the mask with the Mask shader + setMaskTexture(maskSprite->getTexture()); + CCGLProgram* pProgram = new CCGLProgram(); + pProgram->initWithVertexShaderByteArray(ccPositionTextureColor_vert, ccExSwitchMask_frag); + setShaderProgram(pProgram); + pProgram->release(); + + CHECK_GL_ERROR_DEBUG(); + + getShaderProgram()->addAttribute(kCCAttributeNamePosition, kCCVertexAttrib_Position); + getShaderProgram()->addAttribute(kCCAttributeNameColor, kCCVertexAttrib_Color); + getShaderProgram()->addAttribute(kCCAttributeNameTexCoord, kCCVertexAttrib_TexCoords); + CHECK_GL_ERROR_DEBUG(); + + getShaderProgram()->link(); + CHECK_GL_ERROR_DEBUG(); + + getShaderProgram()->updateUniforms(); + CHECK_GL_ERROR_DEBUG(); + + m_uTextureLocation = glGetUniformLocation( getShaderProgram()->getProgram(), "u_texture"); + m_uMaskLocation = glGetUniformLocation( getShaderProgram()->getProgram(), "u_mask"); + CHECK_GL_ERROR_DEBUG(); + + setContentSize(m_pMaskTexture->getContentSize()); + + needsLayout(); + return true; + } + return false; +} + +void CCControlSwitchSprite::updateTweenAction(float value, const char* key) +{ + CCLOG("key = %s, value = %f", key, value); + setSliderXPosition(value); +} + +void CCControlSwitchSprite::draw() +{ + CC_NODE_DRAW_SETUP(); + + ccGLEnableVertexAttribs(kCCVertexAttribFlag_PosColorTex); + ccGLBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + getShaderProgram()->setUniformForModelViewProjectionMatrix(); + + glActiveTexture(GL_TEXTURE0); + glBindTexture( GL_TEXTURE_2D, getTexture()->getName()); + glUniform1i(m_uTextureLocation, 0); + + glActiveTexture(GL_TEXTURE1); + glBindTexture( GL_TEXTURE_2D, m_pMaskTexture->getName() ); + glUniform1i(m_uMaskLocation, 1); + +#define kQuadSize sizeof(m_sQuad.bl) + long offset = (long)&m_sQuad; + + // vertex + int diff = offsetof( ccV3F_C4B_T2F, vertices); + glVertexAttribPointer(kCCVertexAttrib_Position, 3, GL_FLOAT, GL_FALSE, kQuadSize, (void*) (offset + diff)); + + // texCoods + diff = offsetof( ccV3F_C4B_T2F, texCoords); + glVertexAttribPointer(kCCVertexAttrib_TexCoords, 2, GL_FLOAT, GL_FALSE, kQuadSize, (void*)(offset + diff)); + + // color + diff = offsetof( ccV3F_C4B_T2F, colors); + glVertexAttribPointer(kCCVertexAttrib_Color, 4, GL_UNSIGNED_BYTE, GL_TRUE, kQuadSize, (void*)(offset + diff)); + + glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); + glActiveTexture(GL_TEXTURE0); +} + +void CCControlSwitchSprite::needsLayout() +{ + m_pOnSprite->setPosition(ccp(m_pOnSprite->getContentSize().width / 2 + m_fSliderXPosition, + m_pOnSprite->getContentSize().height / 2)); + m_pOffSprite->setPosition(ccp(m_pOnSprite->getContentSize().width + m_pOffSprite->getContentSize().width / 2 + m_fSliderXPosition, + m_pOffSprite->getContentSize().height / 2)); + m_ThumbSprite->setPosition(ccp(m_pOnSprite->getContentSize().width + m_fSliderXPosition, + m_pMaskTexture->getContentSize().height / 2)); + + if (m_pOnLabel) + { + m_pOnLabel->setPosition(ccp(m_pOnSprite->getPosition().x - m_ThumbSprite->getContentSize().width / 6, + m_pOnSprite->getContentSize().height / 2)); + } + if (m_pOffLabel) + { + m_pOffLabel->setPosition(ccp(m_pOffSprite->getPosition().x + m_ThumbSprite->getContentSize().width / 6, + m_pOffSprite->getContentSize().height / 2)); + } + + CCRenderTexture *rt = CCRenderTexture::renderTextureWithWidthAndHeight(m_pMaskTexture->getContentSize().width, m_pMaskTexture->getContentSize().height); + + rt->begin(); + m_pOnSprite->visit(); + m_pOffSprite->visit(); + + if (m_pOnLabel) + { + m_pOnLabel->visit(); + } + if (m_pOffLabel) + { + m_pOffLabel->visit(); + } + + rt->end(); + + setTexture(rt->getSprite()->getTexture()); + setFlipY(true); +} + +void CCControlSwitchSprite::setSliderXPosition(CCFloat sliderXPosition) +{ + if (sliderXPosition <= m_fOffPosition) + { + // Off + sliderXPosition = m_fOffPosition; + } else if (sliderXPosition >= m_fOnPosition) + { + // On + sliderXPosition = m_fOnPosition; + } + + m_fSliderXPosition = sliderXPosition; + + needsLayout(); +} + + +CCFloat CCControlSwitchSprite::onSideWidth() +{ + return m_pOnSprite->getContentSize().width; +} + +CCFloat CCControlSwitchSprite::offSideWidth() +{ + return m_pOffSprite->getContentSize().height; +} + + +// CCControlSwitch + +CCControlSwitch::CCControlSwitch() +{ + +} + +CCControlSwitch::~CCControlSwitch() +{ + CC_SAFE_RELEASE(m_pSwitchSprite); +} + +bool CCControlSwitch::initWithMaskSprite(CCSprite *maskSprite, CCSprite * onSprite, CCSprite * offSprite, CCSprite * thumbSprite) +{ + return initWithMaskSprite(maskSprite, onSprite, offSprite, thumbSprite, NULL, NULL); +} + +CCControlSwitch* CCControlSwitch::switchWithMaskSprite(CCSprite *maskSprite, CCSprite * onSprite, CCSprite * offSprite, CCSprite * thumbSprite) +{ + CCControlSwitch* pRet = new CCControlSwitch(); + if (pRet && pRet->initWithMaskSprite(maskSprite, onSprite, offSprite, thumbSprite, NULL, NULL)) + { + pRet->autorelease(); + } + else + { + CC_SAFE_DELETE(pRet); + } + return pRet; +} + +bool CCControlSwitch::initWithMaskSprite(CCSprite *maskSprite, CCSprite * onSprite, CCSprite * offSprite, CCSprite * thumbSprite, CCLabelTTF* onLabel, CCLabelTTF* offLabel) +{ + if (CCControl::init()) + { + CCAssert(maskSprite, "Mask must not be nil."); + CCAssert(onSprite, "onSprite must not be nil."); + CCAssert(offSprite, "offSprite must not be nil."); + CCAssert(thumbSprite, "thumbSprite must not be nil."); + + setIsTouchEnabled(true); + m_bOn = true; + + m_pSwitchSprite = new CCControlSwitchSprite(); + m_pSwitchSprite->initWithMaskSprite(maskSprite, + onSprite, + offSprite, + thumbSprite, + onLabel, + offLabel); + m_pSwitchSprite->setPosition(ccp (m_pSwitchSprite->getContentSize().width / 2, m_pSwitchSprite->getContentSize().height / 2)); + addChild(m_pSwitchSprite); + + setIsRelativeAnchorPoint(true); + setAnchorPoint(ccp (0.5f, 0.5f)); + setContentSize(m_pSwitchSprite->getContentSize()); + return true; + } + return false; +} + +CCControlSwitch* CCControlSwitch::switchWithMaskSprite(CCSprite *maskSprite, CCSprite * onSprite, CCSprite * offSprite, CCSprite * thumbSprite, CCLabelTTF* onLabel, CCLabelTTF* offLabel) +{ + CCControlSwitch* pRet = new CCControlSwitch(); + if (pRet && pRet->initWithMaskSprite(maskSprite, onSprite, offSprite, thumbSprite, onLabel, offLabel)) + { + pRet->autorelease(); + } + else + { + CC_SAFE_DELETE(pRet); + } + return pRet; +} + +void CCControlSwitch::setOn(bool isOn) +{ + setOn(isOn, false); +} + +void CCControlSwitch::setOn(bool isOn, bool animated) +{ + m_bOn = isOn; + + m_pSwitchSprite->runAction + ( + CCActionTween::actionWithDuration + ( + 0.2f, + "sliderXPosition", + m_pSwitchSprite->getSliderXPosition(), + (m_bOn) ? m_pSwitchSprite->getOnPosition() : m_pSwitchSprite->getOffPosition() + ) + ); + + sendActionsForControlEvents(CCControlEventValueChanged); +} + +void CCControlSwitch::setIsEnabled(bool enabled) +{ + m_bEnabled = enabled; + + m_pSwitchSprite->setOpacity((enabled) ? 255.0f : 128.0f); +} + +CCPoint CCControlSwitch::locationFromTouch(CCTouch* pTouch) +{ + CCPoint touchLocation = pTouch->locationInView(); // Get the touch position + touchLocation = CCDirector::sharedDirector()->convertToGL(touchLocation); // Convert the position to GL space + touchLocation = this->convertToNodeSpace(touchLocation); // Convert to the node space of this class + + return touchLocation; +} + +bool CCControlSwitch::ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent) +{ + if (!this->isTouchInside(pTouch) + || !this->getIsEnabled()) + { + return false; + } + + m_bMoved = false; + + CCPoint location = this->locationFromTouch(pTouch); + + m_fInitialTouchXPosition = location.x - m_pSwitchSprite->getSliderXPosition(); + + m_pSwitchSprite->getThumbSprite()->setColor(ccGRAY); + m_pSwitchSprite->needsLayout(); + + return true; +} + +void CCControlSwitch::ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent) +{ + CCPoint location = this->locationFromTouch(pTouch); + location = ccp (location.x - m_fInitialTouchXPosition, 0); + + m_bMoved = true; + + m_pSwitchSprite->setSliderXPosition(location.x); +} + +void CCControlSwitch::ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent) +{ + CCPoint location = this->locationFromTouch(pTouch); + + m_pSwitchSprite->getThumbSprite()->setColor(ccWHITE); + + if (hasMoved()) + { + setOn(!(location.x < m_pSwitchSprite->getContentSize().width / 2), true); + } + else + { + setOn(!m_bOn, true); + } +} + +void CCControlSwitch::ccTouchCancelled(CCTouch *pTouch, CCEvent *pEvent) +{ + CCPoint location = this->locationFromTouch(pTouch); + + m_pSwitchSprite->getThumbSprite()->setColor(ccWHITE); + + if (hasMoved()) + { + setOn(!(location.x < m_pSwitchSprite->getContentSize().width / 2), true); + } else + { + setOn(!m_bOn, true); + } +} + +NS_CC_END diff --git a/cocos2dx/extensions/CCControlExtension/CCControlSwitch.h b/cocos2dx/extensions/CCControlExtension/CCControlSwitch.h new file mode 100644 index 0000000000..37492fda80 --- /dev/null +++ b/cocos2dx/extensions/CCControlExtension/CCControlSwitch.h @@ -0,0 +1,91 @@ +/* + * CCControlSwitch.h + * + * Copyright 2012 Yannick Loriot. All rights reserved. + * http://yannickloriot.com + * + * 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 __CCCONTROLSWITCH_H__ +#define __CCCONTROLSWITCH_H__ + +#include "CCControl.h" + +NS_CC_BEGIN + +class CCControlSwitchSprite; +class CCSprite; +class CCLabelTTF; + +/** @class CCControlSwitch Switch control for Cocos2D. */ +class CC_DLL CCControlSwitch : public CCControl +{ +public: + CCControlSwitch(); + virtual ~CCControlSwitch(); + /** Initializes a switch with a mask sprite, on/off sprites for on/off states and a thumb sprite. */ + bool initWithMaskSprite(CCSprite *maskSprite, CCSprite * onSprite, CCSprite * offSprite, CCSprite * thumbSprite); + + /** Creates a switch with a mask sprite, on/off sprites for on/off states and a thumb sprite. */ + static CCControlSwitch* switchWithMaskSprite(CCSprite *maskSprite, CCSprite * onSprite, CCSprite * offSprite, CCSprite * thumbSprite); + + /** Initializes a switch with a mask sprite, on/off sprites for on/off states, a thumb sprite and an on/off labels. */ + bool initWithMaskSprite(CCSprite *maskSprite, CCSprite * onSprite, CCSprite * offSprite, CCSprite * thumbSprite, CCLabelTTF* onLabel, CCLabelTTF* offLabel); + + /** Creates a switch with a mask sprite, on/off sprites for on/off states, a thumb sprite and an on/off labels. */ + static CCControlSwitch* switchWithMaskSprite(CCSprite *maskSprite, CCSprite * onSprite, CCSprite * offSprite, CCSprite * thumbSprite, CCLabelTTF* onLabel, CCLabelTTF* offLabel); + + /** + * Set the state of the switch to On or Off, optionally animating the transition. + * + * @param isOn YES if the switch should be turned to the On position; NO if it + * should be turned to the Off position. If the switch is already in the + * designated position, nothing happens. + * @param animated YES to animate the "flipping" of the switch; otherwise NO. + */ + void setOn(bool isOn, bool animated); + void setOn(bool isOn); + bool getIsOn(void) { return m_bOn; } + bool hasMoved() { return m_bMoved; } + void setIsEnabled(bool enabled); + + CCPoint locationFromTouch(CCTouch* touch); + //events + virtual bool ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent); + virtual void ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent); + virtual void ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent); + virtual void ccTouchCancelled(CCTouch *pTouch, CCEvent *pEvent); + +protected: + /** Sprite which represents the view. */ + CCControlSwitchSprite* m_pSwitchSprite; + CCFloat m_fInitialTouchXPosition; + + bool m_bMoved; + /** A Boolean value that determines the off/on state of the switch. */ + bool m_bOn; +}; + + +NS_CC_END + +#endif /* __CCCONTROLSWITCH_H__ */ + diff --git a/cocos2dx/extensions/CCControlExtension/CCControlUtils.cpp b/cocos2dx/extensions/CCControlExtension/CCControlUtils.cpp new file mode 100644 index 0000000000..691d246f15 --- /dev/null +++ b/cocos2dx/extensions/CCControlExtension/CCControlUtils.cpp @@ -0,0 +1,149 @@ +#include "CCControlUtils.h" +#include "CCPointExtension.h" + +NS_CC_BEGIN + +CCSprite* CCControlUtils::addSpriteToTargetWithPosAndAnchor(const char* spriteName, CCNode * target, CCPoint pos, CCPoint anchor) +{ + CCSprite *sprite =CCSprite::spriteWithSpriteFrameName(spriteName); + + if (!sprite) + return NULL; + + sprite->setPosition(pos); + sprite->setAnchorPoint(anchor); + target->addChild(sprite); + + return sprite; +} + + +HSV CCControlUtils::HSVfromRGB(RGBA value) +{ + HSV out; + double min, max, delta; + + min = value.r < value.g ? value.r : value.g; + min = min < value.b ? min : value.b; + + max = value.r > value.g ? value.r : value.g; + max = max > value.b ? max : value.b; + + out.v = max; // v + delta = max - min; + if( max > 0.0 ) + { + out.s = (delta / max); // s + } else + { + // r = g = b = 0 // s = 0, v is undefined + out.s = 0.0; + out.h = -1; // its now undefined (don't know if setting to NAN is a good idea) + return out; + } + if( value.r >= max ) // > is bogus, just keeps compilor happy + { + out.h = ( value.g - value.b ) / delta; // between yellow & magenta + } else + { + if( value.g >= max ) + out.h = 2.0 + ( value.b - value.r ) / delta; // between cyan & yellow + else + out.h = 4.0 + ( value.r - value.g ) / delta; // between magenta & cyan + } + + out.h *= 60.0; // degrees + + if( out.h < 0.0 ) + out.h += 360.0; + + return out; +} + +RGBA CCControlUtils::RGBfromHSV(HSV value) +{ + double hh, p, q, t, ff; + long i; + RGBA out; + out.a = 1; + + if (value.s <= 0.0) // < is bogus, just shuts up warnings + { + if (isnan(value.h)) // value.h == NAN + { + out.r = value.v; + out.g = value.v; + out.b = value.v; + return out; + } + + // error - should never happen + out.r = 0.0; + out.g = 0.0; + out.b = 0.0; + return out; + } + + hh = value.h; + if(hh >= 360.0) hh = 0.0; + hh /= 60.0; + i = (long)hh; + ff = hh - i; + p = value.v * (1.0 - value.s); + q = value.v * (1.0 - (value.s * ff)); + t = value.v * (1.0 - (value.s * (1.0 - ff))); + + switch(i) + { + case 0: + out.r = value.v; + out.g = t; + out.b = p; + break; + case 1: + out.r = q; + out.g = value.v; + out.b = p; + break; + case 2: + out.r = p; + out.g = value.v; + out.b = t; + break; + + case 3: + out.r = p; + out.g = q; + out.b = value.v; + break; + case 4: + out.r = t; + out.g = p; + out.b = value.v; + break; + case 5: + default: + out.r = value.v; + out.g = p; + out.b = q; + break; + } + return out; +} + +CCRect CCControlUtils::CCRectUnion(const CCRect& src1, const CCRect& src2) +{ + CCRect result; + + float x1 = MIN(CCRect::CCRectGetMinX(src1), CCRect::CCRectGetMinX(src2)); + float y1 = MIN(CCRect::CCRectGetMinY(src1), CCRect::CCRectGetMinY(src2)); + + float x2 = MAX(CCRect::CCRectGetMaxX(src1), CCRect::CCRectGetMaxX(src2)); + float y2 = MAX(CCRect::CCRectGetMaxY(src1), CCRect::CCRectGetMaxY(src2)); + + result.origin=ccp(x1,x2); + result.size=CCSizeMake(x2-x1, y2-y1); + return result; +} + +NS_CC_END diff --git a/cocos2dx/extensions/CCControlExtension/CCControlUtils.h b/cocos2dx/extensions/CCControlExtension/CCControlUtils.h new file mode 100644 index 0000000000..0db24e15b5 --- /dev/null +++ b/cocos2dx/extensions/CCControlExtension/CCControlUtils.h @@ -0,0 +1,74 @@ +/* + * ColourUtils.h + * + * Copyright 2012 Stewart Hamilton-Arrandale. + * http://creativewax.co.uk + * + * Modified by Yannick Loriot. + * http://yannickloriot.com + * + * 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. + * + * + * Converted to c++ / cocos2d-x by Angus C + */ + +#ifndef __CCCONTROL_UTILS_H__ +#define __CCCONTROL_UTILS_H__ + +#include "CCSprite.h" + +NS_CC_BEGIN + +typedef struct +{ + double r; // percent + double g; // percent + double b; // percent + double a; // percent +} RGBA; + +typedef struct +{ + double h; // angle in degrees + double s; // percent + double v; // percent +} HSV; + + +//helper class to store ccColor3B's in mutable arrays +class CC_DLL CCColor3bObject : public CCObject +{ +public: + ccColor3B value; + CCColor3bObject(ccColor3B s_value):value(s_value){} +}; + +class CCControlUtils +{ +public: + static CCSprite* addSpriteToTargetWithPosAndAnchor(const char* spriteName, CCNode * target, CCPoint pos, CCPoint anchor); + static HSV HSVfromRGB(RGBA value); + static RGBA RGBfromHSV(HSV value); + static CCRect CCRectUnion(const CCRect& src1, const CCRect& src2); +}; + +NS_CC_END + +#endif \ No newline at end of file diff --git a/cocos2dx/extensions/CCControlExtension/CCInvocation.cpp b/cocos2dx/extensions/CCControlExtension/CCInvocation.cpp new file mode 100644 index 0000000000..031cdcae7c --- /dev/null +++ b/cocos2dx/extensions/CCControlExtension/CCInvocation.cpp @@ -0,0 +1,20 @@ +#include "CCInvocation.h" + +NS_CC_BEGIN + +CCInvocation::CCInvocation(CCObject* target, SEL_MenuHandler action, CCControlEvent controlEvent) +{ + m_target=target; + m_action=action; + m_controlEvent=controlEvent; +} + +void CCInvocation::invoke(CCObject* sender) +{ + if (m_target && m_action) + { + (m_target->*m_action)(sender); + } +} + +NS_CC_END diff --git a/cocos2dx/extensions/CCControlExtension/CCInvocation.h b/cocos2dx/extensions/CCControlExtension/CCInvocation.h new file mode 100644 index 0000000000..4df44cea5e --- /dev/null +++ b/cocos2dx/extensions/CCControlExtension/CCInvocation.h @@ -0,0 +1,28 @@ + /* + * + * Helper class to store targets and selectors (and eventually, params?) in the same CCMutableArray. Basically a very crude form of a NSInvocation + */ +#ifndef __CCINVOCATION_H__ +#define __CCINVOCATION_H__ + +#include "CCObject.h" + +NS_CC_BEGIN + +typedef unsigned int CCControlEvent; + +class CC_DLL CCInvocation : public CCObject +{ + CC_SYNTHESIZE_READONLY(SEL_MenuHandler, m_action, Action); + CC_SYNTHESIZE_READONLY(CCObject*, m_target, Target); + CC_SYNTHESIZE_READONLY(CCControlEvent, m_controlEvent, ControlEvent); + +public: + CCInvocation(CCObject* target, SEL_MenuHandler action, CCControlEvent controlEvent); + + void invoke(CCObject* sender); +}; + +NS_CC_END + +#endif \ No newline at end of file diff --git a/cocos2dx/extensions/CCControlExtension/CCMenuPassive.cpp b/cocos2dx/extensions/CCControlExtension/CCMenuPassive.cpp new file mode 100644 index 0000000000..aeb9fc689d --- /dev/null +++ b/cocos2dx/extensions/CCControlExtension/CCMenuPassive.cpp @@ -0,0 +1,440 @@ +#include "CCMenuPassive.h" +#include "CCDirector.h" +#include "CCPointExtension.h" +#include "CCMenuItem.h" +#include + +using namespace std; + +NS_CC_BEGIN + +enum +{ + kDefaultPadding = 5, +}; + +// +//CCMenu +// + + CCMenuPassive* CCMenuPassive::node() + { + return menuWithItem(NULL); + } + +CCMenuPassive * CCMenuPassive::menuWithItems(CCNode* item, ...) +{ + va_list args; + va_start(args,item); + CCMenuPassive *pRet = new CCMenuPassive(); + if (pRet && pRet->initWithItems(item, args)) + { + pRet->autorelease(); + va_end(args); + return pRet; + } + va_end(args); + CC_SAFE_DELETE(pRet); + return NULL; +} + +CCMenuPassive* CCMenuPassive::menuWithItem(CCNode* item) +{ + return menuWithItems(item, NULL); +} + +bool CCMenuPassive::initWithItems(CCNode* item, va_list args) +{ + if (CCLayer::init()) + { + //this->m_bIsTouchEnabled = false; + + // menu in the center of the screen + CCSize s = CCDirector::sharedDirector()->getWinSize(); + + // Set the default anchor point + setIsRelativeAnchorPoint(false); + setAnchorPoint(ccp(0.5f, 0.5f)); + this->setContentSize(s); + + setPosition(ccp(s.width/2, s.height/2)); + + int z=0; + + if (item) + { + this->addChild(item, z); + CCMenuItem *i = va_arg(args, CCMenuItem*); + while (i) + { + z++; + this->addChild(i, z); + i = va_arg(args, CCMenuItem*); + } + } + + return true; + } + + return false; +} + + +//Menu - Alignment +void CCMenuPassive::alignItemsVertically() +{ + this->alignItemsVerticallyWithPadding(kDefaultPadding); +} + +void CCMenuPassive::alignItemsVerticallyWithPadding(float padding) +{ + float height = -padding; + if (m_pChildren && m_pChildren->count() > 0) + { + CCObject* pObject = NULL; + CCARRAY_FOREACH(m_pChildren, pObject) + { + CCNode* pChild = dynamic_cast(pObject); + if (pChild) + { + height += pChild->getContentSize().height * pChild->getScaleY() + padding; + } + } + } + float width=0; + float y = height / 2.0f; + if (m_pChildren && m_pChildren->count() > 0) + { + CCObject* pObject = NULL; + CCARRAY_FOREACH(m_pChildren, pObject) + { + CCNode* pChild = dynamic_cast(pObject); + if (pChild) + { + width=max(width, pChild->getContentSize().width); + pChild->setPosition(ccp(0, y - pChild->getContentSize().height * pChild->getScaleY() / 2.0f)); + y -= pChild->getContentSize().height * pChild->getScaleY() + padding; + } + } + } + setContentSize(CCSizeMake(width, height)); +} + +void CCMenuPassive::alignItemsHorizontally(void) +{ + this->alignItemsHorizontallyWithPadding(kDefaultPadding); +} + +void CCMenuPassive::alignItemsHorizontallyWithPadding(float padding) +{ + + float width = -padding; + if (m_pChildren && m_pChildren->count() > 0) + { + CCObject* pObject = NULL; + CCARRAY_FOREACH(m_pChildren, pObject) + { + CCNode* pChild = dynamic_cast(pObject); + if (pChild) + { + width += pChild->getContentSize().width * pChild->getScaleX() + padding; + } + } + } + + float height=0; + float x = -width / 2.0f; + if (m_pChildren && m_pChildren->count() > 0) + { + CCObject* pObject = NULL; + CCARRAY_FOREACH(m_pChildren, pObject) + { + CCNode* pChild = dynamic_cast(pObject); + if (pChild) + { + height=max(height, pChild->getContentSize().height); + pChild->setPosition(ccp(x + pChild->getContentSize().width * pChild->getScaleX() / 2.0f, 0)); + x += pChild->getContentSize().width * pChild->getScaleX() + padding; + } + } + } + setContentSize(CCSizeMake(width, height)); +} + +void CCMenuPassive::alignItemsInColumns(unsigned int columns, ...) +{ + va_list args; + va_start(args, columns); + + this->alignItemsInColumns(columns, args); + + va_end(args); +} + +void CCMenuPassive::alignItemsInColumns(unsigned int columns, va_list args) +{ + vector rows; + while (columns) + { + rows.push_back(columns); + columns = va_arg(args, unsigned int); + } + + int height = -5; + unsigned int row = 0; + unsigned int rowHeight = 0; + unsigned int columnsOccupied = 0; + unsigned int rowColumns; + + if (m_pChildren && m_pChildren->count() > 0) + { + CCObject* pObject = NULL; + CCARRAY_FOREACH(m_pChildren, pObject) + { + CCNode* pChild = dynamic_cast(pObject); + if (pChild) + { + CCAssert(row < rows.size(), ""); + + rowColumns = rows[row]; + // can not have zero columns on a row + CCAssert(rowColumns, ""); + + float tmp = pChild->getContentSize().height; + rowHeight = (unsigned int)((rowHeight >= tmp || isnan(tmp)) ? rowHeight : tmp); + + ++columnsOccupied; + if (columnsOccupied >= rowColumns) + { + height += rowHeight + 5; + + columnsOccupied = 0; + rowHeight = 0; + ++row; + } + } + } + } + + // check if too many rows/columns for available menu items + CCAssert(! columnsOccupied, ""); + + CCSize winSize = CCDirector::sharedDirector()->getWinSize(); + + row = 0; + rowHeight = 0; + rowColumns = 0; + float w = 0.0; + float x = 0.0; + float y = (float)(height / 2); + + if (m_pChildren && m_pChildren->count() > 0) + { + CCObject* pObject = NULL; + CCARRAY_FOREACH(m_pChildren, pObject) + { + CCNode* pChild = dynamic_cast(pObject); + if (pChild) + { + if (rowColumns == 0) + { + rowColumns = rows[row]; + w = winSize.width / (1 + rowColumns); + x = w; + } + + float tmp = pChild->getContentSize().height; + rowHeight = (unsigned int)((rowHeight >= tmp || isnan(tmp)) ? rowHeight : tmp); + + pChild->setPosition(ccp(x - winSize.width / 2, + y - pChild->getContentSize().height / 2)); + + x += w; + ++columnsOccupied; + + if (columnsOccupied >= rowColumns) + { + y -= rowHeight + 5; + + columnsOccupied = 0; + rowColumns = 0; + rowHeight = 0; + ++row; + } + } + } + } +} + +void CCMenuPassive::alignItemsInRows(unsigned int rows, ...) +{ + va_list args; + va_start(args, rows); + + this->alignItemsInRows(rows, args); + + va_end(args); +} + +void CCMenuPassive::alignItemsInRows(unsigned int rows, va_list args) +{ + vector columns; + while (rows) + { + columns.push_back(rows); + rows = va_arg(args, unsigned int); + } + + vector columnWidths; + vector columnHeights; + + int width = -10; + int columnHeight = -5; + unsigned int column = 0; + unsigned int columnWidth = 0; + unsigned int rowsOccupied = 0; + unsigned int columnRows; + + if (m_pChildren && m_pChildren->count() > 0) + { + CCObject* pObject = NULL; + CCARRAY_FOREACH(m_pChildren, pObject) + { + CCNode* pChild = dynamic_cast(pObject); + if (pChild) + { + // check if too many menu items for the amount of rows/columns + CCAssert(column < columns.size(), ""); + + columnRows = columns[column]; + // can't have zero rows on a column + CCAssert(columnRows, ""); + + // columnWidth = fmaxf(columnWidth, [item contentSize].width); + float tmp = pChild->getContentSize().width; + columnWidth = (unsigned int)((columnWidth >= tmp || isnan(tmp)) ? columnWidth : tmp); + + columnHeight += (int)(pChild->getContentSize().height + 5); + ++rowsOccupied; + + if (rowsOccupied >= columnRows) + { + columnWidths.push_back(columnWidth); + columnHeights.push_back(columnHeight); + width += columnWidth + 10; + + rowsOccupied = 0; + columnWidth = 0; + columnHeight = -5; + ++column; + } + } + } + } + + // check if too many rows/columns for available menu items. + CCAssert(! rowsOccupied, ""); + + CCSize winSize = CCDirector::sharedDirector()->getWinSize(); + + column = 0; + columnWidth = 0; + columnRows = 0; + float x = (float)(-width / 2); + float y = 0.0; + + if (m_pChildren && m_pChildren->count() > 0) + { + CCObject* pObject = NULL; + CCARRAY_FOREACH(m_pChildren, pObject) + { + CCNode* pChild = dynamic_cast(pObject); + if (pChild) + { + if (columnRows == 0) + { + columnRows = columns[column]; + y = (float) columnHeights[column]; + } + + // columnWidth = fmaxf(columnWidth, [item contentSize].width); + float tmp = pChild->getContentSize().width; + columnWidth = (unsigned int)((columnWidth >= tmp || isnan(tmp)) ? columnWidth : tmp); + + pChild->setPosition(ccp(x + columnWidths[column] / 2, + y - winSize.height / 2)); + + y -= pChild->getContentSize().height + 10; + ++rowsOccupied; + + if (rowsOccupied >= columnRows) + { + x += columnWidth + 5; + rowsOccupied = 0; + columnRows = 0; + columnWidth = 0; + ++column; + } + } + } + } +} + +// Opacity Protocol + +/** Override synthesized setOpacity to recurse items */ +void CCMenuPassive::setOpacity(GLubyte var) +{ + m_cOpacity = var; + + if (m_pChildren && m_pChildren->count() > 0) + { + CCObject* pObject = NULL; + CCARRAY_FOREACH(m_pChildren, pObject) + { + CCNode* pChild = dynamic_cast(pObject); + if (pChild) + { + CCRGBAProtocol *pRGBAProtocol = dynamic_cast(pChild); + if (pRGBAProtocol) + { + pRGBAProtocol->setOpacity(m_cOpacity); + } + } + } + } +} + +GLubyte CCMenuPassive::getOpacity(void) +{ + return m_cOpacity; +} + +void CCMenuPassive::setColor(const ccColor3B& var) +{ + m_tColor = var; + + if (m_pChildren && m_pChildren->count() > 0) + { + CCObject* pObject = NULL; + CCARRAY_FOREACH(m_pChildren, pObject) + { + CCNode* pChild = dynamic_cast(pObject); + if (pChild) + { + CCRGBAProtocol *pRGBAProtocol = dynamic_cast(pChild); + if (pRGBAProtocol) + { + pRGBAProtocol->setColor(m_tColor); + } + } + } + } +} + +const ccColor3B& CCMenuPassive::getColor(void) +{ + return m_tColor; +} + +NS_CC_END diff --git a/cocos2dx/extensions/CCControlExtension/CCMenuPassive.h b/cocos2dx/extensions/CCControlExtension/CCMenuPassive.h new file mode 100644 index 0000000000..dbabba71db --- /dev/null +++ b/cocos2dx/extensions/CCControlExtension/CCMenuPassive.h @@ -0,0 +1,64 @@ +/* + * + * A menu that does not send any events, it's simply a passive container (lets the contents do their own thing) of CCNodes + */ +#ifndef __CCMENU_PASSIVE_H__ +#define __CCMENU_PASSIVE_H__ + +#include "CCControl.h" + +NS_CC_BEGIN + +class CC_DLL CCMenuPassive : public CCLayer, public CCRGBAProtocol +{ + /** Color: conforms with CCRGBAProtocol protocol */ + CC_PROPERTY_PASS_BY_REF(ccColor3B, m_tColor, Color); + /** Opacity: conforms with CCRGBAProtocol protocol */ + CC_PROPERTY(GLubyte, m_cOpacity, Opacity); + +public: + /** creates an empty CCMenu */ + static CCMenuPassive* node(); + + /** creates a CCMenu with it's items */ + static CCMenuPassive* menuWithItems(CCNode* item, ...); + + /** creates a CCMenu with it's item, then use addChild() to add + * other items. It is used for script, it can't init with undetermined + * number of variables. + */ + static CCMenuPassive*menuWithItem(CCNode* item); + + /** initializes a CCMenu with it's items */ + bool initWithItems(CCNode* item, va_list args); + + /** align items vertically */ + void alignItemsVertically(); + /** align items vertically with padding + @since v0.7.2 + */ + void alignItemsVerticallyWithPadding(float padding); + + /** align items horizontally */ + void alignItemsHorizontally(); + /** align items horizontally with padding + @since v0.7.2 + */ + void alignItemsHorizontallyWithPadding(float padding); + + /** align items in rows of columns */ + void alignItemsInColumns(unsigned int columns, ...); + void alignItemsInColumns(unsigned int columns, va_list args); + + /** align items in columns of rows */ + void alignItemsInRows(unsigned int rows, ...); + void alignItemsInRows(unsigned int rows, va_list args); + + //RGBA protocol + virtual void setIsOpacityModifyRGB(bool bValue) {CC_UNUSED_PARAM(bValue);} + virtual bool getIsOpacityModifyRGB(void) { return false;} +}; + +NS_CC_END + +#endif \ No newline at end of file diff --git a/cocos2dx/extensions/CCControlExtension/CCScale9Sprite.cpp b/cocos2dx/extensions/CCControlExtension/CCScale9Sprite.cpp new file mode 100644 index 0000000000..98eb1a35ba --- /dev/null +++ b/cocos2dx/extensions/CCControlExtension/CCScale9Sprite.cpp @@ -0,0 +1,464 @@ +// +// CCScale9Sprite.cpp +// PlantCaring +// +// Created by Jung Sang-Taik on 12. 3. 16.. +// Copyright (c) 2012 Neofect. All rights reserved. +// + +#include "CCScale9Sprite.h" +#include "CCSpriteBatchNode.h" +#include "CCSpriteFrame.h" +#include "CCSpriteFrameCache.h" +#include "CCSprite.h" +#include "CCPointExtension.h" + +NS_CC_BEGIN + +CCScale9Sprite::CCScale9Sprite() +{ + +} + +CCScale9Sprite::~CCScale9Sprite() +{ + +} + +bool CCScale9Sprite::initWithBatchNode(CCSpriteBatchNode* batchnode, CCRect rect, CCRect capInsets) +{ + + CCAssert(batchnode != NULL, "The batchnode must be not nil."); + + scale9Image = batchnode; + + // If there is no given rect + if ( CCRect::CCRectEqualToRect(rect, CCRectZero) ) + { + // Get the texture size as original + CCSize textureSize = scale9Image->getTextureAtlas()->getTexture()->getContentSize(); + + rect = CCRectMake(0, 0, textureSize.width, textureSize.height); + } + + // Set the given rect's size as original size + m_spriteRect = rect; + m_originalSize = rect.size; + m_preferredSize = m_originalSize; + m_capInsets = capInsets; + this->setAnchorPoint(ccp(0.5f, 0.5f)); + + // If there is no specified center region + if ( CCRect::CCRectEqualToRect(m_capInsets, CCRectZero) ) + { + // Apply the 3x3 grid format + m_capInsets = CCRectMake( + rect.origin.x + m_originalSize.width / 3, + rect.origin.y + m_originalSize.height / 3, + m_originalSize.width / 3, + m_originalSize.height / 3); + } + + // Get the image edges + float l = rect.origin.x; + float t = rect.origin.y; + float h = rect.size.height; + float w = rect.size.width; + + // + // Set up the image + // + + // Centre + centre = CCSprite::spriteWithTexture(scale9Image->getTexture(), m_capInsets); + scale9Image->addChild(centre ,0 ,pCentre); + + // Top + top = CCSprite::spriteWithTexture(scale9Image->getTexture(), CCRectMake(m_capInsets.origin.x, + t, + m_capInsets.size.width, + m_capInsets.origin.y - t)); + scale9Image->addChild(top, 1, pTop); + + // Bottom + bottom = CCSprite::spriteWithTexture(scale9Image->getTexture(), CCRectMake( m_capInsets.origin.x, + m_capInsets.origin.y + m_capInsets.size.height, + m_capInsets.size.width, + h - (m_capInsets.origin.y - t + m_capInsets.size.height) )); + scale9Image->addChild(bottom, 1, pBottom); + + // Left + left = CCSprite::spriteWithTexture(scale9Image->getTexture(), CCRectMake( + l, + m_capInsets.origin.y, + m_capInsets.origin.x - l, + m_capInsets.size.height) ); + scale9Image->addChild(left, 1, pLeft); + + // Right + right = CCSprite::spriteWithTexture(scale9Image->getTexture(), CCRectMake( + m_capInsets.origin.x + m_capInsets.size.width, + m_capInsets.origin.y, + w - (m_capInsets.origin.x - l + m_capInsets.size.width), + m_capInsets.size.height)); + scale9Image->addChild(right, 1, pRight); + + // Top left + topLeft = CCSprite::spriteWithTexture(scale9Image->getTexture(), CCRectMake( + l, + t, + m_capInsets.origin.x - l, + m_capInsets.origin.y - t)); + + scale9Image->addChild(topLeft, 2, pTopLeft); + + // Top right + topRight = CCSprite::spriteWithTexture(scale9Image->getTexture(), CCRectMake( + m_capInsets.origin.x + m_capInsets.size.width, + t, + w - (m_capInsets.origin.x - l + m_capInsets.size.width), + m_capInsets.origin.y - t)); + + scale9Image->addChild(topRight, 2, pTopRight); + + // Bottom left + bottomLeft = CCSprite::spriteWithTexture(scale9Image->getTexture(), CCRectMake( + l, + m_capInsets.origin.y + m_capInsets.size.height, + m_capInsets.origin.x - l, + h - (m_capInsets.origin.y - t + m_capInsets.size.height)) ); + scale9Image->addChild(bottomLeft, 2, pBottomLeft); + + // Bottom right + bottomRight = CCSprite::spriteWithTexture(scale9Image->getTexture(), CCRectMake( + m_capInsets.origin.x + m_capInsets.size.width, + m_capInsets.origin.y + m_capInsets.size.height, + w - (m_capInsets.origin.x - l + m_capInsets.size.width), + h - (m_capInsets.origin.y - t + m_capInsets.size.height)) ); + scale9Image->addChild(bottomRight, 2, pBottomRight); + + + this->setContentSize(rect.size); + this->addChild(scale9Image); + + return true; +} + +void CCScale9Sprite::setContentSize(const CCSize &size) +{ + + CCNode::setContentSize(size); + setAnchorPoint(ccp(0.5f,0.5f)); + + CCLOG("scale9 set content size %0.2f %0.2f",size.width,size.height); + CCLOG("leftCap %0.2f rightCap %0.2f",topLeft->getContentSize().width,topRight->getContentSize().width); + + float sizableWidth = size.width - topLeft->getContentSize().width - topRight->getContentSize().width; + float sizableHeight = size.height - topLeft->getContentSize().height - bottomRight->getContentSize().height; + float horizontalScale = sizableWidth/centre->getContentSize().width; + float verticalScale = sizableHeight/centre->getContentSize().height; + centre->setScaleX(horizontalScale); + centre->setScaleY(verticalScale); + float rescaledWidth = centre->getContentSize().width * horizontalScale; + float rescaledHeight = centre->getContentSize().height * verticalScale; + + float despx = size.width*0.5f; + float despy = size.height*0.5f; + + //Position corners + topLeft->setPosition(ccp(-rescaledWidth/2 - topLeft->getContentSize().width/2 +despx, rescaledHeight/2 + topLeft->getContentSize().height*0.5f +despy) ); + topRight->setPosition(ccp(rescaledWidth/2 + topRight->getContentSize().width/2 +despx, rescaledHeight/2 + topRight->getContentSize().height*0.5f +despy)); + bottomLeft->setPosition(ccp(-rescaledWidth/2 - bottomLeft->getContentSize().width/2 +despx, -rescaledHeight/2 - bottomLeft->getContentSize().height*0.5f +despy)); + bottomRight->setPosition(ccp(rescaledWidth/2 + bottomRight->getContentSize().width/2 +despx, -rescaledHeight/2 + -bottomRight->getContentSize().height*0.5f +despy)); + + top->setScaleX(horizontalScale); + top->setPosition(ccp(0+despx,rescaledHeight/2 + topLeft->getContentSize().height*0.5f +despy)); + bottom->setScaleX (horizontalScale); + bottom->setPosition(ccp(0+despx,-rescaledHeight/2 - bottomLeft->getContentSize().height*0.5f +despy)); + left->setScaleY (verticalScale); + left->setPosition(ccp(-rescaledWidth/2 - topLeft->getContentSize().width/2 +despx, 0+despy)); + right->setScaleY (verticalScale); + right->setPosition(ccp(rescaledWidth/2 + topRight->getContentSize().width/2 +despx, 0+despy)); + + centre->setPosition(ccp(despx, despy)); + + CCLOG("Scale9 setContentSize %02.f x %02.f <%0.2f x %0.2f>",sizableWidth,sizableHeight,horizontalScale,verticalScale); +} + +bool CCScale9Sprite::initWithFile(const char* file, CCRect rect, CCRect capInsets) +{ + CCAssert(file != NULL, "Invalid file for sprite"); + + CCSpriteBatchNode *batchnode = CCSpriteBatchNode::batchNodeWithFile(file, 9); + bool pReturn = this->initWithBatchNode(batchnode, rect, capInsets); + return pReturn; +} + +CCScale9Sprite* CCScale9Sprite::spriteWithFile(const char* file, CCRect rect, CCRect capInsets) +{ + CCScale9Sprite* pReturn = new CCScale9Sprite(); + if ( pReturn && pReturn->initWithFile(file, rect, capInsets) ) + { + pReturn->autorelease(); + return pReturn; + } + CC_SAFE_DELETE(pReturn); + return NULL; +} + +bool CCScale9Sprite::initWithFile(const char* file, CCRect rect) +{ + bool pReturn = this->initWithFile(file, rect, CCRectZero); + return pReturn; +} +CCScale9Sprite* CCScale9Sprite::spriteWithFile(const char* file, CCRect rect) +{ + CCScale9Sprite* pReturn = new CCScale9Sprite(); + if ( pReturn && pReturn->initWithFile(file, rect) ) + { + pReturn->autorelease(); + return pReturn; + } + CC_SAFE_DELETE(pReturn); + return NULL; +} + + +bool CCScale9Sprite::initWithFile(CCRect capInsets, const char* file) +{ + bool pReturn = this->initWithFile(file, CCRectZero, capInsets); + return pReturn; +} + +CCScale9Sprite* CCScale9Sprite::spriteWithFile(CCRect capInsets, const char* file) +{ + CCScale9Sprite* pReturn = new CCScale9Sprite(); + if ( pReturn && pReturn->initWithFile(file, capInsets) ) + { + pReturn->autorelease(); + return pReturn; + } + CC_SAFE_DELETE(pReturn); + return NULL; +} + +bool CCScale9Sprite::initWithFile(const char* file) +{ + bool pReturn = this->initWithFile(file, CCRectZero); + return pReturn; + +} +CCScale9Sprite* CCScale9Sprite::spriteWithFile(const char* file) +{ + CCScale9Sprite* pReturn = new CCScale9Sprite(); + if ( pReturn && pReturn->initWithFile(file) ) + { + pReturn->autorelease(); + return pReturn; + } + CC_SAFE_DELETE(pReturn); + return NULL; +} + +bool CCScale9Sprite::initWithSpriteFrame(CCSpriteFrame* spriteFrame, CCRect capInsets) +{ + CCAssert(spriteFrame != NULL, "Sprite frame must be not nil"); + + CCSpriteBatchNode *batchnode = CCSpriteBatchNode::batchNodeWithTexture(spriteFrame->getTexture(), 9); + bool pReturn = this->initWithBatchNode(batchnode, spriteFrame->getRect(), capInsets); + return pReturn; +} + +CCScale9Sprite* CCScale9Sprite::spriteWithSpriteFrame(CCSpriteFrame* spriteFrame, CCRect capInsets) +{ + CCScale9Sprite* pReturn = new CCScale9Sprite(); + if ( pReturn && pReturn->initWithSpriteFrame(spriteFrame, capInsets) ) + { + pReturn->autorelease(); + return pReturn; + } + CC_SAFE_DELETE(pReturn); + return NULL; +} +bool CCScale9Sprite::initWithSpriteFrame(CCSpriteFrame* spriteFrame) +{ + bool pReturn = this->initWithSpriteFrame(spriteFrame, CCRectZero); + return pReturn; +} + +CCScale9Sprite* CCScale9Sprite::spriteWithSpriteFrame(CCSpriteFrame* spriteFrame) +{ + CCScale9Sprite* pReturn = new CCScale9Sprite(); + if ( pReturn && pReturn->initWithSpriteFrame(spriteFrame) ) + { + pReturn->autorelease(); + return pReturn; + } + CC_SAFE_DELETE(pReturn); + return NULL; +} + +bool CCScale9Sprite::initWithSpriteFrameName(const char* spriteFrameName, CCRect capInsets) +{ + CCAssert(spriteFrameName != NULL, "Invalid spriteFrameName for sprite"); + + CCSpriteFrame *frame = CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName(spriteFrameName); + bool pReturn = this->initWithSpriteFrame(frame, capInsets); + return pReturn; +} + +CCScale9Sprite* CCScale9Sprite::spriteWithSpriteFrameName(const char* spriteFrameName, CCRect capInsets) +{ + CCScale9Sprite* pReturn = new CCScale9Sprite(); + if ( pReturn && pReturn->initWithSpriteFrameName(spriteFrameName, capInsets) ) + { + pReturn->autorelease(); + return pReturn; + } + CC_SAFE_DELETE(pReturn); + return NULL; + +} + +bool CCScale9Sprite::initWithSpriteFrameName(const char* spriteFrameName) +{ + bool pReturn = this->initWithSpriteFrameName(spriteFrameName, CCRectZero); + return pReturn; +} + +CCScale9Sprite* CCScale9Sprite::spriteWithSpriteFrameName(const char* spriteFrameName) +{ + CCScale9Sprite* pReturn = new CCScale9Sprite(); + if ( pReturn && pReturn->initWithSpriteFrameName(spriteFrameName) ) + { + pReturn->autorelease(); + return pReturn; + } + CC_SAFE_DELETE(pReturn); + return NULL; + +} + +CCScale9Sprite* CCScale9Sprite::resizableSpriteWithCapInsets(CCRect capInsets) +{ + CCScale9Sprite* pReturn = new CCScale9Sprite(); + if ( pReturn && pReturn->initWithBatchNode(scale9Image, m_spriteRect, capInsets) ) + { + pReturn->autorelease(); + return pReturn; + } + CC_SAFE_DELETE(pReturn); + return NULL; +} + +CCScale9Sprite* CCScale9Sprite::node() +{ + CCScale9Sprite *pRet = new CCScale9Sprite(); + if (pRet) + { + pRet->autorelease(); + } + return pRet; +} + + +//LabelBMFont - CCRGBAProtocol protocol +void CCScale9Sprite::setColor(const ccColor3B& color3) +{ + m_tColor = color3; + if (scale9Image->getChildren() && scale9Image->getChildren()->count() != 0) + { + CCObject* child; + CCARRAY_FOREACH(scale9Image->getChildren(), child) + { + CCRGBAProtocol* pNode = dynamic_cast(child); + if (pNode) + { + pNode->setColor(m_tColor); + } + } + } +} +const ccColor3B& CCScale9Sprite::getColor(void) +{ + return m_tColor; +} + +void CCScale9Sprite::setOpacity(GLubyte var) +{ + m_cOpacity = var; + + if (scale9Image->getChildren() && scale9Image->getChildren()->count() != 0) + { + CCObject* child; + CCARRAY_FOREACH(scale9Image->getChildren(), child) + { + CCRGBAProtocol* pNode = dynamic_cast(child); + if (pNode) + { + pNode->setOpacity(m_cOpacity); + } + //CCNode* pNode = (CCNode*) child; + //if (pNode) + //{ + // CCRGBAProtocol *pRGBAProtocol = (CCRGBAProtocol *)pNode; + // if (pRGBAProtocol) + // { + // pRGBAProtocol->setOpacity(m_cOpacity); + // } + //} + } + } +} + +/** sets the opacity. + @warning If the the texture has premultiplied alpha then, the R, G and B channels will be modifed. + Values goes from 0 to 255, where 255 means fully opaque. + */ +GLubyte CCScale9Sprite::getOpacity() +{ + return m_cOpacity; +} + + +void CCScale9Sprite::setCapInsets(CCRect capInsets) +{ + m_capInsets = capInsets; +} + +CCRect CCScale9Sprite::getCapInsets() +{ + return m_capInsets; +} + +void CCScale9Sprite::setIsOpacityModifyRGB(bool var) +{ + m_bIsOpacityModifyRGB = var; + if (scale9Image->getChildren() && scale9Image->getChildren()->count() != 0) + { + CCObject* child; + CCARRAY_FOREACH(scale9Image->getChildren(), child) + { + CCRGBAProtocol* pNode = dynamic_cast(child); + if (pNode) + { + pNode->setIsOpacityModifyRGB(m_bIsOpacityModifyRGB); + } + //CCNode* pNode = (CCNode*) child; + //if (pNode) + //{ + // CCRGBAProtocol *pRGBAProtocol = (CCRGBAProtocol *)pNode; + // if (pRGBAProtocol) + // { + // pRGBAProtocol->setIsOpacityModifyRGB(m_bIsOpacityModifyRGB); + // } + //} + } + } +} +bool CCScale9Sprite::getIsOpacityModifyRGB() +{ + return m_bIsOpacityModifyRGB; +} + +NS_CC_END diff --git a/cocos2dx/extensions/CCControlExtension/CCScale9Sprite.h b/cocos2dx/extensions/CCControlExtension/CCScale9Sprite.h new file mode 100644 index 0000000000..10fe960c70 --- /dev/null +++ b/cocos2dx/extensions/CCControlExtension/CCScale9Sprite.h @@ -0,0 +1,281 @@ +// +// CCScale9Sprite.h +// PlantCaring +// +// Created by Jung Sang-Taik on 12. 3. 16.. +// Copyright (c) 2012 Neofect. All rights reserved. +// + +#ifndef __CCScale9Sprite_H__ +#define __CCScale9Sprite_H__ + +#include "CCNode.h" +#include "CCProtocols.h" + + +NS_CC_BEGIN + +class CCSprite; +class CCSpriteBatchNode; +class CCSpriteFrame; + +enum positions +{ + pCentre = 0, + pTop, + pLeft, + pRight, + pBottom, + pTopRight, + pTopLeft, + pBottomRight, + pBottomLeft +}; + +class CC_DLL CCScale9Sprite : public CCNode, CCRGBAProtocol +{ +public: + CCScale9Sprite(); + virtual ~CCScale9Sprite(); + +public: + /** Original sprite's size. */ + CC_SYNTHESIZE(CCSize, m_originalSize, OriginalSize); + /** Prefered sprite's size. By default the prefered size is the original size. */ + + //if the preferredSize component is given as -1, it is ignored + CC_SYNTHESIZE(CCSize, m_preferredSize, PreferredSize); + /** + * The end-cap insets. + * On a non-resizeable sprite, this property is set to CGRectZero; the sprite + * does not use end caps and the entire sprite is subject to stretching. + */ + + /** Opacity: conforms to CCRGBAProtocol protocol */ + CC_PROPERTY(GLubyte, m_cOpacity, Opacity) + /** Color: conforms to CCRGBAProtocol protocol */ + CC_PROPERTY_PASS_BY_REF(ccColor3B, m_tColor, Color) + CC_PROPERTY(CCRect, m_capInsets, CapInsets); + + +protected: + CCRect m_spriteRect; + + CCSpriteBatchNode* scale9Image; + CCSprite* topLeft; + CCSprite* top; + CCSprite* topRight; + CCSprite* left; + CCSprite* centre; + CCSprite* right; + CCSprite* bottomLeft; + CCSprite* bottom; + CCSprite* bottomRight; + + /** Conforms to CocosNodeRGBA protocol. */ + ccColor3B m_sColorUnmodified; + bool m_bIsOpacityModifyRGB; + +public: + + void virtual setContentSize(const CCSize &size); + + virtual bool initWithBatchNode(CCSpriteBatchNode* batchnode, CCRect rect, CCRect capInsets); + /** + * Initializes a 9-slice sprite with a texture file, a delimitation zone and + * with the specified cap insets. + * Once the sprite is created, you can then call its "setContentSize:" method + * to resize the sprite will all it's 9-slice goodness intract. + * It respects the anchorPoint too. + * + * @param file The name of the texture file. + * @param rect The rectangle that describes the sub-part of the texture that + * is the whole image. If the shape is the whole texture, set this to the + * texture's full rect. + * @param capInsets The values to use for the cap insets. + */ + virtual bool initWithFile(const char* file, CCRect rect, CCRect capInsets); + + /** + * Creates a 9-slice sprite with a texture file, a delimitation zone and + * with the specified cap insets. + * + * @see initWithFile:rect:centerRegion: + */ + static CCScale9Sprite* spriteWithFile(const char* file, CCRect rect, CCRect capInsets); + + /** + * Initializes a 9-slice sprite with a texture file and a delimitation zone. The + * texture will be broken down into a 3×3 grid of equal blocks. + * Once the sprite is created, you can then call its "setContentSize:" method + * to resize the sprite will all it's 9-slice goodness intract. + * It respects the anchorPoint too. + * + * @param file The name of the texture file. + * @param rect The rectangle that describes the sub-part of the texture that + * is the whole image. If the shape is the whole texture, set this to the + * texture's full rect. + */ + virtual bool initWithFile(const char* file, CCRect rect); + + /** + * Creates a 9-slice sprite with a texture file and a delimitation zone. The + * texture will be broken down into a 3×3 grid of equal blocks. + * + * @see initWithFile:rect: + */ + static CCScale9Sprite* spriteWithFile(const char* file, CCRect rect); + + /** + * Initializes a 9-slice sprite with a texture file and with the specified cap + * insets. + * Once the sprite is created, you can then call its "setContentSize:" method + * to resize the sprite will all it's 9-slice goodness intract. + * It respects the anchorPoint too. + * + * @param file The name of the texture file. + * @param capInsets The values to use for the cap insets. + */ + virtual bool initWithFile(CCRect capInsets, const char* file); + + /** + * Creates a 9-slice sprite with a texture file. The whole texture will be + * broken down into a 3×3 grid of equal blocks. + * + * @see initWithFile:capInsets: + */ + static CCScale9Sprite* spriteWithFile(CCRect capInsets, const char* file); + + /** + * Initializes a 9-slice sprite with a texture file. The whole texture will be + * broken down into a 3×3 grid of equal blocks. + * Once the sprite is created, you can then call its "setContentSize:" method + * to resize the sprite will all it's 9-slice goodness intract. + * It respects the anchorPoint too. + * + * @param file The name of the texture file. + */ + virtual bool initWithFile(const char* file); + + /** + * Creates a 9-slice sprite with a texture file. The whole texture will be + * broken down into a 3×3 grid of equal blocks. + * + * @see initWithFile: + */ + static CCScale9Sprite* spriteWithFile(const char* file); + + /** + * Initializes a 9-slice sprite with an sprite frame and with the specified + * cap insets. + * Once the sprite is created, you can then call its "setContentSize:" method + * to resize the sprite will all it's 9-slice goodness intract. + * It respects the anchorPoint too. + * + * @param spriteFrame The sprite frame object. + * @param capInsets The values to use for the cap insets. + */ + virtual bool initWithSpriteFrame(CCSpriteFrame* spriteFrame, CCRect capInsets); + + /** + * Creates a 9-slice sprite with an sprite frame and the centre of its zone. + * Once the sprite is created, you can then call its "setContentSize:" method + * to resize the sprite will all it's 9-slice goodness intract. + * It respects the anchorPoint too. + * + * @see initWithSpriteFrame:centerRegion: + */ + static CCScale9Sprite* spriteWithSpriteFrame(CCSpriteFrame* spriteFrame, CCRect capInsets); + /** + * Initializes a 9-slice sprite with an sprite frame. + * Once the sprite is created, you can then call its "setContentSize:" method + * to resize the sprite will all it's 9-slice goodness intract. + * It respects the anchorPoint too. + * + * @param spriteFrame The sprite frame object. + */ + virtual bool initWithSpriteFrame(CCSpriteFrame* spriteFrame); + + /** + * Creates a 9-slice sprite with an sprite frame. + * Once the sprite is created, you can then call its "setContentSize:" method + * to resize the sprite will all it's 9-slice goodness intract. + * It respects the anchorPoint too. + * + * @see initWithSpriteFrame: + */ + static CCScale9Sprite* spriteWithSpriteFrame(CCSpriteFrame* spriteFrame); + /** + * Initializes a 9-slice sprite with an sprite frame name and with the specified + * cap insets. + * Once the sprite is created, you can then call its "setContentSize:" method + * to resize the sprite will all it's 9-slice goodness intract. + * It respects the anchorPoint too. + * + * @param spriteFrameName The sprite frame name. + * @param capInsets The values to use for the cap insets. + */ + virtual bool initWithSpriteFrameName(const char*spriteFrameName, CCRect capInsets); + /** + * Creates a 9-slice sprite with an sprite frame name and the centre of its + * zone. + * Once the sprite is created, you can then call its "setContentSize:" method + * to resize the sprite will all it's 9-slice goodness intract. + * It respects the anchorPoint too. + * + * @see initWithSpriteFrameName:centerRegion: + */ + static CCScale9Sprite* spriteWithSpriteFrameName(const char*spriteFrameName, CCRect capInsets); + /** + * Initializes a 9-slice sprite with an sprite frame name. + * Once the sprite is created, you can then call its "setContentSize:" method + * to resize the sprite will all it's 9-slice goodness intract. + * It respects the anchorPoint too. + * + * @param spriteFrameName The sprite frame name. + */ + virtual bool initWithSpriteFrameName(const char*spriteFrameName); + + /** + * Creates a 9-slice sprite with an sprite frame name. + * Once the sprite is created, you can then call its "setContentSize:" method + * to resize the sprite will all it's 9-slice goodness intract. + * It respects the anchorPoint too. + * + * @see initWithSpriteFrameName: + */ + static CCScale9Sprite* spriteWithSpriteFrameName(const char*spriteFrameName); + + /** + * Creates and returns a new sprite object with the specified cap insets. + * You use this method to add cap insets to a sprite or to change the existing + * cap insets of a sprite. In both cases, you get back a new image and the + * original sprite remains untouched. + * + * @param capInsets The values to use for the cap insets. + */ + CCScale9Sprite* resizableSpriteWithCapInsets(CCRect capInsets); + + + static CCScale9Sprite* node(); + + // optional + + /** sets the premultipliedAlphaOpacity property. + If set to NO then opacity will be applied as: glColor(R,G,B,opacity); + If set to YES then oapcity will be applied as: glColor(opacity, opacity, opacity, opacity ); + Textures with premultiplied alpha will have this property by default on YES. Otherwise the default value is NO + @since v0.8 + */ + virtual void setIsOpacityModifyRGB(bool bValue); + + /** returns whether or not the opacity will be applied using glColor(R,G,B,opacity) or glColor(opacity, opacity, opacity, opacity); + @since v0.8 + */ + virtual bool getIsOpacityModifyRGB(void); + +}; + +NS_CC_END + +#endif // __CCScale9Sprite_H__ diff --git a/cocos2dx/extensions/CCControlExtension/CCSpacer.cpp b/cocos2dx/extensions/CCControlExtension/CCSpacer.cpp new file mode 100644 index 0000000000..8bc52a2138 --- /dev/null +++ b/cocos2dx/extensions/CCControlExtension/CCSpacer.cpp @@ -0,0 +1,23 @@ +#include "CCSpacer.h" + +NS_CC_BEGIN + +CCSpacer* CCSpacer::verticalSpacer(float space) +{ + CCSpacer *pRet = new CCSpacer(); + pRet->init(); + pRet->setContentSize(CCSizeMake(0, space)); + pRet->autorelease(); + return pRet; +} + +CCSpacer* CCSpacer::horizontalSpacer(float space) +{ + CCSpacer *pRet = new CCSpacer(); + pRet->init(); + pRet->setContentSize(CCSizeMake(space, 0)); + pRet->autorelease(); + return pRet; +} + +NS_CC_END diff --git a/cocos2dx/extensions/CCControlExtension/CCSpacer.h b/cocos2dx/extensions/CCControlExtension/CCSpacer.h new file mode 100644 index 0000000000..3e484bf267 --- /dev/null +++ b/cocos2dx/extensions/CCControlExtension/CCSpacer.h @@ -0,0 +1,17 @@ +#ifndef __CCSPACER_H__ +#define __CCSPACER_H__ + +#include "CCLayer.h" + +NS_CC_BEGIN + +class CC_DLL CCSpacer: public CCLayer +{ +public: + static CCSpacer* verticalSpacer(float space); + static CCSpacer* horizontalSpacer(float space); +}; + +NS_CC_END + +#endif \ No newline at end of file diff --git a/cocos2dx/extensions/CCNotificationCenter.cpp b/cocos2dx/extensions/CCNotificationCenter/CCNotificationCenter.cpp similarity index 99% rename from cocos2dx/extensions/CCNotificationCenter.cpp rename to cocos2dx/extensions/CCNotificationCenter/CCNotificationCenter.cpp index e6d4b47c9a..f23826f7d3 100644 --- a/cocos2dx/extensions/CCNotificationCenter.cpp +++ b/cocos2dx/extensions/CCNotificationCenter/CCNotificationCenter.cpp @@ -23,10 +23,12 @@ THE SOFTWARE. ****************************************************************************/ #include "CCNotificationCenter.h" +#include "CCArray.h" #include + using namespace std; -NS_CC_BEGIN; +NS_CC_BEGIN static CCNotificationCenter *s_sharedNotifCenter = NULL; @@ -183,4 +185,4 @@ CCObject *CCNotificationObserver::getObject() return m_object; } -NS_CC_END; +NS_CC_END diff --git a/cocos2dx/extensions/CCNotificationCenter.h b/cocos2dx/extensions/CCNotificationCenter/CCNotificationCenter.h similarity index 96% rename from cocos2dx/extensions/CCNotificationCenter.h rename to cocos2dx/extensions/CCNotificationCenter/CCNotificationCenter.h index a6e22c4fb7..9bd0ba9cf9 100644 --- a/cocos2dx/extensions/CCNotificationCenter.h +++ b/cocos2dx/extensions/CCNotificationCenter/CCNotificationCenter.h @@ -25,9 +25,11 @@ THE SOFTWARE. #ifndef __CCNOTIFICATIONCENTER_H__ #define __CCNOTIFICATIONCENTER_H__ -#include "cocos2d.h" +#include "CCObject.h" -NS_CC_BEGIN; +NS_CC_BEGIN + +class CCArray; class CC_DLL CCNotificationCenter : public CCObject { @@ -77,6 +79,6 @@ private: CC_PROPERTY_READONLY(CCObject *, m_object, Object); }; -NS_CC_END; +NS_CC_END #endif//__CCNOTIFICATIONCENTER_H__ \ No newline at end of file diff --git a/cocos2dx/include/CCActionTween.h b/cocos2dx/include/CCActionTween.h new file mode 100644 index 0000000000..19015bcbcf --- /dev/null +++ b/cocos2dx/include/CCActionTween.h @@ -0,0 +1,79 @@ +/**************************************************************************** +Copyright (c) 2010-2011 cocos2d-x.org +Copyright 2009 lhunath (Maarten Billemont) + +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 __CCACTIONTWEEN_H__ +#define __CCACTIONTWEEN_H__ + +#include "CCActionInterval.h" + +NS_CC_BEGIN + +class CCActionTweenDelegate +{ +public: + virtual ~CCActionTweenDelegate() {} + virtual void updateTweenAction(float value, const char* key) = 0; +}; + +/** CCActionTween + + CCActionTween is an action that lets you update any property of an object. + For example, if you want to modify the "width" property of a target from 200 to 300 in 2 seconds, then: + + id modifyWidth = [CCActionTween actionWithDuration:2 key:@"width" from:200 to:300]; + [target runAction:modifyWidth]; + + + Another example: CCScaleTo action could be rewriten using CCPropertyAction: + + // scaleA and scaleB are equivalents + id scaleA = [CCScaleTo actionWithDuration:2 scale:3]; + id scaleB = [CCActionTween actionWithDuration:2 key:@"scale" from:1 to:3]; + + + @since v0.99.2 + */ +class CCActionTween : public CCActionInterval +{ +public: + /** creates an initializes the action with the property name (key), and the from and to parameters. */ + static CCActionTween* actionWithDuration(ccTime aDuration, const char* key, float from, float to); + + /** initializes the action with the property name (key), and the from and to parameters. */ + bool initWithDuration(ccTime aDuration, const char* key, float from, float to); + + void startWithTarget(CCNode *pTarget); + void update(ccTime dt); + CCActionInterval* reverse(); + + std::string key_; + float from_, to_; + float delta_; +}; + +NS_CC_END + +#endif /* __CCACTIONTWEEN_H__ */ + + diff --git a/cocos2dx/include/CCString.h b/cocos2dx/include/CCString.h index 3cf931cfd6..763de0135c 100755 --- a/cocos2dx/include/CCString.h +++ b/cocos2dx/include/CCString.h @@ -105,6 +105,10 @@ public: std::string m_sString; }; +#define CCStringMake(str) CCString::stringWithCString(str) +#define ccs CCStringMake + + NS_CC_END #endif //__CCSTRING_H__ \ No newline at end of file diff --git a/cocos2dx/include/ccShaders.h b/cocos2dx/include/ccShaders.h index 3fd6d0bd26..aad09944a8 100644 --- a/cocos2dx/include/ccShaders.h +++ b/cocos2dx/include/ccShaders.h @@ -49,6 +49,8 @@ extern const GLchar * ccPositionTextureColorAlphaTest_frag; extern const GLchar * ccPositionTexture_uColor_frag; extern const GLchar * ccPositionTexture_uColor_vert; +extern const GLchar * ccExSwitchMask_frag; + NS_CC_END #endif /* __CCSHADER_H__ */ diff --git a/cocos2dx/include/cocos2d.h b/cocos2dx/include/cocos2d.h index a239081ae6..c6162657e5 100755 --- a/cocos2dx/include/cocos2d.h +++ b/cocos2dx/include/cocos2d.h @@ -69,6 +69,7 @@ THE SOFTWARE. #include "CCActionTiledGrid.h" #include "CCActionGrid3D.h" #include "CCActionGrid.h" +#include "CCActionTween.h" #include "CCLabelBMFont.h" #include "CCParallaxNode.h" #include "CCTileMapAtlas.h" @@ -119,8 +120,6 @@ THE SOFTWARE. #include "CCAccelerometer.h" #include "CCGL.h" -// extensions -#include "extensions/CCNotificationCenter.h" // Shaders #include "CCGLProgram.h" #include "ccGLStateCache.h" @@ -137,6 +136,9 @@ THE SOFTWARE. #include "kazmath/kazmath.h" #include "kazmath/GL/matrix.h" +// extensions +#include "cocos2dExt.h" + namespace cocos2d { const char* cocos2dVersion(); diff --git a/cocos2dx/include/cocos2dExt.h b/cocos2dx/include/cocos2dExt.h new file mode 100644 index 0000000000..a98a783e43 --- /dev/null +++ b/cocos2dx/include/cocos2dExt.h @@ -0,0 +1,7 @@ +#ifndef __COCOS2DEXT_H__ +#define __COCOS2DEXT_H__ + +#include "extensions/CCNotificationCenter/CCNotificationCenter.h" +#include "extensions/CCControlExtension/CCControlExtensions.h" + +#endif /* __COCOS2DEXT_H__ */ diff --git a/cocos2dx/proj.win32/cocos2d-win32.vcproj b/cocos2dx/proj.win32/cocos2d-win32.vcproj index ae0d67f0a9..54fa638a31 100644 --- a/cocos2dx/proj.win32/cocos2d-win32.vcproj +++ b/cocos2dx/proj.win32/cocos2d-win32.vcproj @@ -311,6 +311,10 @@ RelativePath="..\actions\CCActionTiledGrid.cpp" > + + + + @@ -659,6 +667,10 @@ RelativePath="..\include\cocos2d.h" > + + - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + + + + + - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + + + + + getWinSize(); + + // Defines an array of title to create buttons dynamically + CCArray *stringArray = CCArray::arrayWithObjects( + ccs("Hello"), + ccs("Variable"), + ccs("Size"), + ccs("!"), + NULL); + + CCNode *layer = CCNode::node(); + addChild(layer, 1); + + double total_width = 0, height = 0; + + // For each title in the array + CCObject* pObj = NULL; + CCARRAY_FOREACH(stringArray, pObj) + { + CCString* title = (CCString*)pObj; + // Creates a button with this string as title + CCControlButton *button = standardButtonWithTitle(title->getCString()); + button->setPosition(ccp (total_width + button->getContentSize().width / 2, button->getContentSize().height / 2)); + layer->addChild(button); + + // Compute the size of the layer + height = button->getContentSize().height; + total_width += button->getContentSize().width; + } + + layer->setAnchorPoint(ccp (0.5, 0.5)); + layer->setContentSize(CCSizeMake(total_width, height)); + layer->setPosition(ccp(screenSize.width / 2.0f, screenSize.height / 2.0f)); + + // Add the black background + CCScale9Sprite *background = CCScale9Sprite::spriteWithFile("extensions/buttonBackground.png"); + background->setContentSize(CCSizeMake(total_width + 14, height + 14)); + background->setPosition(ccp(screenSize.width / 2.0f, screenSize.height / 2.0f)); + addChild(background); + return true; + } + return false; +} + +CCControlButton *CCControlButtonTest_HelloVariableSize::standardButtonWithTitle(const char * title) +{ + /** Creates and return a button with a default background and title color. */ + CCScale9Sprite *backgroundButton = CCScale9Sprite::spriteWithFile("extensions/button.png"); + CCScale9Sprite *backgroundHighlightedButton = CCScale9Sprite::spriteWithFile("extensions/buttonHighlighted.png"); + + CCLabelTTF *titleButton = CCLabelTTF::labelWithString(title, "Marker Felt", 30); + + titleButton->setColor(ccc3(159, 168, 176)); + + CCControlButton *button = CCControlButton::buttonWithLabelAndBackgroundSprite(titleButton, backgroundButton); + button->setBackgroundSpriteForState(backgroundHighlightedButton, CCControlStateHighlighted); + button->setTitleColorForState(ccWHITE, CCControlStateHighlighted); + + return button; +} + +CCControlButtonTest_Event::CCControlButtonTest_Event() +: m_pDisplayValueLabel(NULL) +{ + +} + +CCControlButtonTest_Event::~CCControlButtonTest_Event() +{ + CC_SAFE_RELEASE_NULL(m_pDisplayValueLabel); +} + +bool CCControlButtonTest_Event::init() +{ + if (CCControlScene::init()) + { + CCSize screenSize = CCDirector::sharedDirector()->getWinSize(); + + // Add a label in which the button events will be displayed + setDisplayValueLabel(CCLabelTTF::labelWithString("No Event", "Marker Felt", 32)); + m_pDisplayValueLabel->setAnchorPoint(ccp(0.5f, -1)); + m_pDisplayValueLabel->setPosition(ccp(screenSize.width / 2.0f, screenSize.height / 2.0f)); + addChild(m_pDisplayValueLabel, 1); + + // Add the button + CCScale9Sprite *backgroundButton = CCScale9Sprite::spriteWithFile("extensions/button.png"); + CCScale9Sprite *backgroundHighlightedButton = CCScale9Sprite::spriteWithFile("extensions/buttonHighlighted.png"); + + CCLabelTTF *titleButton = CCLabelTTF::labelWithString("Touch Me!", "Marker Felt", 30); + + titleButton->setColor(ccc3(159, 168, 176)); + + CCControlButton *controlButton = CCControlButton::buttonWithLabelAndBackgroundSprite(titleButton, backgroundButton); + controlButton->setBackgroundSpriteForState(backgroundHighlightedButton, CCControlStateHighlighted); + controlButton->setTitleColorForState(ccWHITE, CCControlStateHighlighted); + + controlButton->setAnchorPoint(ccp(0.5f, 1)); + controlButton->setPosition(ccp(screenSize.width / 2.0f, screenSize.height / 2.0f)); + addChild(controlButton, 1); + + // Add the black background + CCScale9Sprite *background = CCScale9Sprite::spriteWithFile("extensions/buttonBackground.png"); + background->setContentSize(CCSizeMake(300, 170)); + background->setPosition(ccp(screenSize.width / 2.0f, screenSize.height / 2.0f)); + addChild(background); + + // Sets up event handlers + controlButton->addTargetWithActionForControlEvent(this, menu_selector(CCControlButtonTest_Event::touchDownAction), CCControlEventTouchDown); + controlButton->addTargetWithActionForControlEvent(this, menu_selector(CCControlButtonTest_Event::touchDragInsideAction), CCControlEventTouchDragInside); + controlButton->addTargetWithActionForControlEvent(this, menu_selector(CCControlButtonTest_Event::touchDragOutsideAction), CCControlEventTouchDragOutside); + controlButton->addTargetWithActionForControlEvent(this, menu_selector(CCControlButtonTest_Event::touchDragEnterAction), CCControlEventTouchDragEnter); + controlButton->addTargetWithActionForControlEvent(this, menu_selector(CCControlButtonTest_Event::touchDragExitAction), CCControlEventTouchDragExit); + controlButton->addTargetWithActionForControlEvent(this, menu_selector(CCControlButtonTest_Event::touchUpInsideAction), CCControlEventTouchUpInside); + controlButton->addTargetWithActionForControlEvent(this, menu_selector(CCControlButtonTest_Event::touchUpOutsideAction), CCControlEventTouchUpOutside); + controlButton->addTargetWithActionForControlEvent(this, menu_selector(CCControlButtonTest_Event::touchCancelAction), CCControlEventTouchCancel); + return true; + } + return false; +} + +void CCControlButtonTest_Event::touchDownAction(CCObject *sender) +{ + m_pDisplayValueLabel->setString(CCString::stringWithFormat("Touch Down")->getCString()); +} + +void CCControlButtonTest_Event::touchDragInsideAction(CCObject *sender) +{ + m_pDisplayValueLabel->setString(CCString::stringWithFormat("Drag Inside")->getCString()); +} + +void CCControlButtonTest_Event::touchDragOutsideAction(CCObject *sender) +{ + m_pDisplayValueLabel->setString(CCString::stringWithFormat("Drag Outside")->getCString()); +} + +void CCControlButtonTest_Event::touchDragEnterAction(CCObject *sender) +{ + m_pDisplayValueLabel->setString(CCString::stringWithFormat("Drag Enter")->getCString()); +} + +void CCControlButtonTest_Event::touchDragExitAction(CCObject *sender) +{ + m_pDisplayValueLabel->setString(CCString::stringWithFormat("Drag Exit")->getCString()); +} + +void CCControlButtonTest_Event::touchUpInsideAction(CCObject *sender) +{ + m_pDisplayValueLabel->setString(CCString::stringWithFormat("Touch Up Inside.")->getCString()); +} + +void CCControlButtonTest_Event::touchUpOutsideAction(CCObject *sender) +{ + m_pDisplayValueLabel->setString(CCString::stringWithFormat("Touch Up Outside.")->getCString()); +} + +void CCControlButtonTest_Event::touchCancelAction(CCObject *sender) +{ + m_pDisplayValueLabel->setString(CCString::stringWithFormat("Touch Cancel")->getCString()); +} + + +//CCControlButtonTest_Styling + +bool CCControlButtonTest_Styling::init() +{ + if (CCControlScene::init()) + { + CCSize screenSize = CCDirector::sharedDirector()->getWinSize(); + + CCNode *layer = CCNode::node(); + addChild(layer, 1); + + int space = 10; // px + + double max_w = 0, max_h = 0; + for (int i = 0; i < 3; i++) + { + for (int j = 0; j < 3; j++) + { + // Add the buttons + CCControlButton *button = standardButtonWithTitle(CCString::stringWithFormat("%d",rand() % 30)->getCString()); + button->setAdjustBackgroundImage(false); // Tells the button that the background image must not be adjust + // It'll use the prefered size of the background image + button->setPosition(ccp (button->getContentSize().width / 2 + (button->getContentSize().width + space) * i, + button->getContentSize().height / 2 + (button->getContentSize().height + space) * j)); + layer->addChild(button); + + max_w = MAX(button->getContentSize().width * (i + 1) + space * i, max_w); + max_h = MAX(button->getContentSize().height * (j + 1) + space * j, max_h); + } + } + + layer->setAnchorPoint(ccp (0.5, 0.5)); + layer->setContentSize(CCSizeMake(max_w, max_h)); + layer->setPosition(ccp(screenSize.width / 2.0f, screenSize.height / 2.0f)); + + // Add the black background + CCScale9Sprite *backgroundButton = CCScale9Sprite::spriteWithFile("extensions/buttonBackground.png"); + backgroundButton->setContentSize(CCSizeMake(max_w + 14, max_h + 14)); + backgroundButton->setPosition(ccp(screenSize.width / 2.0f, screenSize.height / 2.0f)); + addChild(backgroundButton); + return true; + } + return false; +} + + +//CCControlButtonTest_Styling + +CCControlButton *CCControlButtonTest_Styling::standardButtonWithTitle(const char *title) +{ + /** Creates and return a button with a default background and title color. */ + CCScale9Sprite *backgroundButton = CCScale9Sprite::spriteWithFile("extensions/button.png"); + backgroundButton->setPreferredSize(CCSizeMake(45, 45)); // Set the prefered size + CCScale9Sprite *backgroundHighlightedButton = CCScale9Sprite::spriteWithFile("extensions/buttonHighlighted.png"); + backgroundHighlightedButton->setPreferredSize(CCSizeMake(45, 45)); // Set the prefered size + + CCLabelTTF *titleButton = CCLabelTTF::labelWithString(title, "Marker Felt", 30); + + titleButton->setColor(ccc3(159, 168, 176)); + + CCControlButton *button = CCControlButton::buttonWithLabelAndBackgroundSprite(titleButton, backgroundButton); + button->setBackgroundSpriteForState(backgroundHighlightedButton, CCControlStateHighlighted); + button->setTitleColorForState(ccWHITE, CCControlStateHighlighted); + + return button; +} + diff --git a/tests/tests/ExtensionsTest/ControlExtensionTest/CCControlButtonTest/CCControlButtonTest.h b/tests/tests/ExtensionsTest/ControlExtensionTest/CCControlButtonTest/CCControlButtonTest.h new file mode 100644 index 0000000000..8f869071db --- /dev/null +++ b/tests/tests/ExtensionsTest/ControlExtensionTest/CCControlButtonTest/CCControlButtonTest.h @@ -0,0 +1,70 @@ +/* + * CCControlButtonTest.h + * + * Copyright (c) 2011 Yannick Loriot + * + * 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 __CCCONTROLBUTTONTEST_H__ +#define __CCCONTROLBUTTONTEST_H__ + +#include "../CCControlScene.h" + +class CCControlButtonTest_HelloVariableSize : public CCControlScene +{ +public: + bool init(); + /** Creates and return a button with a default background and title color. */ + CCControlButton *standardButtonWithTitle(const char * title); + + CONTROL_SCENE_NODE_FUNC(CCControlButtonTest_HelloVariableSize) +}; + +class CCControlButtonTest_Event : public CCControlScene +{ +public: + CCControlButtonTest_Event(); + ~CCControlButtonTest_Event(); + bool init(); + void touchDownAction(CCObject *sender); + void touchDragInsideAction(CCObject *sender); + void touchDragOutsideAction(CCObject *sender); + void touchDragEnterAction(CCObject *sender); + void touchDragExitAction(CCObject *sender); + void touchUpInsideAction(CCObject *sender); + void touchUpOutsideAction(CCObject *sender); + void touchCancelAction(CCObject *sender); +protected: + CC_SYNTHESIZE_RETAIN(CCLabelTTF *, m_pDisplayValueLabel, DisplayValueLabel) + CONTROL_SCENE_NODE_FUNC(CCControlButtonTest_Event) +}; + + +class CCControlButtonTest_Styling : public CCControlScene +{ +public: + bool init(); + CCControlButton *standardButtonWithTitle(const char *title); + CONTROL_SCENE_NODE_FUNC(CCControlButtonTest_Styling) +}; + + +#endif /* __CCCONTROLBUTTONTEST_H__ */ diff --git a/tests/tests/ExtensionsTest/ControlExtensionTest/CCControlColourPicker/CCControlColourPickerTest.cpp b/tests/tests/ExtensionsTest/ControlExtensionTest/CCControlColourPicker/CCControlColourPickerTest.cpp new file mode 100644 index 0000000000..0253fe9de0 --- /dev/null +++ b/tests/tests/ExtensionsTest/ControlExtensionTest/CCControlColourPicker/CCControlColourPickerTest.cpp @@ -0,0 +1,96 @@ +/* + * CCControlColourPickerTest.m + * + * Copyright (c) 2012 Yannick Loriot + * + * 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. + * + */ + +#include "CCControlColourPickerTest.h" + +CCControlColourPickerTest::CCControlColourPickerTest() +{ + +} + +bool CCControlColourPickerTest::init() +{ + if (CCControlScene::init()) + { + CCSize screenSize = CCDirector::sharedDirector()->getWinSize(); + + CCNode *layer = CCNode::node(); + layer->setPosition(ccp (screenSize.width / 2, screenSize.height / 2)); + addChild(layer, 1); + + double layer_width = 0; + + // Create the colour picker + CCControlColourPicker *colourPicker = CCControlColourPicker::colourPicker(); + colourPicker->setColor(ccc3(37, 46, 252)); + colourPicker->setPosition(ccp (colourPicker->getContentSize().width / 2, 0)); + + // Add it to the layer + layer->addChild(colourPicker); + + // Add the target-action pair + colourPicker->addTargetWithActionForControlEvents(this, menu_selector(CCControlColourPickerTest::colourValueChanged), CCControlEventValueChanged); + + + layer_width += colourPicker->getContentSize().width; + + // Add the black background for the text + CCScale9Sprite *background = CCScale9Sprite::spriteWithFile("extensions/buttonBackground.png"); + background->setContentSize(CCSizeMake(150, 50)); + background->setPosition(ccp(layer_width + background->getContentSize().width / 2.0f, 0)); + layer->addChild(background); + + layer_width += background->getContentSize().width; + + m_pColorLabel = CCLabelTTF::labelWithString("#color", "Marker Felt", 30); + m_pColorLabel->retain(); + + m_pColorLabel->setPosition(background->getPosition()); + layer->addChild(m_pColorLabel); + + // Set the layer size + layer->setContentSize(CCSizeMake(layer_width, 0)); + layer->setAnchorPoint(ccp (0.5f, 0.5f)); + + // Update the color text + colourValueChanged(colourPicker); + return true; + } + return false; + +} + +CCControlColourPickerTest::~CCControlColourPickerTest() +{ + CC_SAFE_RELEASE(m_pColorLabel); +} + +void CCControlColourPickerTest::colourValueChanged(CCObject *sender) +{ + CCControlColourPicker* pPicker = (CCControlColourPicker*)sender; + m_pColorLabel->setString(CCString::stringWithFormat("#%02X%02X%02X",pPicker->getColorValue().r, pPicker->getColorValue().g, pPicker->getColorValue().b)->getCString()); +} + + diff --git a/tests/tests/ExtensionsTest/ControlExtensionTest/CCControlColourPicker/CCControlColourPickerTest.h b/tests/tests/ExtensionsTest/ControlExtensionTest/CCControlColourPicker/CCControlColourPickerTest.h new file mode 100644 index 0000000000..3888243cea --- /dev/null +++ b/tests/tests/ExtensionsTest/ControlExtensionTest/CCControlColourPicker/CCControlColourPickerTest.h @@ -0,0 +1,41 @@ +/* + * CCControlColourPickerTest.h + * + * Copyright (c) 2012 Yannick Loriot + * + * 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. + * + */ + +#include "../CCControlScene.h" + +class CCControlColourPickerTest : public CCControlScene +{ +public: + CCControlColourPickerTest(); + virtual ~CCControlColourPickerTest(); + bool init(); + /** Callback for the change value. */ + void colourValueChanged(CCObject *sender); + + CC_SYNTHESIZE_RETAIN(CCLabelTTF*, m_pColorLabel, ColorLabel) + + CONTROL_SCENE_NODE_FUNC(CCControlColourPickerTest) +}; + diff --git a/tests/tests/ExtensionsTest/ControlExtensionTest/CCControlScene.cpp b/tests/tests/ExtensionsTest/ControlExtensionTest/CCControlScene.cpp new file mode 100644 index 0000000000..89160a0934 --- /dev/null +++ b/tests/tests/ExtensionsTest/ControlExtensionTest/CCControlScene.cpp @@ -0,0 +1,96 @@ +/* + * CCControlScene.m + * + * Copyright (c) 2011 Yannick Loriot + * + * 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. + * + */ + +#include "CCControlScene.h" + +#include "CCControlSceneManager.h" + + +CCControlScene::CCControlScene() +: m_pSceneTitleLabel(NULL) +{ + +} + +CCControlScene::~CCControlScene() +{ + CC_SAFE_RELEASE_NULL(m_pSceneTitleLabel); +} + +bool CCControlScene::init() +{ + if (CCLayer::init()) + { + // Get the sceensize + CCSize screensize = CCDirector::sharedDirector()->getWinSize(); + + // Add the generated background + CCSprite *background = CCSprite::spriteWithFile("extensions/background.png"); + background->setPosition(ccp(screensize.width / 2, screensize.height / 2)); + addChild(background); + + // Add the ribbon + CCScale9Sprite *ribbon = CCScale9Sprite::spriteWithFile("extensions/ribbon.png", CCRectMake(1, 1, 48, 55)); + ribbon->setContentSize(CCSizeMake(screensize.width, 57)); + ribbon->setPosition(ccp(screensize.width / 2.0f, screensize.height - ribbon->getContentSize().height / 2.0f)); + addChild(ribbon); + + // Add the title + setSceneTitleLabel(CCLabelTTF::labelWithString("Title", "Arial", 12)); + m_pSceneTitleLabel->setPosition(ccp (screensize.width / 2, screensize.height - m_pSceneTitleLabel->getContentSize().height / 2 - 5)); + addChild(m_pSceneTitleLabel, 1); + + // Add the menu + CCMenuItemImage *item1 = CCMenuItemImage::itemWithNormalImage("Images/b1.png", "Images/b2.png", this, menu_selector(CCControlScene::previousCallback)); + CCMenuItemImage *item2 = CCMenuItemImage::itemWithNormalImage("Images/r1.png", "Images/r2.png", this, menu_selector(CCControlScene::restartCallback)); + CCMenuItemImage *item3 = CCMenuItemImage::itemWithNormalImage("Images/f1.png", "Images/f2.png", this, menu_selector(CCControlScene::nextCallback)); + + CCMenu *menu = CCMenu::menuWithItems(item1, item3, item2, NULL); + menu->setPosition(CCPointZero); + item1->setPosition(ccp(screensize.width / 2 - 100, 37)); + item2->setPosition(ccp(screensize.width / 2, 35)); + item3->setPosition(ccp(screensize.width / 2 + 100, 37)); + + addChild(menu ,1); + return true; + } + return false; +} + +void CCControlScene::previousCallback(CCObject* sender) +{ + CCDirector::sharedDirector()->replaceScene(CCControlSceneManager::sharedControlSceneManager()->previousControlScene()); +} + +void CCControlScene::restartCallback(CCObject* sender) +{ + CCDirector::sharedDirector()->replaceScene(CCControlSceneManager::sharedControlSceneManager()->currentControlScene()); +} + +void CCControlScene::nextCallback(CCObject* sender) +{ + CCDirector::sharedDirector()->replaceScene(CCControlSceneManager::sharedControlSceneManager()->nextControlScene()); +} + diff --git a/tests/tests/ExtensionsTest/ControlExtensionTest/CCControlScene.h b/tests/tests/ExtensionsTest/ControlExtensionTest/CCControlScene.h new file mode 100644 index 0000000000..43e7ed53a1 --- /dev/null +++ b/tests/tests/ExtensionsTest/ControlExtensionTest/CCControlScene.h @@ -0,0 +1,72 @@ +/* + * CCControlScene.h + * + * Copyright (c) 2011 Yannick Loriot + * + * 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 __CCCONTROLSCENE_H__ +#define __CCCONTROLSCENE_H__ + +#include "cocos2d.h" +#include "cocos2dExt.h" + +USING_NS_CC; + + +#define CONTROL_SCENE_NODE_FUNC(controlScene) \ +public: \ +static CCScene* sceneWithTitle(const char * title) \ +{ \ + CCScene* pScene = CCScene::node(); \ + controlScene* controlLayer = new controlScene(); \ + if (controlLayer && controlLayer->init()) \ + { \ + controlLayer->autorelease(); \ + controlLayer->getSceneTitleLabel()->setString(title); \ + pScene->addChild(controlLayer); \ + } \ + else \ + { \ + CC_SAFE_DELETE(controlLayer); \ + } \ + return pScene; \ +} + + +class CCControlScene : public cocos2d::CCLayer +{ +public: + CCControlScene(); + ~CCControlScene(); + bool init(); + // Menu Callbacks + void previousCallback(cocos2d::CCObject* sender); + void restartCallback(cocos2d::CCObject* sender); + void nextCallback(cocos2d::CCObject* sender); + + /** Title label of the scene. */ + CC_SYNTHESIZE_RETAIN(cocos2d::CCLabelTTF*, m_pSceneTitleLabel, SceneTitleLabel) + + CONTROL_SCENE_NODE_FUNC(CCControlScene); +}; + +#endif /* __CCCONTROLSCENE_H__ */ diff --git a/tests/tests/ExtensionsTest/ControlExtensionTest/CCControlSceneManager.cpp b/tests/tests/ExtensionsTest/ControlExtensionTest/CCControlSceneManager.cpp new file mode 100644 index 0000000000..4fc19c49b8 --- /dev/null +++ b/tests/tests/ExtensionsTest/ControlExtensionTest/CCControlSceneManager.cpp @@ -0,0 +1,107 @@ +/* + * CCControlSceneManager.m + * + * Copyright (c) 2011 Yannick Loriot + * + * 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. + * + */ + +#include "CCControlSceneManager.h" +#include "CCControlScene.h" +#include "CCControlButtonTest/CCControlButtonTest.h" +#include "CCControlColourPicker/CCControlColourPickerTest.h" +#include "CCControlSliderTest/CCControlSliderTest.h" +#include "CCControlSwitchTest/CCControlSwitchTest.h" + +USING_NS_CC; + +enum +{ + kCCControlSliderTest = 0, + kCCControlColourPickerTest, + kCCControlSwitchTest, + kCCControlButtonTest_HelloVariableSize, + kCCControlButtonTest_Event, + kCCControlButtonTest_Styling, + kCCControlTestMax +}; + +static const char* s_testArray[] = { + "CCControlSliderTest", + "ControlColourPickerTest", + "ControlSwitchTest", + "ControlButtonTest_HelloVariableSize", + "ControlButtonTest_Event", + "ControlButtonTest_Styling" +}; + +static CCControlSceneManager *sharedInstance = NULL; + + +CCControlSceneManager::CCControlSceneManager() +{ + m_nCurrentControlSceneId = kCCControlSliderTest; +} + +CCControlSceneManager::~CCControlSceneManager() +{ + CC_SAFE_RELEASE(sharedInstance); +} + +CCControlSceneManager * CCControlSceneManager::sharedControlSceneManager() +{ + if (sharedInstance == NULL) + { + sharedInstance = new CCControlSceneManager(); + } + return sharedInstance; +} + +CCScene *CCControlSceneManager::nextControlScene() +{ + m_nCurrentControlSceneId = (m_nCurrentControlSceneId + 1) % kCCControlTestMax; + + return currentControlScene(); +} + +CCScene *CCControlSceneManager::previousControlScene() +{ + m_nCurrentControlSceneId = m_nCurrentControlSceneId - 1; + if (m_nCurrentControlSceneId < 0) + { + m_nCurrentControlSceneId = kCCControlTestMax - 1; + } + + return currentControlScene(); +} + +CCScene *CCControlSceneManager::currentControlScene() +{ + switch (m_nCurrentControlSceneId) + { + case kCCControlSliderTest: return CCControlSliderTest::sceneWithTitle(s_testArray[m_nCurrentControlSceneId]); + case kCCControlColourPickerTest:return CCControlColourPickerTest::sceneWithTitle(s_testArray[m_nCurrentControlSceneId]); + case kCCControlSwitchTest:return CCControlSwitchTest::sceneWithTitle(s_testArray[m_nCurrentControlSceneId]); + case kCCControlButtonTest_HelloVariableSize:return CCControlButtonTest_HelloVariableSize::sceneWithTitle(s_testArray[m_nCurrentControlSceneId]); + case kCCControlButtonTest_Event:return CCControlButtonTest_Event::sceneWithTitle(s_testArray[m_nCurrentControlSceneId]); + case kCCControlButtonTest_Styling:return CCControlButtonTest_Styling::sceneWithTitle(s_testArray[m_nCurrentControlSceneId]); + } + return NULL; +} diff --git a/tests/tests/ExtensionsTest/ControlExtensionTest/CCControlSceneManager.h b/tests/tests/ExtensionsTest/ControlExtensionTest/CCControlSceneManager.h new file mode 100644 index 0000000000..5ea7ee60db --- /dev/null +++ b/tests/tests/ExtensionsTest/ControlExtensionTest/CCControlSceneManager.h @@ -0,0 +1,54 @@ +/* + * CCControlSceneManager.h + * + * Copyright (c) 2011 Yannick Loriot + * + * 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 __CCCONTROLSCENEMANAGER_H__ +#define __CCCONTROLSCENEMANAGER_H__ + +#include "cocos2d.h" +#include "cocos2dExt.h" + +USING_NS_CC; + +class CCControlSceneManager : public cocos2d::CCObject +{ +public: + CCControlSceneManager(); + ~CCControlSceneManager(); + /** Returns the singleton of the control scene manager. */ + static CCControlSceneManager * sharedControlSceneManager(); + + /** Returns the next control scene. */ + cocos2d::CCScene *nextControlScene(); + + /** Returns the previous control scene. */ + cocos2d::CCScene *previousControlScene(); + + /** Returns the current control scene. */ + cocos2d::CCScene *currentControlScene(); + + /** Control scene id. */ + CC_SYNTHESIZE(int, m_nCurrentControlSceneId, CurrentControlSceneId) +}; + +#endif /* __CCCONTROLSCENEMANAGER_H__ */ diff --git a/tests/tests/ExtensionsTest/ControlExtensionTest/CCControlSliderTest/CCControlSliderTest.cpp b/tests/tests/ExtensionsTest/ControlExtensionTest/CCControlSliderTest/CCControlSliderTest.cpp new file mode 100644 index 0000000000..b41c2f07ac --- /dev/null +++ b/tests/tests/ExtensionsTest/ControlExtensionTest/CCControlSliderTest/CCControlSliderTest.cpp @@ -0,0 +1,74 @@ +/* + * CCControlSliderTest.m + * + * Copyright (c) 2011 Yannick Loriot + * + * 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. + * + */ + + +#include "CCControlSliderTest.h" + +CCControlSliderTest::CCControlSliderTest() +{ + +} + +CCControlSliderTest::~CCControlSliderTest() +{ + CC_SAFE_RELEASE_NULL(m_pDisplayValueLabel); +} + +bool CCControlSliderTest::init() +{ + if (CCControlScene::init()) + { + CCSize screenSize = CCDirector::sharedDirector()->getWinSize(); + + // Add a label in which the slider value will be displayed + m_pDisplayValueLabel = CCLabelTTF::labelWithString("Move the slider thumb!" ,"Marker Felt", 32); + m_pDisplayValueLabel->retain(); + m_pDisplayValueLabel->setAnchorPoint(ccp(0.5f, -1.0f)); + m_pDisplayValueLabel->setPosition(ccp(screenSize.width / 2.0f, screenSize.height / 2.0f)); + addChild(m_pDisplayValueLabel); + + // Add the slider + CCControlSlider *slider = CCControlSlider::sliderWithFiles("extensions/sliderTrack.png","extensions/sliderProgress.png" ,"extensions/sliderThumb.png"); + slider->setAnchorPoint(ccp(0.5f, 1.0f)); + slider->setMinimumValue(0.0f); // Sets the min value of range + slider->setMaximumValue(5.0f); // Sets the max value of range + slider->setPosition(ccp(screenSize.width / 2.0f, screenSize.height / 2.0f)); + + // When the value of the slider will change, the given selector will be call + slider->addTargetWithActionForControlEvents(this, menu_selector(CCControlSliderTest::valueChanged), CCControlEventValueChanged); + + addChild(slider); + return true; + } + return false; +} + +void CCControlSliderTest::valueChanged(CCObject *sender) +{ + CCControlSlider* pSlider = (CCControlSlider*)sender; + // Change value of label. + m_pDisplayValueLabel->setString(CCString::stringWithFormat("Slider value = %.02f", pSlider->getValue())->getCString()); +} + diff --git a/tests/tests/ExtensionsTest/ControlExtensionTest/CCControlSliderTest/CCControlSliderTest.h b/tests/tests/ExtensionsTest/ControlExtensionTest/CCControlSliderTest/CCControlSliderTest.h new file mode 100644 index 0000000000..42e3db1f53 --- /dev/null +++ b/tests/tests/ExtensionsTest/ControlExtensionTest/CCControlSliderTest/CCControlSliderTest.h @@ -0,0 +1,39 @@ +/* + * CCControlSliderTest.h + * + * Copyright (c) 2011 Yannick Loriot + * + * 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. + * + */ + +#include "../CCControlScene.h" + +class CCControlSliderTest : public CCControlScene +{ +public: + CCControlSliderTest(); + virtual ~CCControlSliderTest(); + bool init(); + void valueChanged(CCObject *sender); +protected: + CCLabelTTF* m_pDisplayValueLabel; + CONTROL_SCENE_NODE_FUNC(CCControlSliderTest) +}; + diff --git a/tests/tests/ExtensionsTest/ControlExtensionTest/CCControlSwitchTest/CCControlSwitchTest.cpp b/tests/tests/ExtensionsTest/ControlExtensionTest/CCControlSwitchTest/CCControlSwitchTest.cpp new file mode 100644 index 0000000000..8c269c0714 --- /dev/null +++ b/tests/tests/ExtensionsTest/ControlExtensionTest/CCControlSwitchTest/CCControlSwitchTest.cpp @@ -0,0 +1,99 @@ +/* + * CCControlSwitchTest.m + * + * Copyright (c) 2012 Yannick Loriot + * http://yannickloriot.com + * + * 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. + * + */ + +#include "CCControlSwitchTest.h" + + +CCControlSwitchTest::~CCControlSwitchTest() +{ + CC_SAFE_RELEASE(m_pDisplayValueLabel); +} + +bool CCControlSwitchTest::init() +{ + if (CCControlScene::init()) + { + CCSize screenSize = CCDirector::sharedDirector()->getWinSize(); + + CCNode *layer = CCNode::node(); + layer->setPosition(ccp (screenSize.width / 2, screenSize.height / 2)); + addChild(layer, 1); + + double layer_width = 0; + + // Add the black background for the text + CCScale9Sprite *background = CCScale9Sprite::spriteWithFile("extensions/buttonBackground.png"); + background->setContentSize(CCSizeMake(80, 50)); + background->setPosition(ccp(layer_width + background->getContentSize().width / 2.0f, 0)); + layer->addChild(background); + + layer_width += background->getContentSize().width; + + m_pDisplayValueLabel = CCLabelTTF::labelWithString("#color" ,"Marker Felt" ,30); + m_pDisplayValueLabel->retain(); + + m_pDisplayValueLabel->setPosition(background->getPosition()); + layer->addChild(m_pDisplayValueLabel); + + // Create the switch + CCControlSwitch *switchControl = CCControlSwitch::switchWithMaskSprite + ( + CCSprite::spriteWithFile("extensions/switch-mask.png"), + CCSprite::spriteWithFile("extensions/switch-on.png"), + CCSprite::spriteWithFile("extensions/switch-off.png"), + CCSprite::spriteWithFile("extensions/switch-thumb.png"), + CCLabelTTF::labelWithString("On", "Arial-BoldMT", 16), + CCLabelTTF::labelWithString("Off", "Arial-BoldMT", 16) + ); + switchControl->setPosition(ccp (layer_width + 10 + switchControl->getContentSize().width / 2, 0)); + layer->addChild(switchControl); + + switchControl->addTargetWithActionForControlEvents(this, menu_selector(CCControlSwitchTest::valueChanged), CCControlEventValueChanged); + + // Set the layer size + layer->setContentSize(CCSizeMake(layer_width, 0)); + layer->setAnchorPoint(ccp (0.5f, 0.5f)); + + // Update the value label + valueChanged(switchControl); + return true; + } + return false; +} + +void CCControlSwitchTest::valueChanged(CCObject* sender) +{ + CCControlSwitch* pSwitch = (CCControlSwitch*)sender; + if (pSwitch->getIsOn()) + { + m_pDisplayValueLabel->setString("On"); + } + else + { + m_pDisplayValueLabel->setString("Off"); + } +} + diff --git a/tests/tests/ExtensionsTest/ControlExtensionTest/CCControlSwitchTest/CCControlSwitchTest.h b/tests/tests/ExtensionsTest/ControlExtensionTest/CCControlSwitchTest/CCControlSwitchTest.h new file mode 100644 index 0000000000..d97a272398 --- /dev/null +++ b/tests/tests/ExtensionsTest/ControlExtensionTest/CCControlSwitchTest/CCControlSwitchTest.h @@ -0,0 +1,39 @@ +/* + * CCControlSwitchTest.h + * + * Copyright (c) 2012 Yannick Loriot + * http://yannickloriot.com + * + * 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. + * + */ + +#include "../CCControlScene.h" + +class CCControlSwitchTest : public CCControlScene +{ +public: + virtual ~CCControlSwitchTest(); + bool init(); + /** Callback for the change value. */ + void valueChanged(CCObject* sender); + CCLabelTTF *m_pDisplayValueLabel; + CONTROL_SCENE_NODE_FUNC(CCControlSwitchTest) +}; + diff --git a/tests/tests/ExtensionsTest/ExtensionsTest.cpp b/tests/tests/ExtensionsTest/ExtensionsTest.cpp index 6cf615ec41..bfb4308276 100644 --- a/tests/tests/ExtensionsTest/ExtensionsTest.cpp +++ b/tests/tests/ExtensionsTest/ExtensionsTest.cpp @@ -1,18 +1,19 @@ #include "ExtensionsTest.h" #include "../testResource.h" -#include "NotificationCenterTest.h" - +#include "NotificationCenterTest/NotificationCenterTest.h" +#include "ControlExtensionTest/CCControlSceneManager.h" enum { - MAX_COUNT = 1, + MAX_COUNT = 2, LINE_SPACE = 40, kItemTagBasic = 1000, }; static const std::string testsName[MAX_COUNT] = { - "NotificationCenterTest" + "NotificationCenterTest", + "CCControlButtonTest" }; //////////////////////////////////////////////////////// @@ -51,6 +52,13 @@ void ExtensionsMainLayer::menuCallback(CCObject* pSender) case 0: runNotificationCenterTest(); break; + case 1: + { + CCControlSceneManager* pManager = CCControlSceneManager::sharedControlSceneManager(); + CCScene* pScene = pManager->currentControlScene(); + CCDirector::sharedDirector()->replaceScene(pScene); + } + break; default: break; } diff --git a/tests/tests/ExtensionsTest/NotificationCenterTest.cpp b/tests/tests/ExtensionsTest/NotificationCenterTest/NotificationCenterTest.cpp similarity index 95% rename from tests/tests/ExtensionsTest/NotificationCenterTest.cpp rename to tests/tests/ExtensionsTest/NotificationCenterTest/NotificationCenterTest.cpp index d80949069e..ac18f4aefb 100644 --- a/tests/tests/ExtensionsTest/NotificationCenterTest.cpp +++ b/tests/tests/ExtensionsTest/NotificationCenterTest/NotificationCenterTest.cpp @@ -1,5 +1,6 @@ #include "NotificationCenterTest.h" -#include "ExtensionsTest.h" +#include "../ExtensionsTest.h" +#include "extensions/CCNotificationCenter/CCNotificationCenter.h" #define kTagLight 100 #define kTagConnect 200 diff --git a/tests/tests/ExtensionsTest/NotificationCenterTest.h b/tests/tests/ExtensionsTest/NotificationCenterTest/NotificationCenterTest.h similarity index 93% rename from tests/tests/ExtensionsTest/NotificationCenterTest.h rename to tests/tests/ExtensionsTest/NotificationCenterTest/NotificationCenterTest.h index 84ca0ea591..90f361bcfe 100644 --- a/tests/tests/ExtensionsTest/NotificationCenterTest.h +++ b/tests/tests/ExtensionsTest/NotificationCenterTest/NotificationCenterTest.h @@ -2,7 +2,6 @@ #define __NOTIFICATIONCENTERTEST_H__ #include "cocos2d.h" -#include "ExtensionsTest.h" class NotificationCenterTest : public cocos2d::CCLayer {